Jump to content

Best Pratice for Returning and Filtering Values from AJAX'd PHP Script?


eysikal

Recommended Posts

Consider the following:

 

<?php
//daytime_check.php
    $is_daytime = false;
    if ($is_daytime) {
        echo '1';
    } else {
        echo '0';
    }
?>

 

==================================================================================

 

// javascript/jQuery
$.ajax({
    type: 'POST',
    url: 'daytime_check.php',
    success: function(response) {
        if(response == false) {
            alert('Goodnight, brother');
        } else {
            alert('Day\'s a wastin, brother');
        }            
    },
    error: function() {
        //handle error
    }
});

 

This is how I have heretofore handled the responses from my AJAX'd PHP scripts. I'm hoping someone out there can give me some hints on a better way, as this current method feels pretty clunky.

 

Especially clunky is handling the "filtering" of the PHP script's output on the JS side. For example:

 

In this case, the response from PHP is going to be a JS

var response ='0'

. Now one can't simply use if

(!response)...

in JS to filter, because apparently

!response

evaluates to false, while, interestingly,

response == false

evaluates to

true

. Something to do with type juggling, I suppose.

 

Since the only way I can return things from PHP is in text (echo statements), I can't return proper true/false values to filter on when I get to the JS side. Is there a better way to handle this?

 

I hope this made at least a little sense.

Since the only way I can return things from PHP is in text (echo statements), I can't return proper true/false values to filter on when I get to the JS side.

You can. The problem is that jQuery might not be able to tell the difference between text and JSON.

echo "true";

Then in the JavaScript pass

dataType: "json"

to .ajax().

 

That's one option. The other is pure PHP:

header("Content-Type: application/json");

// ...

echo "true";

The application/json tells jQuery that the result is JSON and not a string.

Here is a neat solution provided by an intelligent former co-worker.

 

Return values from your PHP scripts in the following manner:

 

<?php
    // To return an error
    echo json_encode(
        array(
            'success' => false,
            'message' => '[error message here]',
        )
    );
    // To return a successful response
    echo json_encode(
        array(
            'success' => true,
            'response' => [return value here],
        )
    );

 

This way, we can easily do logic on the JS side:

 

$.ajax({
    type: 'POST',
    url: 'ajax_example.php',
    success: function(response) {
                 response = JSON.parse(response);
                 if (!response.success) {
                     alert(response.message);
                 } else {
                     console.log(response.response);    
                 }
    },
    error: function() {
               //handle error
               alert('error doing ajax, mate');
           }
    });       

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.