Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.post and json_encode is returning a string with quotes around it

Tags:

json

jquery

ajax

I'm using jQuery's $.post call and it's returning a string with quotes around it. The quotes are being added by the json_encode line. How do I stop this from adding quotes? Am I missing something in my $.post call?

$.post("getSale.php", function(data) {
    console.log('data = '+data); // is showing the data with double quotes
}, 'json');
like image 432
Catfish Avatar asked Nov 24 '10 03:11

Catfish


2 Answers

json_encode() returns a string. From the json_encode() documentation:

Returns a string containing the JSON representation of value.

You need to call JSON.parse() on data, which will parse the JSON string and turn it into an object:

$.post("getSale.php", function(data) {
    data = JSON.parse(data);
    console.log('data = '+data); // is showing the data with double quotes
}, 'json');

However, since you are concatenating the string data = to data in your console.log() call, what will be logged is data.toString(), which will return the string representation of your object, which will be [object Object]. So, you are going to want to log data in a separate console.log() call. Something like this:

$.post("getSale.php", function(data) {
    data = JSON.parse(data);
    console.log('data = '); // is showing the data with double quotes
    console.log(data);
}, 'json');
like image 200
Alex Avatar answered Oct 13 '22 19:10

Alex


What exactly are you trying t do with the data that you're receiving? If you're simply trying to obtain a particular key of the JSON message, i.e. the "name" in "{"name":"sam"}" then (assuming you have a JSON Object and not a JSON Array) you'd be able to use data.name regardless of the double quotes.

like image 32
sahhhm Avatar answered Oct 13 '22 19:10

sahhhm