I want to post an array using Jquery Ajax to php. Is this possible ?
Thanks
EDIT:
I tried following :
type: "POST",
url: "path",
data: "styles=" + strstyles + "&templateId=" + custTempId, //strstyles is an associative array
dataType: "json",
success: function (data) { .....}
but, styles hold no data. I spent a lot of time, before adding data type to the declaration. What can be the reason for "styles" being posted as null ?
Second Edit
I want to post style sheet dom object and save the class names and properties to DB. With the above edit, adding datatype did not help. I think it is b'coz the string is not in json format as follows -
{"a":1,"b":2,"c":3,"d":4,"e":5}
As the my string has double quotes, it is not following the format, and I think that's the reason, I'm getting an empty array. How can I handle this ?
-
1hi buddy, use JSON.stringify to create json strings from objects, see my solution in few minutesAyaz Alavi– Ayaz Alavi2010年08月27日 09:16:37 +00:00Commented Aug 27, 2010 at 9:16
4 Answers 4
With jQuery it is very easy:
$.ajax({
type: "POST",
url: location.href,
data: data,//data is array
dataType: "json",
success : function () {
// Something after success
}
});
2 Comments
You can use in following way too
$.ajax({
type: "POST",
url: location.href,
data: ({'data[]' : array}),//array is array
dataType: "json",
success : function () {
// Something after success
}
});
Comments
if you don't want to use JSON, PHP can automatically create arrays from Html forms so you could do something like this:
type: "POST",
url: "path",
data: "styles[key1]=" + strstyles.val1 + "&styles[key2]=" + strstyles.val2 + ... + "&templateId=" + custTempId
...
that is if you want to have an associative array in php, but if you want just an array you could do
data: "styles[]=" + strstyles.val1 + "&templateId=" + custTempId
Comments
In POST call you dont use & , So your code should be something like
type: "POST",
url: "path",
data: {styles: strstyles , templateId: custTempId}, //strstyles is an associative array
dataType: "json",
success: function (data) { .....}
is that point clear? So coming to my solution,
- you should download JSON parser from http://www.mediafire.com/?x6k3su7bbdrcta8.
- Create object strstylesOBJ, code:
var strstylesOBJ = {}; insert your
strstylesarray intostrstylesOBJand stringify it then pass to it in your post callstrstylesOBJ.styles = strstyles; strstyles = JSON.stringify(strstylesOBJ);In PHP code you refecth your array using
$strstyles = json_decode($_POST['styles']);do
var_dump($strstyles)and please tell what was the output.
regards
Ayaz Alavi