[英]Passing Javascript variable to php on same page without reload
I have been having problems passing Javascript variable to php using ajax on the same page.I have a try.php page and once a button is clicked, I want a value sent to try.php variable without reloading the page..我在同一页面上使用 ajax 将 Javascript 变量传递给 php 时遇到问题。我有一个 try.php 页面,一旦单击一个按钮,我想要一个值发送到 try.php 变量而不重新加载页面..
This is my form code,I am actually looping trough a database record这是我的表单代码,我实际上是通过数据库记录循环
<?php
foreach($vars as $var){
?>
<form method="POST">
<button class="btn btn-warning btn-sm btn_edit" name="btn_edit" value="<?php echo $var['mem_id'];?>">
<span class="glyphicon glyphicon-pencil"></span></button>
<?php
}
?>
Here is my ajax code这是我的ajax代码
$('.btn_edit').click(function(e){
var uid = $(this).val()
$.post("try.php",{ btn_edit : uid},
function(){
});
console.log(uid);//I could see the id logged on console
$('#edit_details').modal('show');
e.preventDefault();//prevent the form from submitting
});
On my try.php page, I have this code to check if it passed succesfully在我的 try.php 页面上,我有这个代码来检查它是否成功通过
<?php if(isset($_POST['btn_edit'])){
$user_id = $_POST['btn_edit'];
}?>
There are two modifications need to be done:有两个修改需要做:
Change 1: Only input elements can have value
attribute.变化 1:只有 input 元素可以有value
属性。 And as you have <button>
, it should be assigned with some other attribute which can be captured using jQuery, so here I am going to use data-bind
attribute with it.正如你有<button>
,它应该被分配一些可以使用 jQuery 捕获的其他属性,所以在这里我将使用data-bind
属性。
<button class="btn btn-warning btn-sm btn_edit" name="btn_edit" data-bind="<?php echo $var['mem_id'];?>">
And then,Change 2: Get data-bind value with jQuery like this:然后,更改 2:使用 jQuery 获取数据绑定值,如下所示:
$('.btn_edit').click(function(e){
var uid = $(this).attr('data-bind'); // Using attr, not val()...
$.post("try.php",{ btn_edit : uid},
function(){
});
console.log(uid);//I could see the id logged on console
$('#edit_details').modal('show');
e.preventDefault();//prevent the form from submitting
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.