How do I create a javascript object from an AJAX response?
This is what I'm currently doing:
PHP:
<?
echo '{status:"1", site:"example"}';
?>
JS:
success:function(data_response){
var object = eval( data_response );
console.log(object.url);
}});
I'm currently getting "undefined" on the console. How is this done?
How do I create a javascript object from an AJAX response?
This is what I'm currently doing:
PHP:
<?
echo '{status:"1", site:"example."}';
?>
JS:
success:function(data_response){
var object = eval( data_response );
console.log(object.url);
}});
I'm currently getting "undefined" on the console. How is this done?
Share Improve this question asked Sep 15, 2012 at 3:42 lisovaccarolisovaccaro 34k99 gold badges270 silver badges423 bronze badges4 Answers
Reset to default 5Set the dataType
of the ajax request to json
, and the data_response
will be an object already parsed to.
Or you could use $.getJSON
also.
You can also try something like this:
PHP
<?
echo json_encode(array("status"=>1,"site"=>"example."));
?>
Ajax call here with your params in JS
$.ajax({
url: url, // your url where the php is
dataType: 'json',
data: data, //send data
//callback
success: function(data_response){
alert(data_response.status);
alert(data_response.site);
}
});
instead of making your own json notation use php built in json_encode
<?php
return json_encode(array('status' => '1', 'site' => 'example.'));
?>
Also you're logging object.url
but it should be object.site
.
You may also need to set your header to return application/json
instead of text/html
. This can be done also by specifying the dataType
type parameter in your AJAX request to json
If you want to parse a raw object string using eval
, you must wrap the object notation code in parens:
var object = eval( '(' + data_response + ')' );
The following will choke the parser:
eval('{status:"1", site:"example."}')
But this will work as you expect:
eval('({status:"1", site:"example."})')
Edit: Please note, I don't necessarily endorse this solution. This is just so you understand what's needed if you're going to use eval
.