I am trying to post a dictionary using ajax. But I have run into some problems with json and "]" character.
Here's example of my code (javascript):
var dict = {"id":"patient","where":{"name[~]":"J"}};
$.post("./ajax.php",{data:dict},function(data){
});
And ajax.php (this file just deals with the json encoded data in $_POST array):
$where = $_POST["data"]["where"];
Basically i am trying to send json format message to php, and there I want to process with the data.
I tried whole bunch of combination with json_encode and decode on php side, also JSON.stringify() on javascript side, tried to use escape characters with the right bracket.
But when I dump $_POST["data]["where] there's value "J" with key "name[~" and not "name[~]". Right bracket disappears from the key.
Anyone having any advice, please?
Thanks for help, I've been struggling with this for hours...
//EDIT: I've figured out, that everything i place after "]" disappears from the key. So the key transforms from "name[~]asdf" -> "name[~"...
When you provide an object to the jQuery AJAX functions, it URL-encodes it. jQuery is sending the data.where parameter as:
data[where][name[~]]=J
and PHP apparently can't deal with nested brackets like that; it just matches the [ before name with the next ].
Probably jQuery needs to double-encode this property name to protect it, but obviously it doesn't.
The workaround is to encode dict as JSON, and decode it in PHP. JS:
$.post("./ajax.php",{data: JSON.stringify(dict)},function(data){
PHP:
$data = json_decode($_POST['data'], true);
$where = $data['where'];
var_dump($where);
I have tried JSON.stringify in junction with json_decode and the result looks fine:
JS
$.ajax({
url: './ajax.php',
method: 'post',
data: "data="+JSON.stringify(dict)
});
PHP
json_decode($_POST['data'], true);
I think you should have specified the JSON is associative, setting $assoc parameter to true. See this.
You can also send data as a JSON (not string) and then read the raw post data using php://input stream and use json_decode with $assoc set to true on the retrieved data yourself; since it appears that out-of-the-box method compiled into PHP is inefficient.
Another solution that worked for me:
JS
$.ajax({
url: 'recAjax.php',
method: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(dict)
});
PHP
var_dump(json_decode(file_get_contents('php://input'), true));
json_decode, php://input
Related
I am parsing a float data from my controller to a js function via JSON, following is the JS function:
function fetchbal(){
$.ajax({
url: "/count/ew",
dataType: "json"
}).success(function(data){
$('#bal').html(JSON.stringify(data.sum));
});
}
but I am getting an output with quotes around the figure.
I have checked the value returned by the controller, and it is not passing the quotes, so it has to do something with JSON stringify!
for cross checking this is the controller(Symfony):
$repo = $em->getRepository('SystemBundle:Admin');
$user = $repo->findOneBy(array('id'=>$session->get('id')));
$sum = $user->getWallet();
return new JsonResponse(array('sum'=>$sum));
here $sum is fetching a float val from the db (doctrine)
I have also tried this post's solution but it instead stops displaying the value on the page
I don't want quotes to be displayed around the fetched value, any suggestion for that? also ask for more elaboration if you want.
Json stringify adds the quotes, since it's intended to serialize data before sending them to server.
You probably want to invoke json.parse, or even just do nothing, as jquery will parse the json for you.
I need to write this:
$.ajax({
url:webPath + '/ajax/list_filter.php',
data:{form:serializedForm,userId:localStorage['userId'],code:localStorage['code'],refreshType:refreshType},
type:'POST'
}).done(function(data){
//do stuff with data
});
Now pay attention to serializedForm which comes from, as the name says, a serialised form. The problem is that the serializedForm is passed as a string and PHP doesn't parse it in a correct way, it sees the other variables sent correctly and form as only one big string.
How can I solve this problem, still using the very handy jQuery .serialize() method?
Personally, I would just change:
data:{form:serializedForm,userId:localStorage['userId'],code:localStorage['code'],refreshType:refreshType}
to
data:serializedForm+'&userId='+encodeURIComponent(localStorage.userId)+'&code='+encodeURIComponent(localStorage.code)+'&refreshType='+encodeURIComponent(refreshType)
This should keep your data out of arrays within arrays, as well.
#SOLVED
As explained by James M. Lay, I should change my content-type from application/x-www-form-urlencoded to application/json
it implied in an error because it seems that only UrlEnconded types generates POST arrays in server side (at least in PHP). So I had to change the way I receive/deal with the request in my server script
$json = file_get_contents('php://input'); //yes. php://input
if($json) $params = json_decode($json,true);
else $params = $_POST;
I also had to make a few changes in the Javascript code to check the content-type and generate different strings. If it's JSON I just use JSON.stringify
//string to use in the 'send' method
this.getParametersString = function(){
if(this.contentType == 'application/json'){
return JSON.stringify(this.parameters);
}else{}
}
I got a question
I`m building a function that receive parameters to write a list of parameters and send it by POST
The problem is that we can't send special characters, such is +
So I tried to use the function encodeURIComponent to encode them to a URI friendly string.
There comes another problem: if the parameter received is an object, I am loop through the attributes, checking if it is another object or a string, if it is an object, loop again, otherwise encode it.
But it is returning an object of encoded strings. I have to make the object become a string to send it, and for that purpose I use JSON.stringify. It decodes the encoded string. So %2B becomes + again and It is not sent to the server via POST.
on the other hand If I use stringify first and the encodeURIComponent it generates signs like " and { } that shouldn't be encoded and the string is not a well written JSON
How do you that? Is that a way without using jQuery? Do I have to build my own stringify function?!
im using the following and i have no issues
encodeURIComponent(JSON.stringify(object_to_be_serialised))
I am making a simple web app, in one part of it, the result of SQL query is to be passed from PHP to JavaScript with AJAX.
This is the SQL Query:
$meta_query = mysql_fetch_row(mysql_query("SELECT * from meta WHERE user_id='$user_id'"));
This is how I pass it to JavaScript
var_dump($meta_query);
This is what I am getting at JavaScript (as a string):
array(30) {[0]=>string(1) "3"["id"]=>string(1) "3"[1]=>string(2) "14"["user_id"]=>string(2) "14"[2]=>string(10) "29-06-2014"["date"]=>string(10) "29-06-2014"[3]=>string(1) "0"["present"]=>string(1) "0"[4]=>string(1) "0"["future"]=>string(1) "0"}
How, how do I convert this into a proper JavaScript object so that the output is something like:
{"id":"3","user_id":"14","date":"29-06-2014","Present":0,"Future":0}
How do I convert data from the first format to the second in JavaScript? Or should I do something else entirely in PHP to get the data out in some other format? Or should I convert the data to the required format somehow in PHP?
You might want to use
echo json_encode($meta_query);
from php side toy should convert php array to json object using
<?php echo json_encode($array)
here is tutorial how to do this
Don't forget to put in your jquery request dataType: "json"
I have a javascript object which I want to pass to a PHP file while using jQuery's ajax-implementation.
I've tried to directly pass it to it but this doesn't work, because it isn't escaped or anything. I've tried to use JSON.stringify but this isn't working for me either.
Is there a way to 'serialize' a javascript object to a POST-string?
Update, I'm using JSON.stringify() again. The result is:
The result of JSON.stringify() is:
{\"label\":\"Borne, Overijssel, Nederland\",\"value\":\"Borne, Overijssel, Nederland\",\"geocode\":{\"address_components\":[{\"long_name\":\"Borne\",\"short_name\":\"Borne\",\"types\":[\"locality\",\"political\"]},{\"long_name\":\"Borne\",\"short_name\":\"Borne\",\"types\":[\"administrative_area_level_2\",\"political\"]},{\"long_name\":\"Overijssel\",\"short_name\":\"OV\",\"types\":[\"administrative_area_level_1\",\"political\"]},{\"long_name\":\"Nederland\",\"short_name\":\"NL\",\"types\":[\"country\",\"political\"]}],\"formatted_address\":\"Borne, Nederland\",\"geometry\":{\"bounds\":{\"ca\":{\"b\":52.2832527,\"f\":52.3151634},\"ea\":{\"b\":6.688658900000064,\"f\":6.801415300000031}},\"location\":{\"Ya\":52.3002366,\"Za\":6.753725799999984},\"location_type\":\"APPROXIMATE\",\"viewport\":{\"ca\":{\"b\":52.2832527,\"f\":52.3151634},\"ea\":{\"b\":6.688658900000064,\"f\":6.801415300000031}}},\"types\":[\"locality\",\"political\"]}}
When I do a json_decode it results to NULL. Any suggestions?
If your passing an object as a string thats in legitmate JSON format, to PHP try using
json_decode() on the php side of things. Example
<?php
$ojb = json_decode($_POST['my_json_string']);
?>
What this will do is turn your object into an array or object depending on which version of PHP you are using, and in some cases the object will turn into an array with multiple objects in it.. example:
Array(
[0] stdClass (
'key1'=>'val1'
'key2'=>'val2'
'key3'=>'val3'
)
)
which I know the above isnt a good representation, but its a representation in the lines there of.
After that PHP side you can work with the variable $ojb like any other array/object.
$something = $ojb[0]->key1;
EDIT
I notice your string now. The fact that the quotes are escaped in the string, breaks the fact that its a JSON object, with that you can do one of two things.. Either just pass the object to PHP through your post/get as is, without running it through strigify or.. you could try on the PHP side, if there is a need to strigfy it..
$ojb = stripslashes($_POST['my_json_string']); $ojb = json_decode($ojb);
which will attempt to remove the slashes from the quotes, before putting it through the decode process.
http://php.net/manual/en/function.json-decode.php
You can specify a raw body of the POST request. The raw data would be the result of a JSON.stringify call which would mean that you should specify an appropriate Content-Type header.
$.ajax(url, {
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
processData: false // prevent escaping and other processing
});
You can then deserialize the object in PHP like this:
$json = file_get_contents('php://input');
$data = json_decode($json);
The raw request body is mapped onto the special path php://input