Reputation: 563
I need to submit an html form via .ajax with jQuery. When I submit it normally, not via ajax, everything works great. It is in switching to ajax that I encounter problems.
The form has changing number of inputs. (One each for each user in a particular group, groups can have a differing number of users). So I name the inputs like so:
<input type="hidden" name="<?php echo 'sampleA['. $i .']'; ?>" value="sampleValue" />
Where $i is a counter so the inputs are sampleA['1'] and sampleA['2'] and so on.
I have another input for each user that is done the same way, which we can call sample2['1'] and so forth.
So with php I just get these 2 arrays and run through them with a similar counter and insert them to my db as need. This all works well. But I need to make it ajax.
How do I pass those two arrays via jQuery's .ajax function to a php script, and then how do I handle it in php?
I've tried using .serialize on my form, but that serializes both inputs on all the users into one array and I have been unable to de-serialzie that correctly on the php side of things.
The following doesn't work, but I will include it here to show you what I've been doing:
function updateOnCourt() {
var thearray = $('#sub-form').serialize();
$.ajax({
url: 'sub-update.php',
method: 'POST',
data: thearray,
success: function() {
alert('Success: '+thearray);
}
});
}
and then in my PHP script:
<?php
$size = count($_POST['thearray']);
$finally = json_decode($_POST['thearray'], true);
// start a loop in order to update each record
$i = 1;
while ($i < ($size+1)) {
// define each variable
$pid = $finally[$i];
$playing = $finally[$i];
$query = "UPDATE players SET
on_court = '{$playing}'
WHERE id = {$pid}";
mysql_query($query, $connection);
$i = $i + 1;
} ?>
What am I doing wrong?
Upvotes: 1
Views: 231
Reputation: 171700
thearray
is only a variable name in javascript, so there is no $_POST['thearray']
and the data is not sent as JSON so no need to use json_decode
You want to access the name
attributes in the form controls:
Try looking at $_POST['sampleA']
.
Look at docs for serialize()
will see that it sends the data in same format as if form was submitted without AJAX
API Reference: http://api.jquery.com/serialize/
Upvotes: 1