modify an input and perform the update

0

php

Can anyone give me some tips on implementing a part? I have a text input inside the while loop: "<td><input type='text' value='".$valor['url_video']."' style='width: 400px;' id='url-video'></td>". , inside this input the url_video is printed, when I click on the update btn, I have it update the selected input field var string = $('#url-video').val(); the problem is that it only updates the first column url_video , is giving problem in the others (only a copy of this first is made for other fields). I think the problem is when I enter my input as id='url-video' , is not it? Can you give me tips?

    echo "<table class='table'>".
        "<thead>".
             "<tr>".
                "<td>ID</td>".
                "<td>url_video</td>".
             "</tr>".
        "</thead><tbody>";
while($valor = mysqli_fetch_array($resultado)){
    echo "<tr>".
            "<td>".$valor['ID']."</td>".
            "<td><input type='text' value='".$valor['url_video']."'  style='width: 400px;' id='url-video'></td>".
            "<td><input type='button' value='Update' class='btn-update' data-id='".$valor['ID']."' >"."</td>".
         "</tr>";
}
echo "</tbody></table>";

ajax

$(document).ready(function(){

    $('.btn-update').click(function(){
        var id = $('.btn-update').data('id');
        var string = $('#url_video').val();

        $.ajax({
            url: "tabelaUpdate.php",
            data: { 'idDeUpdate' : id,
                    'url_video' : string
                  },
            type: "POST",
            cache: false,
            success: function(response){
                //alert("ok"+response);
                $('#result').html(response); //serve para ver a array foi inserida mesmo
            }
        })
    });
});
    
asked by anonymous 26.03.2015 / 20:11

1 answer

2

Using id this way within a loop is unfeasible. IDs are SINGLE, if you have two equals on the same page JS gives a spade.

Solution (I added the Video ID in the Input ID):

while($valor = mysqli_fetch_array($resultado)){
    echo "<tr>".
            "<td>".$valor['ID']."</td>".
            "<td><input type='text' value='".$valor['url_video']."'  style='width: 400px;' id='url-video-".$valor['ID']."'></td>".
            "<td><input type='button' value='Update' class='btn-update' data-id='".$valor['ID']."' >"."</td>".
         "</tr>";
}

And JS retrieves the right field, using the button ID:

$('.btn-update').click(function(){
    var id = $('.btn-update').data('id');
    var string = $('#url_video-'+id).val();

    $.ajax({
        url: "tabelaUpdate.php",
        data: { 'idDeUpdate' : id,
                'url_video' : string
              },
        type: "POST",
        cache: false,
        success: function(response){
            //alert("ok"+response);
            $('#result').html(response); //serve para ver a array foi inserida mesmo
        }
    })
});
    
26.03.2015 / 21:02