jQUery PHP pass the value to ajax i just need the id to edit the file

不打扰是莪最后的温柔 提交于 2021-01-29 05:31:05

问题


how can i get the value of id from my database using jQuery AJAX.

I created an CRUD which i need to edit and delete the user for each respected id the Create New user was working because i dont need the id to pass. But when i do the update the user the value of ID was not working for each user.

it only read the first ID but the rest of the user cannot be read anymore. I have this code

<form method="get">
<table class="table table-bordered">
<?php 
$sqlView = mysql_query("SELECT * FROM user ORDER BY id DESC") or die (mysql_error());
while($rowView = mysql_fetch_array($sqlView)){
$id = $rowView['id'];
echo '
<tr>
    <td>
        <input type="hidden" name="id" value="'.$id.'" />
        <input type="hidden" name="name" value="'.$rowView['name'].'" />
        <input type="hidden" name="up" value="edit" />
        '.$rowView['name'].'
    </td>
    <td>'.$rowView['phone'].'</td>
    <td>'.$rowView['address'].'</td>
    <td>'.$rowView['email'].'</td>
    <td>'.$rowView['status'].'</td>
    <td><a href="#" class="update" id="'.$id.'">Update</a> Delete </td>
</tr>
';
}

?>
</table>
</form>

$('a.update').click(function(e) {
    $('<img src="images/loading.gif" id="loading" style="width:auto;" />').appendTo(".span9");
    //Cancel the link behavior
    e.preventDefault();
    //Get the A tag
    var id = $( 'input[name=id]' ).val();
    var edit = $( 'input[name=up]' ).val();
    var name = $( 'a#id' ).val();
    alert( name );
    $.ajax({
        type:"GET",
        url:"ajax/company.php",
        data: {id: id, up: edit, aid: name},
        dataType: 'html',
        target: '.span9',
        success: function(data){
            $(".span9").find('img#loading').remove();
            $(".span9").html(data);
        }
    })
}); 

the ajax/company.php

<?
echo $_GET['id'];
?>

is my ajax wrong?

why is it on while the jQuery cannot pass the value of each id.


回答1:


Your fields have the same name for all rows, so when you query it via $( 'input[name=id]' ).val(), it always returns the first value.

If you don't want to change the name of the fieds to unique names, you should access them with:

var row = $(this).parent().parent();
var id = row.find('input[name=id]' ).val();
var edit = row.find('input[name=up]' ).val();
var name = row.find('a#id' ).val();



回答2:


You can also try :

  var row = $(this).parents(\"tr:first\")
  or
  var row = $(this).closest('tr');

var id = row.find('input[name=id]' ).val();
var edit = row.find('input[name=up]' ).val();
var name = row.find('a#id' ).val();


来源:https://stackoverflow.com/questions/13715214/jquery-php-pass-the-value-to-ajax-i-just-need-the-id-to-edit-the-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!