#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))
Related
I'm facing an issue when converting ODATA string into JSON while posting on my Dynamics CRM.
When I'm trying to serialize that way:
var phoneCallAssociationJsonData = '{'
+'"#odata.id" : "https://contoso.crm4.dynamics.com/api/data/v8.1/phonecalls('+ phoneCallUid +')"'
+'}';
And serialize it in the request like that: JSON.stringify(phoneCallAssociationJsonData);
I get a BAD REQUEST response. But When I use POSTMAN to post data and I copy the following JSON:
{"#odata.id" : "https://contoso.crm4.dynamics.com/api/data/v8.1/phonecalls(12a59ec0-76b5-e611-80ed-5065f38a8ad1)"}
It works perfectly.
Does someone know if there is a special way way to serialize string with odata format ?
I've tried to create a javascript object but adding a object.#odata.id is not possible because # is not an allowed character.
Firstly, rather than creating a string, which you then stringify, create an OBJECT
var phoneCallAssociationJsonData = {
"#odata.id" : "https://contoso.crm4.dynamics.com/api/data/v8.1/phonecalls("+ phoneCallUid +")"
};
then
JSON.stringify(phoneCallAssociationJsonData);
should now work
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
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
I'm sending a json object through ajax to a java servlet.
The json object is key-value type with three keys that point to arrays and a key that points to a single string. I build it in javascript like this:
var jsonObject = {"arrayOne": arrayOne, "arrayTwo": arrayTwo, "arrayThree": arrThree, "string": stringVar};
I then send it to a java servlet using ajax as follows:
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.setRequestHeader("Connection", "close");
var jsonString = jsonObject.toJSONString();
httpRequest.send(jsonString);
This will send the string to my servlet, but It isn't showing as I expect it to. The whole json string gets set to the name of one of my request's parameters. So in my servlet if I do request.getParameterNames(); It will return an enumeration with one of the table entries' key's to be the entire object contents. I may be mistaken, but my thought was that it should set each key to a different parameter name. So I should have 4 parameters, arrayOne, arrayTwo, arrayThree, and string. Am I doing something wrong or is my thinking off here? Any help is appreciated.
Thanks
When you set the content-type to application/x-www-form-urlencoded, you're telling the server that the request content is going to be a string of the form "param1=value1¶m2=value2...". But your actual content is just a single value; the x-www-form-urlencoded content type has nothing to do with JSON. If you want to pass the request as JSON, you'll need to set the content-type to application/json and then have a JSON parser on the server side to parse it and extract the key/value pairs.
Alternatively, you could keep the x-www-form-urlencoded type, loop through your JSON object and, for every key/value pair, serialize the value as a JSON string and URL-encode, and use that to build up a request string that looks like:
arrayOne=<arrayOne JSON string>&arrayTwo=<arrayTwo JSON String>&...
It is the expected behavior, you're converting your object to string (using toJSONString) and its is being send as a request parameter. You may want to parse the JSON value on the serverside using libraries such as Jackson, Jettison or XStream see http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
I have
var pageData = {
query: null,
pageNumber: 0,
pageSize: 30};
When I make an ajax get:
$.ajax({
type: 'GET',
url: '/Ajax/GetSuggestions',
data: pageData,
success: function (response) {}
The request show in firebug: http://localhost:31198/Ajax/GetSuggestions?query=null&pageNumber=1&pageSize=30
At server side (ASP .NET MVC3), I received query = null in string, not null data(what I need).
How can I fix it without using delete method of javascript to remove null value?
If you want your URL to look like this:
http://localhost:31198/Ajax/GetSuggestions?query=&pageNumber=1&pageSize=30
Then, you have to set query property to "" (an empty string).
If you want your URL to look like this:
http://localhost:31198/Ajax/GetSuggestions?&pageNumber=1&pageSize=30
Then, you have to remove to remove the query property from the pageData object by either not putting it there in the first place or by using delete pageData.query to remove it.
There are multiple ways to send data "over the wire". The standard one for sending form data to the server is url encoding. A second way is to send a JSON object. (A transmission detail is that the JSON would be url-encoded. But that's only a transmission detail.) A third way is to use XML.
As #jfriend00 shows in his answer, there are multiple, hacky ways to send a "null" value via url encoding. You should use the one which your server side stack best supports.
Re: why the string "null" What's happening is that the Javascript value null needs to be converted to a value that can be sent via HTTP ("over the wire"). The default way to do that is to use the string null. The problem is that the url encoding scheme only sends things as strings. So it doesn't have an automatic way to send the value null vs teh string null. The usual work around is an empty string, "".
But this can also raise an issue on your server-side since the string "" is not equal to the value null in most computer languages. So you will need to make appropriate comparisons or conversions. Eg does "" == false in your server software?
Using JSON for the data encoding is the other technique.
JSON directly supports a null value. It is is supposed to transmit it as null. See JSON spec (not so obvious, search the page for null) and IBM docs
The way you receive null data in JSON is the bareword null. If you're using JSON, note that you do not receive the string null, you receive the JSON keyword null. Your JSON receiver/decoder should know the difference. If it doesn't, then it is faulty.
When the request string is being built in jQuery, it's using every property on the data object it can find.
All you need to do to remove a property is delete the property:
delete pageData.query;