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.
Related
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 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 am using jQuery and I want to gather the data from a form and then manipulate it BEFORE I serialize it. The form object itself is a very complex beast that contains all of its descendant DOM nodes, etc, etc.
Basically, what I want is the serialized data but in an unserialized format.
I can do something like this:
function unser(serdata) {
var data = {};
var str = unescape(serdata);
var pairs = str.split('&');
for (var i=0;i<pairs.length;i++) {
var pp = pairs[i].split('=');
data[pp[0]] = pp[1];
}
return data;
}
And then when I do this:
unser( $('form').serialize() );
I have an object of the data, which I can then manipulate and then serialize it and send it to the backend server. But surely, there must be a jQuery way of doing this that I am not seeing?
It would almost make sense to have something like:
$('form').formData();
Is there a way to get form data before jQuery.serialize()
You want $('form').serializeArray(). You can then modify the result, and when you're done, pass it to $.param
$.param($('form').serializeArray())
Is equivalent to:
$('form').serialize()
#Eric's answer above is correct.
However, if you've got the serialised data (such as from a form post or from a query string), this plugin will allow you to decode and use the data.
I found jQuery.deserialize, a jQuery plugin that is the inverse to jQuery.serialize() which you could use like this:
$('form').deserialize( $('form').serialize() );
It supports deserialising complex types, such as arrays (i.e. multiple selects and checkbox arrays - see the documentation on jQuery.serialize() for examples of these) and objects (see http://benalman.com/projects/jquery-misc-plugins/#serializeobject).
Since a query string is the same as form data (application/x-www-form-urlencoded), you can also use this plugin to properly decode query strings.
I have the need to send an array of ID's to my server-side in the form of a JSON Object.I am using a dropdownlist where multiple values can be selected to do an action with them.
To get them in an array, I've used:
var selectedArray = [];
var selectObj = document.getElementById('addedList');
var i=0;
var count=0;
for(i=0;i<selectObj.options.length;i++){
selectedArray[count] = selectObj.options[i].value;
count++;
}
Now the question is, I need to get those ID's to the server.
I've always thought of sending it like a JSON object, since it has a variable amount of parameters. As far as I found out, you can convert a JS object to JSON.
Now I do have a few questions:
Could you give me an example of how to convert it? There seem to be a million ways, one of them being JSON.stringify(jsObj);. My object would simply consist of an array of values. As far as I know this would be an example:
{ array : ["value1","value2","value3"] }
Another question is:
How can I send this using jQuery? Can I send a JSON object to the server using $.getJSON? (This uses $.GET under the hood), or do I need to use $.POST ?
Now I've just been trying, but can't get it out...
$.getJSON code
$.getJSON("removerequest.htm",{ ids: JSON.stringify(selectedArray) }, function(data){
$('#removerequestdiv').text('');
$('#removerequestdiv').append('<select name="addedList">');
for(var index in data){
$('#removerequestdiv').append('<option value="' + data[index].id + '">' + data[index].voornaam + data[index].familienaam + '</option>');
}
$('#removerequestdiv').append('</select>');
});
The $.getJSON() routine is for fetching JSON-encoded content from the server. Your problem is the opposite: you want to send it to the server.
You should understand the terminology here. There's no such thing really as a "JSON object" in Javascript. It's just a Javascript object of some sort, and there's nothing special about it in that sense. What you want to do is serialize the Javascript object into a single string. That string is your parameter you'll send to the server, and the server will deserialize that string back into an object (in the context of whatever language your server code is using).
Thus, when you call JSON.stringify(obj), what you get is just a string. Passing such a string back to the server is no different than passing any other string; it's just a parameter. Use $.post() to post it, or you can even just stuff it into the value of a simple form input element and post a form the old-fashioned way.
I currently have the following javascript array:
var stuffs = ['a', 'b'];
I pass the above to the server code using jQuery's load:
var data = {
'stuffs': stuffs
};
$(".output").load("/my-server-code/", data, function() {
});
On the server side, if I print the content of request.POST(I'm currently using Django), I get:
'stuffs[]': [u'a', u'b']
Notice the [] at the prefix of the variable name stuffs. Is there a way to remove that [] before it reaches the server code?
This is default behavior in jQuery 1.4+...if you want the post to be &stuffs=a&stuffs=b instead of &stuffs[]=a&stuffs[]=b you should set the traditional option to true, like this:
$.ajaxSetup({traditional: true});
Note this affects all requests... which is usually what you want in this case. If you want it to be per-request you should use the longer $.ajax() call and set traditional: true there. You can find more info about traditional in the $.param() documentation.
When an array is submitted using a GET request, through a form or AJAX, each element is given the name of the array, followed by a pair of optionally empty square brackets. So the jQuery is generating the url http://example.com/get.php?stuff[]=a&stuff[]=b. This is the only way of submitting an array, and the javascript is following the standard.
POST requests work in exactly the same way (unless the json is sent as one long json string).
In PHP, this is parsed back into the original array, so although the query string can be a little strange, the data is recieved as it was sent. $_GET['stuff'][0] works correctly in PHP.
I'm not sure how Django parses query strings.
The [] indicates that the variable is an array. I imagine that the appending of the [] to your variable name is Python/Django's way of telling you it is an array. You could probably implement your own print function which does not show them.