Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Getting an understandable result back to my AJAX call from my PHP function?

I have a PHP function server-side that looks like this:

function isHandleAvailable($displayname) {
    $res = user::getRow(
        "SELECT `id` FROM `users` WHERE `displayname` = :displayname",
        array(':displayname' => $displayname)
    );
    if ($res) {
        $res = 'Got a row!';
    } else {
        $res = 'No row :(';
    }

    echo $res;
}

and it's used to determine if a display name is already being used on the site. This function is called by the following JavaScript:

function checkHandleAvailability(displayName, callback) {
    $.ajax({
        type: 'POST',
        url: '/users/isHandleAvailable',
        data: { displayname: displayName }
    })
        .done(function(data, textStatus, jqXHR) {
            isHandleAvailable = data;
        })
        .fail(function() {
            isHandleAvailable = false;
        })
        .always(function() { callback(); });
}

however, the data and jqXHR.responseText are both an empty string. I know the PHP code is working because I put it into a basic test.php page and got the expected strings echoed to the screen.

Why isn't the result getting back to the .done function?

Upvotes: 1

Views: 104

Answers (2)

Mangiucugna
Mangiucugna

Reputation: 1762

Try to add the option "dataType: 'string'", by default $.ajax try to guess the content of the response and maybe this time is wrong.

But, as suggested by Matt Kantor, the best practice is to encode your response with some structured protocol like JSON or XML.

Upvotes: 0

Matt Kantor
Matt Kantor

Reputation: 1754

You'll need to output the value, just like non-AJAX webpage content.

If you want to communicate structured/typed data to the client (as opposed to some text or HTML), you should probably use JSON. PHP comes with a handy json_encode function to serialize PHP values to JSON.

The way to do the output might differ depending on your framework and whether you think this should count as a "view", but a simple way would be to just echo what you want to hand off to the client right from the controller method.

You should also set the Content-type header to application/json to let the client know you're sending JSON over the wire. Again, the specifics of where/how you should do that depend on your framework and architectural preferences. The easy but possibly less maintainable way is to just set the header in the controller method.

So, putting that all together, try this:

function isHandleAvailable($displayname) {
    $handleIsAvailable = user::getRow(
        "SELECT `id` FROM `users` WHERE `displayname` = :displayname",
        array(':displayname' => $displayname)
    ) == null;

    // This has to happen before any output.
    header('Content-type: application/json');

    echo json_encode($handleIsAvailable);
}

Upvotes: 1

Related Questions