Billy Billy - 2 months ago 7
Ajax Question

Loop through submit buttons and post to MySQL w/ ajax

I currently have a form(s) that gets created based on the number of rows in the DB. Each row gets pulled in to its own form where data is editable. Each row also has it's own button.

$i = 0;
while($row = mysql_fetch_array( $result )) {
if ($row['stage']=='1'){ $i++;
<form method="post" name="form<?php echo $i;?>' id='form<?php echo $i;?>">
<input type="text" name="product<?php echo $i;?>" value="<?php echo $row['product'];?>" id="product<?php echo $i;?>" />
<input type='button' name='submit<?php echo $i;?>' value='NEXT'/>
</form>


JQUERY

$(".submit1").click(function(){
$.ajax({
type: "post",
url: "xx1.php",
data: $("#form1").serialize(),
success: function() {
alert("UPDATE SUCCESS");
location.reload();
},
error: function () {
alert("FAILED");
}
});
});


xx1.php

$ProductOne= strip_tags($_POST['product1']);
if ($StageOne == "1"){
SQL STATEMENT
}elseif ($StageOne == "2"){
SQL STATEMENT
}elseif ($StageOne == "3"){


I currently have xx.php for each row (xx1.php,xx2.php,xx3.php) and in my php file my $_POST['x'] matches the xx.php ($_POST['product1'], $_POST['product2'], $_POST['product3']

How do write something that says if submitx is clicked update that row where i = i (update product1 when submit1 is clicked, update product2 when submit2 is clicked)

Answer

You need to get button id (the one which got clicked) and call the respective file for the execution.

$("button").click(function() {
  //extract the name of the button clicked
  var name = $(this).attr('name');
  //get the button id from name.
  var buttonId = name.split('submit')[1];
  $.ajax({
      type: "post",
      url: "xx.php",
      data: $("#form" + buttonId + "").serialize(),
      success: function() {
          alert("UPDATE SUCCESS");
          location.reload();  
      },
      error: function () {
         alert("FAILED");
      }
  });
});

data sent to xx.php has the id. So you may use this id to operate on xx.php.

$id = //get the id from form data sent from js
$Product = strip_tags($_POST["product{$id}"]);
.
.
//use id instead of number in further operations.