0

I have a dynamically generated form.It has only one text input which value is ID dynamically fetched from database table (table_one). My aim is to submit this ID to another table(table_two). On my page I can see these IDs fetched from the table_one say: 1, 2, 3, 4 ,5, but when I submit any of these IDs say '2', it is only the last ID '5' that will be submitted to table_two. How can I amend my code so that when I submit row 2, ID '2' will be submitted not '5'? Below is my code.

HTML

<form>
     <input type="text" id="name" name="name" value="<?php echo $name_id;?>" >
     <button type="submit" onclick="return chk()">Edit</button>
</form>

JAVASCRIPT

function chk(){
    var name = document.getElementById('name').value;
    var dataString = 'name='+ name;
    $.ajax({
        type:"post",
        url:"test.php",
        data:dataString,
        cache:false,
        success: function(html){
            $('#msg').html(html);
             }
        });
    return false;
}

PHP

$name = $_POST['name'];
echo "$name";
Oponjous
  • 37
  • 7
  • 1
    [ID's Must Be Unique](http://stackoverflow.com/questions/5611963/can-multiple-different-html-elements-have-the-same-id-if-theyre-different-eleme), specifically because it will cause problems in [JavaScript](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id) and CSS when you try to interact with those elements. – Jay Blanchard Sep 11 '17 at 19:53
  • Thank @Jay, but how do I make the IDs unique? – Oponjous Sep 11 '17 at 19:58
  • 1
    There are a number of approaches you can take. Because the elements are dynamically created I would probably generate an array of ids and then create an element for each id. – Jay Blanchard Sep 11 '17 at 20:03

1 Answers1

1

You must add unique identifier or use the DOM. Simple solution to your case is:

HTML

<input type="text" id="name-<?php echo $name_id;?>">
<button type="submit" onclick="return chk(<?php echo $name_id;?>)">Edit</button>

Javascript

function chk(name_id){
    $.ajax({
        type:"post",
        url:"test.php",
        data: { 
            id: name_id, 
            name: $('#name-'+name_id).val() 
        },
        cache:false,
        success: function(html){
            $('#msg').html(html);
         }
        });
    return false;
}

And pass the id of the row you want to change. On the server you process both values from the $_POST. Hope this helps.

btw you don't need form element in this AJAX scenario.