I am doing an ajax request through post that contains a forms variables.
the data for the ajax request looks like
data : {
somevar1: 'someval1',
somevar2: 'someval2',
somevar3: 'someval3',
somevar4: 'someval4',
form: FORMDATA
}
as you can see, as well as the basic form data I am also passing through some other data.
this means that I cannot use jquery .serialize()
I am wanting to end up with something that I can send through so on the other side I can just do
$_POST['form']['fieldname']
is there a built in function do do this?
or what would I need to do to create one?
the possibility of running a function on the form that does something like
function postArray(form){
var data = {};
var name, value = null;
$(form).children('textarea, input, select'){
name = this.name;
data.name = $(this).val();
}
return data;
}
over the form could work.
and having
data : {
somevar1: 'someval1',
somevar2: 'someval2',
somevar3: 'someval3',
somevar4: 'someval4',
form: postArray(form)
}
would it work?
I could use
.serializeArray();
But on the other side I get
Array
(
[0] => Array
(
[name] => name1
[value] => val1
),
[1] => Array
(
[name] => name2
[value] => val2
)
...
[8] => Array
(
[name] => name8
[value] => val8
)
)
Which is close, but that requires me to either
a: loop over the array and convert it to what I want
b: every time i use it loop over it to find the right key
You can encode your form data as JSON using
serializeArray
andJSON.stringify
.serializeArray
gives you an array like so:so you would not be able to access the data on the server side with
$data['fieldname']
. To convert the array to an object (so that you could access the data like you want to), have a look at Convert form data to JavaScript object with jQuery.Of course you can also just use your own function (which seems to do something similar if you fix the errors‡), but you still have to use
JSON.stringify
:In your PHP script, you can then use
json_decode
to get the form data:‡ Here is a fixed version (updated from you comment, don't use
for...in
to loop over arrays):If you want to fix it for elements with
[]
in the name, you have to process those elements manually and put them in an array:but this assumes that you don't have field names like
field
andfield[]
.