using onSuccess(transport, json) and header("Content-type: application/x-json")

217 views
Skip to first unread message

liketofindoutwhy

unread,
Oct 6, 2008, 9:54:46 PM10/6/08
to Prototype & script.aculo.us
For some reason, no matter what I use

new Ajax.Request(url, {
method: 'get',

onSuccess: function(transport, json){
//alert(Object.inspect(json));
alert(json ? Object.inspect(json) : "no JSON object");
},
...
});

and then in PHP, when i use

header('Content-type: application/x-json');
echo '{ "status" : 1 }';


the ajax will come back showing "no JSON object"

it doesn't matter if i use text/x-json or text/json or application/
json

and it is prototype 1.6.0.3...
is there something wrong the header or the formatting of the content?
thanks.

jason maina

unread,
Oct 6, 2008, 11:52:26 PM10/6/08
to prototype-s...@googlegroups.com
Try this:
//php
$myArray=array('status'=>1);
$jsonData=json_encode($myArray);
return $jsonData;
Dont forget the header.

//javascript/prototype
jsonResponse=eval('('+response.responseText+')');
Access data as array:
var myVal=jsonResponse[0].status;

Hope that helps

--
Sent from Gmail for mobile | mobile.google.com

jason maina

unread,
Oct 7, 2008, 12:56:31 AM10/7/08
to prototype-s...@googlegroups.com
Something I forgot json in your case will recieve the header while
transport the XHR object. So will have to evaluate transport & not
json

On 10/7/08, liketofindoutwhy <liketofi...@gmail.com> wrote:
>

--

T.J. Crowder

unread,
Oct 7, 2008, 1:51:43 AM10/7/08
to Prototype & script.aculo.us
Hi,

You're looking for the JSON in the second parameter to onSuccess, but
that's the result of evaling the X-JSON *header*. From
http://www.prototypejs.org/api/ajax/options:
"...all callbacks (except onException) are invoked with two
parameters: the XMLHttpRequest object and the result of evaluating the
X-JSON response header, if any (can be null)."

You're sending JSON back as the body of the response, not in an X-JSON
header. If you do that, use transport.responseJSON in your onSuccess
handler:

onSuccess: function(transport){
alert(transport.responseJSON ?
Object.inspect(transport.responseJSON) : "no JSON object");
},

Or if you really want to send an X-JSON header (where the body of the
response is something else), you'll have to modify your PHP to do
that.

HTH,
--
T.J. Crowder
tj / crowder software / com

On Oct 7, 2:54 am, liketofindoutwhy <liketofindout...@gmail.com>
wrote:
Reply all
Reply to author
Forward
0 new messages