user965951
user965951

Reputation: 167

How does a PHP script send an JSON Ajax response to Dojo's xhrGet?

I just started using dojo and I'm onto using Ajax in dojo via xhrGet.

I understand that whatever you "echo" in PHP is what is returned as the Ajax result, however how does this work with JSON?

Does the PHP script echo javascript code that is then directly accessed from the function called by xhrGet?

I'm trying to have a PHP script retrieve data from the database, populate three arrays, and make them available in my javascript code, all with xhrGet.

Thanks!

Upvotes: 1

Views: 1023

Answers (2)

Xeoncross
Xeoncross

Reputation: 57234

Most JavaScript libraries wrap a callback around the AJAX request. I'm not sure about Dojo, but jQuery adds a callback param to the URL when it's sent.

Then, when the server responds it triggers that callback which calls your callback to handle the result.

As for the actual server side stuff, the server usually just prints the JSON encoded string and passes along an extra header letting the browser know what type of content it is.

<?php
$rows = $db->fetch($sql);

header('Content-type: application/json');
print json_encode($rows);
?>

Upvotes: 0

SeanCannon
SeanCannon

Reputation: 77986

Set the header with PHP before you echo:

<?php
    header('Content-type: application/json');
    echo '{"myJsonKey":"myJsonVal"}';

For your specific case, you'd do something like this:

<?php
    $my_records_array = fetch_records($some_criteria);
    $my_records_json  = json_encode($my_records_array);

    header('Content-type: application/json'); 
    echo $my_records_json;

Upvotes: 2

Related Questions