我想添加给定表格中的用户。我正在迭代整个表并将每个值发送到javascript文件。
<?php
$sql = "select * from user where user_id not in (select second_user_id from friends where first_user_id = '$user_id'\n"
. " union\n"
. " select first_user_id from friends where second_user_id = '$user_id') limit 20";
$result_not_friends=mysqli_query($dbc,$sql)
or die("error in fetching");
// print_r($row_not_friends);
?>
<table class="table table-hover table-bordered">
<h1>Users</h1>
<tbody>
<?php
while ( $row_not_friends = mysqli_fetch_array($result_not_friends))
{
if ( $row_not_friends['user_id'] != $user_id )
{
?>
<tr>
<td>
<?php echo $row_not_friends['user_name']; ?>
</td>
<!-- here I am sending request and processing it via ajax -->
<td><i class="fa fa-user-plus send_request"></i></td>
<input type="hidden" class="send_second" value="<?php echo $row_not_friends['user_id']; ?>">
<input type="hidden" class="send_first" value="<?php echo $user_id; ?>">
</tr>
<?php
}
}
?>
</tbody>
</table>
现在我正在访问javascript文件中的每个值,如下所示: //这里发送请求
$('.send_request').on('click',
function (e) {
e.preventDefault();
var first = $('.send_first').val();
var second = $('.send_second').val();
alert('firt id is ' + first);
alert('second id is ' + second);
$.ajax(
{
url:'send_process.php',
type:'POST',
dataType:"json",
data: { first: first, second: second },
success:function(data)
{
if(data.send_success)
{
window.location.href = "friend.php";
}
else
{
alert("something went wrong");
window.location.href = "friend.php";
}
},
error : function() { console.log(arguments); }
}
);
});
但此处var second = $('.send_second').val();
仅提供$row_not_friends['user_id']
的最高元素值。当我回显该值时,它会给出正确的结果。
请帮帮我。
答案 0 :(得分:1)
因为您正在选择页面中的所有元素,而val()的默认行为是它返回第一个项目。它没有你想要第n项的线索。
首先,您需要修复HTML无效。您不能将输入作为tr元素的兄弟。你需要在TD内部移动它。
<!-- here I am sending request and processing it via ajax -->
<td><i class="fa fa-user-plus send_request"></i> <!-- removed the closing td from here -->
<input type="hidden" class="send_second" value="<?php echo $row_not_friends['user_id']; ?>">
<input type="hidden" class="send_first" value="<?php echo $user_id; ?>"></td> <!-- moved the closing td to here -->
</tr>
您需要在单击按钮的同一行中找到元素。由于隐藏的输入是按钮的npw兄弟,您可以使用siblings()
方法。
var btn = $(this);
var first = btn.siblings('.send_first').val();
var second = btn.siblings('.send_second').val();