Reputation: 2788
I have a form input generated with PHP like given below:
<input type="text" name="category[type]">
<input type="text" name="category[name]">
In PHP, it's ok. But I need to send it with javascript by Ajax. I use jQuery and tried with function $.serializeArray()
in data.
'form': $(this).closest('form').serializeArray(),
But the result what I got is:
array (7)
0 => array (2)
name => "category[type]" (11)
value => "my_type"
Best result what I need is:
array
category => array
type => my_type
or anything similar what I can work with.
Any idea?
Thank in advance for your help
Upvotes: 0
Views: 95
Reputation: 2788
It seems to be better approach get data with serializeArray
and modify them before sending.
Custom data must represent the same object as form object which is returned serializeArray.
.
var formData = $(this).closest('form').serializeArray();
formData.push({ name: 'customParam', value: 'my_val'});
Notice: If you put serializeArray
directly to the ajax data. It will work correctly.
It might help someone.
Upvotes: 0
Reputation: 6766
Use .on method to attach the submit
event handler to your form. This will trigger when you click on a submit button within your form.
You want to pass $(this).serializeArray()
directly into data
setting.
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'script.php'
data: $(this).serializeArray(),
success: function (res) {
// handle the response you get back from the PHP
}
})
});
Upvotes: 2