jqueryhtmlajaxformsserializearray

posting a single dimenstion array to db ajax post


I have this form, that loads the details using jquery load function here is the form

 <form id="form1" name="form1" method="post" action="">
<div id="tableBg">
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="list">
<thead>
<tr>
      <th width="39%" scope="col">WHITE LIST</th>
      <th width="61%" scope="col">&nbsp;</th>
      </tr>
      </thead>
</table>

<div style="max-height:400px; overflow-y:auto">
  <table width="100%" border="0" cellspacing="0" cellpadding="0" id="list">
    <tr class="sub_head">
      <td scope="col"><strong>REG. NO.</strong></td>
      <td scope="col"><strong>STUDENT NAME</strong></td>
      <td scope="col"><strong>GRADE</strong></td>
      <td scope="col"><strong>MESSAGE ID</strong></td>
      </tr>
    <tbody></tbody>
  </table>
</div>
<div id="PageFooter">
 <input type="submit" name="save_result" id="save_result" value="Save Results" />
</div>
</div>
</form>

and loads the loads the code below from another page

do{
    ?>
<tr <?php echo (($x%2) != 0) ? '' : ' class="alternate-row row"' ?>>
  <td scope="col"><?php echo $learners['reg_no'];?></td>
  <td scope="col"><?php echo $learners['surname']." ".$learners['full_names']." (".$learners['nickname'].")";?></td>
  <td scope="col"><?php echo $learners['grd']." ".$learners['grade_section'];?></td>
  <td scope="col">
  <input name="sms_id[<?php echo $learners['reg_no']; ?>]" type="text" size="3" /> 
    </td>
  </tr>
<?php $x++;}while($learners = $getLearners->fetch());

this code is within a form and there is a submit button at the bottom. This for is posted to a process.php which with the following code, print's some output

if(isset($_POST['submit'])){

    foreach($_POST['sms_id']  as $reg=>$msg_id){
        echo $reg. " / ".$msg_id;
    }

}

the above displays both values if the form is posted directly from the form to process.php

But I wanted to use ajax and tried the following code that is not working. Just posting the $msg_id but not the other value.

var formData = $("#form1").serializeArray();
            $.ajax({
                url: "models/process.php",
                type: "POST",
                data: formData,
                success: function(data)
                {
                    alert(data);
                }
            });

This code is not working can someone help? Thanks in advance.

J D K


Solution

  • Actually, you are checking if(isset($_POST['submit'])) in your process.php which was not passing ajax.

    $('#form1').serializeArray() doesn't include data for submit button.

    Check the documentation here: http://api.jquery.com/serializearray/

    Your PHP Code (process.php) should be changed to:

    //if(isset($_POST['submit'])){ // this will not be available when using .serializeArray()
    
        foreach($_POST['sms_id']  as $reg=>$msg_id){
            echo $reg. " / ".$msg_id;
        }
    //}