Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Thursday, October 27, 2016

Reading php-encoded JSON in Javascript

Reading php-encoded JSON in Javascript


I have created a JSON object in php using json_encode and am attempting to display certain values of that object in javascipt through AJAX. I have no issue receiving the response from php but am getting 'undefined' when I try to access any value of the response using JSON notation.

Code snippet:

if (xmlhttp.readyState==4 && xmlhttp.status==200)  {     var response = xmlhttp.responseText;     alert(response);     alert(response.data);  }  

Output:

{"data":[{"cheese":"pork"},{"cheese":"chicken"}]} // Yes, I'm hungry right now.  undefined  

EDIT: Thanks everybody for the responses. Wish I could give you all a check mark but I have selected the most helpful response.

Answer by phihag for Reading php-encoded JSON in Javascript


You need to parse the JSON:

if (xmlhttp.readyState==4 && xmlhttp.status==200)  {     var jdoc = JSON.parse(xmlhttp.responseText);     alert(jdoc.data[0].cheese);  }  

Include json2.js in older browsers.

Answer by Molecular Man for Reading php-encoded JSON in Javascript


You have to convert response into js object.

The simpliest way is to use eval():

eval('var result = ' +response);  alert(result.data);  

Answer by Londeren for Reading php-encoded JSON in Javascript


var response = xmlhttp.responseText  

this is not a JSON object. This is plain text. Use var myObject = eval('(' + myJSONtext + ')'); for example to get JSON (eval is evil:)

Answer by marc for Reading php-encoded JSON in Javascript


You have to parse the json. This can be done through a simple call to eval, but this can only be done if you absolutely trust the returning server as he can make your script execute everything.

 var data = eval('('+response+')');  

The way I would recommand if to use json2.js, a small javascript library that ius faster and will handle the parsing for you.

var data = JSON.parse(response);  

It can be acquire from https://github.com/douglascrockford/JSON-js

Answer by Alex L for Reading php-encoded JSON in Javascript


Looks like response is plain text. Try this:

var response = xmlhttp.responseText;  var data = new Function("return "+xmlhttp.responseText)();  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.