3

How do I create a javascript object from an AJAX response?

This is what I'm currently doing:

PHP:

<?
echo '{status:"1", site:"example.com"}';
?>

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?

4 Answers 4

5

Set 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.

Sign up to request clarification or add additional context in comments.

Comments

2

You can also try something like this:

PHP

<?
echo json_encode(array("status"=>1,"site"=>"example.com"));
?>

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);
}
});

Comments

1

instead of making your own json notation use php built in json_encode

<?php
    return json_encode(array('status' => '1', 'site' => 'example.com'));
?>

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

Comments

0

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.com"}')

But this will work as you expect:

eval('({status:"1", site:"example.com"})')

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.