I have a php class( ajax called) which returns json_encode data as
["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"]
I'm trying to do jquery.parseJSON(data) and it's giving me error "Unexpected number", what am I doing wrong?
You are trying to parse an array, not a string. JSON.parse (and any other JSON parser) expects a string, therefore Array.toString is called and your call becomes jquery.parseJSON("2016-02-08 09:00:00.000,2016-02-15 09:00:00.000")
//Error "Unexpected number", toString is called on the input array
JSON.parse(["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"])
// Returns an array object
JSON.parse('["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"]') // OK
If you are using the return of json_encode inline, you don't need to parse it, just assign it to a variable, JavaScript will do the parsing.
var dates = <?= json_encode($dates) ?>;
If you are using jQuery the data will typically already be parsed into JSON in the callback, if it doesn't, you can force it using dataType: 'json'
var x = '["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"]';
$.parseJSON(x) // return an array
jQuery does the decoding for you when you perform the AJAX call with the JSON dataType:
$.ajax({
url: 'mypage.php',
data: mydata,
dataType: 'json'
})
.done(function(response) {
// Response is an array, not a JSON string, jQuery decoded it.
// Demo:
console.log(response[0]); // "2016-02-08 09:00:00.000"
console.log(response[1]); // "2016-02-15 09:00:00.000"
}
This is explained in the jQuery docs:
dataType
...
"json": Evaluates the response as JSON and returns a JavaScript object.
So, don't use jquery.parseJSON on the result. It has already been done for you.
Related
I am new to JSON.
In JS, I create an array of values like so:
var arrFields = $("td>.frmInput").map(function(){
return {
id: this.id,
value: $(this).val()
};
}).get();
I then AJAX them to the server like so:
$.ajax({
type: "POST",
url: "ajax/ax_all_ajax_fns.php",
data: "Fields=" +JSON.stringify(arrFields),
success: function(recd) {
alert(recd);
}
});
Note that there is a mixture of strings, plus the JSON.stringified (?) array. (There are additional string values sent, so data must remain as string.)
On the PHP side, I need to turn the received Fields string into an associative array.
Doing this:
$jsonAsStr_Fields = $_POST['Fields'];
die($jsonAsStr_Fields);
Returns this text string in the alert():
[{"id":"rateDriver","value":"Jacques Villeneuve"},{"id":"rateCar","value":"Chev"}]
Doing this:
$arrFields = json_decode($jsonAsStr_Fields, TRUE);
$driver = $arrFields['rateDriver'];
$car = $arrFields['rateCar'];
$tire = $arrFields['rateTire'];
die('Driver: [' .$driver. '] Car: [' .$car. '] Tire: [' .$tire. ']');
Returns this:
Driver: [ ] Car: [ ] Tire: [ ]
How can I turn the $jsonAsStr_Fields string into an assoc array, and thereby output the correct values to my alert?
Do this instead for your creation of values:
var arrFields = {};
$("td>.frmInput").each(function(){
arrFields[this.id] = $(this).val();
});
This will create an object, when JSON-stringified, that looks like this:
{"rateDriver":"Jacques Villeneuve", "rateCar":"Chev"}
Which seems to be the format you want to use in your PHP code.
You have an array of associative arrays and your arrays don't have the specified props, rateDriver for example is the value of the first array's element's id:
$driver = $arrFields[0]['id'];
$car = $arrFields[1]['id'];
For seeing the array's contents you use the famous var_dump function.
From the Author:
For those who haven't fully understood what solved this problem.
The underlying problem was that the stringified JSON was being modified en route (immed after hit Submit button en route to the PHP side) by the AJAX. All quote marks were being escaped, which made it impossible for that string to work with json_encode.
This was discovered by grabbing the value of the received data once it hit the PHP side:
$jsonAsStr_Fields = $_POST['Fields'];
die($jsonAsStr_Fields);
And alerting the received data in the AJAX success function:
success: function(recd) {
alert(recd);
}
Both of the above were described in the OP.
However, because I assumed this was an unrelated problem, I "fixed" the string displayed in the alert() box when I posted the question. Lesson to be learned: don't help - just post what you actually see.
It really displayed like this:
{\"id\":\"rateDriver\",\"value\":\"Jacques Villeneuve\"}
but I wrote that it displayed like this:
{"id":"rateDriver","value":"Jacques Villeneuve"}
Of course, the json_decode() PHP function had no idea what to do with the backslashes, so the string did not convert.
Solution was to use str_replace() on the received JSON string over on the PHP side, to resolve the problem, like this:
str_replace("\\", "", $_POST['Fields']);
I'm trying to pass an array in an ajax request, but apparently it doesn't work...
$.post("process.php", array,
function(data) {
document.getElementById("output").innerHTML = JSON.parse(data);
});
My question is, how to use the data sent in the process file?
The array is built like that: [key (0/1/2...)] => ["prod_id"]. The id varies.
I read somewhere using $_POST["key"]; would work, but it doesn't.
It'd be even better if I could just get the array as is in the process file.
process.php (really basic - just to check wether it's working or not.):
<?php
print($_POST["test"]);
?>
Try to pass {data: array} instead of array. The AJAX call expects an object.
You need to build an Object of array elements. for example:
You can also try like:
{ 'key[]': [1, 2, 3] }
OR
{ key: [1,2,3] }
Read more about $.post()
In order to receive data in php you need to send key/value pairs, however you are only sending a value.
You receive in php with $_POST[key] which will return the value for that key.
JS:
$.post("process.php", {myAray: array}, function(data) {
$("#output").html(data);
});
php
$array= $_POST['myArray'];
To return this array from php as text just to test your ajax can use var_dump( $_POST) or var_dump($array);
If you intend to receive JSON in response from server, you do not need to use JSON.parse , jQuery will parse json internally. However you would need to add "json" as dataType argument to $.post
$.post("process.php", {myAray: array}, function(data) {
/* loop over json here*/
},'json');
if you want to pass an array, you have to "prepare" the key as following:
{'key[]' : ['value1', 'value2', 'value3']}
the same way you'd do it, when you want to pass an array in a form and set the name-attribute to "key[]".
I cannot convert JS object to exact string, my code:
jsonObj['payment_value']=100.10;
jsonObj['payment_date']="2012-06-15";
jsonObjStr = JSON.stringify(jsonObj);
alert(jsonObjStr);
$.post("test", jsonObjStr.toString(), function(output){
alert(output);
});
first alert displays:
{"payment_date":"2012-06-15","payment_value":100.1}
and in function test (i'm using codeigniter framework) it should print "payment_date" and "payment_value", code like this:
echo $this->input->post("payment_value");
echo $this->input->post("payment_date");
which is equvalent in "clear" php to:
echo $_POST["payment_value"];
echo $_POST["payment_date"];
but second alert displays clear string.
If I put
{"payment_date":"2012-06-15","payment_value":100.1}
instead of jsonObjStr.toString() it works fine
Does anyone knows how to fix it WITHOUT using json_decode? I need to have posted values in this format, not in other array
So i need to convert jsonObjStr exact to string (something inversely to function eval())
Thank in advice
According to $.post docs, second argument should be map or query string:
map example:
{
"payment_date":"2012-06-15",
"payment_value":100.1
}
query string example:
'payment_date=2012-06-15&payment_value=100.1'
When you use JSON.stringify, then you get:
'{"payment_date":"2012-06-15","payment_value":100.1}'
which is invalid query string. So the solution is: do not stringify anything, pass the object itself as 2nd argument:
jsonObj['payment_value']=100.10;
jsonObj['payment_date']="2012-06-15";
$.post("test", jsonObj, function(output){
alert(output);
});
I get a string with the following output from json_encode:
["images\/zara\/shoes\/thumbnail",
"images\/hermes\/shoes\/thumbnail",
"images\/hermes\/shoes\/thumbnail"]
I attempt to parse it with the below code, but it gives me an error:
var listofshoes = JSON.parse(data);
for (var i in listofshoes) {
$('#pgwrapid').append( $("<p>").text(listofshoes[i]));
}
ERROR: JSON.parse: unexpected character [Break On This Error] return window.JSON.parse( data );`
How do I prevent this?
It's not because of backslashes. JSONLint parses it correctly. It's because JSON.parse() must have string parameter and you are passing an array. https://developer.mozilla.org/En/Using_native_JSON#Parsing_JSON.C2.A0strings
To convert a JSON string into a JavaScript object, you simply pass the
JSON into the JSON.parse() method, like this:
var jsObject = JSON.parse(jsonString);
Also mentioned here: JSON.parse unexpected character error.
Example:
var data = ["images\/zara\/shoes\/thumbnail",
"images\/hermes\/shoes\/thumbnail",
"images\/hermes\/shoes\/thumbnail"];
data_string = JSON.stringify(data);
console.log(JSON.parse(data_string)); // no error
console.log(JSON.parse(data)); // will show error
$str = '["images\/zara\/shoes\/thumbnail",
"images\/hermes\/shoes\/thumbnail",
"images\/hermes\/shoes\/thumbnail"]';
$rst = json_decode($str);
//print_r($rst);
foreach($rst as $val) {
echo $val;
echo "<br>";
}
Try This.
I suspect there's an AJAX call somewhere in the omitted code. jQuery AJAX methods decode JSON strings for you, so JSON.parse() is not necessary.
Here is my PHP code, it's getting a listing of collections from mongodb
$list = $db->dbname->listCollections();
$result = array();
$i=0;
foreach ($list as $thiscollection) {
$result[$i++] = $thiscollection->getName();
}
echo json_encode( $result );
I do console.log in the callback and this is what I see.
["fruits", "dogs", "cars", "countries"]
The problem is that this is a string, not an array. I need to iterate through these values. How an I make this into a real object or get php to give me json rather than php array so I can use parseJSON on it.
Thanks.
js:
$.post('/ajax-database.php', function (data) {
console.log($.parseJSON(data));
$.each(data, function (key, value) {
console.log(value);
});
});
I see you are using jquery, if you want data to come back to you as a json object you need to do 1 of 2 things.
add header("Content-Type: application/json") to your php file, this will tell jquery to convert it to a json object instead of as text
Add a forth parameter to your $.post,
$.post('/ajax-database.php', function (data) {
console.log($.parseJSON(data));
$.each(data, function (key, value) {
console.log(value);
});
}, "json");
that will tell jquery to call your error handler if its NOT json, like if your php code fails and outputs html instead. You really should use $.ajax, i have no idea why anyone uses $.post, you can't do ANY meaningful error handling.
JSON is strings. If you want to be able to iterate over it then you need to decode it.