ive tried 10 different solutions to this issue on stackoverflow and none of them work, heres the issue, i need to post a array via ajax to a url simple right?
the array comes from post values like this $_post[xxx] which i store in a var.
i mocked up a js function, that has the same error, instead of passing the array i just included as a var in the function, problem is the data is not gettin posted to the url. pastebin link: http://pastebin.com/8ivWqJ8g
function generateImage() {
var Imagedata = [];
Imagedata['id'] = 1;
Imagedata['type'] = 'some type';
var url = '';
$.ajax({
url: url,
processData: false,
dataType: 'JSON',
data: JSON.stringify(Imagedata) ,
method:'POST',
async: false
});
Named properties of arrays do not get serialised when you convert the data to JSON.
Arrays are supposed to hold an ordered set of values, not an arbitrary set of name:value pairs.
Use a plain object ({}
) not an array.
Asides:
Don't use processData: false
unless you are passing something that isn't a string or an object to data
(e.g. a FormData
object). Since you are passing a string, it is harmless, but pointless. If you were passing an object (which you probably should be, see below), it would break things.
Don't use async: false
. It is deprecated, and harms the user experience (since it locks up the JS thread until the response arrives).
If you want to populate PHP's $_POST
then don't format your data as JSON. Pass the object directly to data:
without using JSON.stringify
.
If you do want to make a JSON formatted request, then don't forget to set the contentType
.
function generateImage() {
var Imagedata = {
id: 1,
type: "some type"
};
var url = '';
$.ajax({
url: url,
dataType: 'JSON',
data: Imagedata,
method: 'POST'
});
// or …
$.ajax({
url: url,
dataType: 'JSON',
contentType: "application/json",
data: JSON.stringify(Imagedata),
method: 'POST'
});
}
data should be an Object like this:
$.ajax({
url: 'http://...',
dataType: 'JSON',
data: {id: 1, type: 'some type'} ,
method:'POST',
async: false
});