A
A
Alexander2015-11-01 16:45:05
PHP
Alexander, 2015-11-01 16:45:05

How to make multiple forms with ajax?

There is a table, in this table, depending on the value, a form is displayed. That is, there are many forms, but they all refer to one file:

if ($row['status'] == 1) {
echo "<form method='post' action='javascript:void(0);' onsubmit='table_boost_status()'  class='form_status'>
<input name='status' value='1' type='hidden'>
<input  name='id' value='".$row["id"]."' type='hidden'>
<button type='submit'  name='submit' class='btn btn-xs btn-success'><i class='fa fa-refresh'></i></button>
  </form>
  ";
}
if ($row['status'] == 2) {
echo "
<form method='post' action='javascript:void(0);' onsubmit='table_boost_status()' class='form_status'>
<input name='status' value='2' type='hidden'>
<input name='id' value='".$row["id"]."' type='hidden'>
<button type='submit'   name='submit' class='btn btn-xs btn-success'><i class='fa fa-refresh'></i></button>
</form>
";
}

processed by JS like this:
function table_boost_status() { //Ajax отправка формы
    var msg = $(".form_status").serialize();
    $.ajax({
        type: "POST",
        url: "/plugins/status_boost.php",
        data: msg,
        success: function (data) {
            
        },
        error: function (xhr, str) {
            alert("Возникла ошибка!");
        }
    });
}

PHP:
$id = $_POST['id'];
$status = $_POST['status'];

$sql = "UPDATE orders SET status='2' WHERE id='$id';";
$sql1 = "UPDATE orders SET status='3' WHERE id='$id';";

if ($status == 1 || $status == 2)  {

if ($status == 1) {
mysql_query($sql);	 
}
if ($status == 2) {
mysql_query($sql1);	 
}
}

When a button is clicked, a query is executed for the last row from the table, but in theory it should be for the one in which I click.
How to do what would be for this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2015-11-01
@gangstarcj

var msg = $(".form_status").serialize();
It is taken only from the last form with this class, if there are 10 forms, then the data will be taken from the 10th form.
You need to use $(this) or something like this to take from the form that is submitted

Y
Yuri, 2015-11-02
@kapitan7830

you can, for example, add unique id to forms and get data in this way
UPD:
As an option, to get the data of the desired form, add this
And then we change the function a little

function table_boost_status(form) { //Ajax отправка формы
    var msg = form.serialize();
    $.ajax({
        type: "POST",
        url: "/plugins/status_boost.php",
        data: msg,
        success: function (data) {
            
        },
        error: function (xhr, str) {
            alert("Возникла ошибка!");
        }
    });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question