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');
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');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With