开发者

How can I pass a forms checked checkboxes to a PHP page as an array using a jQuery submit function?

开发者 https://www.devze.com 2023-01-07 07:20 出处:网络
I have athat has a list of checkboxes and user can click any number then click submit. The list of checkboxes is generated based on the results of a mySQL query -

I have a that has a list of checkboxes and user can click any number then click submit. The list of checkboxes is generated based on the results of a mySQL query -

echo("<form id=\"target\" action = \"#\">");
echo("<ul>");
while($row = mysql_fetch_array($result) {
  $the_value = $row['result_value'];
  $the_label = $row['result_label'];
  echo("<li><input type='checkbox' name=\"ids[]\" value='" . $the_value . "'/> " . $the_label . "</li>\开发者_StackOverflow中文版n");
echo("</ul>");
echo("<input type=\"submit\" value =\"Copy\">");
echo("</form>");

Then I have a jQuery handler for the submit

$('#target').submit(function() {
  alert(this.ids); // *See note below
  // I now want to call a PHP page, passing the array of ids so that this array can be used in a mySQL statement, then when complete notify the user it has succeeded
  return false;
});

*If I give the checkbox group the name ids (name=\"ids\") rather than ids[] then this alert shows "[object NodeList]"

How should I handle this? many thanks


you use the serialize method, like this:

$('#target').submit(function() {
  $.post('script.php', $(this).serialize(), function(data) {alert('The data was posted!');})
  return false;
});

http://api.jquery.com/serialize/


Are you wanting to do an AJAX request or a normal submit?

A normal submit would be as follows:

<form id="target" action="action.php" method="post">
    <ul>
    <?php
    while($row = mysql_fetch_array($result)) {
        echo "<li><input type='checkbox' name='ids[]' value='{$row['value']}'/>{$row['label']}</li>";
    }
    ?>
    </ul>
    <input type="submit" value="Submit" />
</form>

For an AJAX submit, your handler would be:

$('#target').submit(function() {
    $.post('action.php', $(this).serialize(), function(data) {
        alert(data); // Data is your response;
    });
    return false;
});

Then in action.php, to get the ID's:

$idArray = $_POST['ids'];
0

精彩评论

暂无评论...
验证码 换一张
取 消