Working with forms

There are several consecutive shapes

<form>
<input type="hidden" name="i" value="1">
<input type="submit" value="ok">
</form>
<form>
<input type="hidden" name="i" value="2">
<input type="submit" value="ok">
</form>

Using ajax and jquery, a POST request is sent passing only 1 value from the hidden field i, the question is how to select this value depending on the form in which the ok button was clicked. Or, even more interesting, how to do the same thing, only without a form, for example, by clicking on a link.


Answer 1, authority 100%

Hang up a handler on the click on the link in which you send the request, namely the value of only one field. The answer lies in the question itself.
You can do the following: give names to hidden fields almost the same as to links with the only difference – at the beginning we add the letter h. Then, after the link is clicked, we determine the name of the clicked link and programmatically generate the name of the corresponding hidden field.
The send code is something like this:

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('#error').hide();
var hiddenname='';
$("#container").click(function (e) {
if (e.target.id!='') {hiddenname = e.target.id; hiddenname='h'+hiddenname;}
 var x = $(hiddenname).val();//       
 $.ajax({
    type: "POST",
    url: "test.php",
    data: "x="+x,
    success: function(html){
    $("#error").append(html);
    $("#error").slideDown('slow');
                }           
});
});
}); 
</script>
</head>
<body>
<div id="error"></div>
    <div id="container">
<form>
 <a href="#" id="link1">link1</a>
<input type=hidden id="hlink1"><br><br>
 <a href="#" id="link2">link2</a>
<input type=hidden id="hlink2"><br><br>
 <a href="#" id="link3">link3</a>
<input type=hidden id="hlink3"><br><br>
 <a href="#" id="link4">link4</a>
<input type=hidden id="hlink4"><br><br>
</form>
</div>

And then on the server you take out the value of the variable xfrom the POST array


Answer 2, authority 33%

<form class="add"> 
<input type="hidden" name="i" value="1"> 
<input type="submit" value="ok"> 
</form>
<form class="add"> 
<input type="hidden" name="i" value="2"> 
<input type="submit" value="ok"> 
</form>
$(function() {  
    $("form.add").submit(function(){ 
        $.post("test.php", $(this).serialize(), function(data){ 
        }); 
        return false; 
    });  
});

All you had to do was add a class to each form.