[英]php + ajax without page refresh
I am trying to update a status in my users table - when a user click on a button I used ajax to send it to the the php page but on response the page reload because I used `location.reload();. 我正在尝试更新用户表中的状态-当用户单击按钮时,我使用ajax将其发送到php页面,但响应时页面会重新加载,因为我使用的是`location.reload();。 Is there a way i could make the button change its status without reloading the page? 有没有一种方法可以使按钮更改状态而无需重新加载页面?
The buttons: 按钮:
<i data="<?php echo $row['id'];?>" class="status_checks btn <?php echo ($row['payment_status'])? 'btn-success' : 'btn-danger'?>"><?php echo ($row['payment_status'])? 'Paid' : 'Unpaid'?></i>
php that update the database PHP的更新数据库
<?php
extract($_POST);
$user_id=$db->real_escape_string($id);
$status=$db->real_escape_string($status);
$sql=$db->query("UPDATE users SET payment_status='$status' WHERE id='$id'");
echo $sql;
?>
and finally, the jquery 最后,jQuery
<script type="text/javascript">
$(document).on('click','.status_checks',function(){
var status = ($(this).hasClass("btn-success")) ? 'Unpaid' : 'Paid';
var msg = (status=='Unpaid')? 'Unpaid' : 'Paid';
if(confirm("Are you sure to "+ msg)){
var current_element = $(this);
url = "update.php";
$.ajax({
type:"POST",
url: url,
data: {id:$(current_element).attr('data'),status:status},
success: function(data)
{
location.reload();
}
});
}
});
</script>
echo $sql;
will return either 0 or 1 将返回0或1
you can update the class of the button without reloading as 您可以更新按钮的类而无需重新加载为
success: function(data)
{
if(data == 1) // success
{
$('.status-checks').each(function(){
if($(this).attr(data) == $(current_element).attr('data'))
{
$(this).addClass('btn-success');
$(this).text('Paid');
}
})
}else // failed
{
$('.status-checks').each(function(){
if($(this).attr(data) == $(current_element).attr('data'))
{
$(this).addClass('btn-danger');
$(this).text('Unpaid');
}
})
}
}
});
you must replace location.reload() with a if and else statment that for eg if(data) //button value change else //button value don't change or other statement 您必须用if和else语句替换location.reload(),例如if(data)//按钮值更改else //按钮值不更改或其他语句
that's it 而已
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.