views:

32

answers:

2

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>\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

+1  A: 

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/

also, using an alert to debug you JS is usually not very helpful, you should install firebug, and instead of doing alert(this.ids); try console.log(this.ids); you will get much more helpful information.
A: 

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'];
robdog