![](/img/trans.png)
[英]how to run php code on submit button without refreshing/ reloading the page
[英]How to make a button run php code with ajax, without refreshing the page Shopping cart
我的頁面cart.php中有3個按鈕在cart.php中,我可以使用所有功能。 當我在結帳頁面並且我想從購物車中添加或刪除項目時,我的頁面會刷新。 因為我的按鈕功能在cart.php 中。 我在 checkout.php 中調用了我的購物車功能
我不知道如何使用 ajax,但我認為 ajax 會幫助我解決這個問題......我如何在不去購物車和發送到 location:checkout.. 的情況下運行此代碼?
這是我在cart.php 上的按鈕。
if(isset($_GET['plus'])){
$_SESSION['product_'.$_GET['plus']]+=1;
if($_SESSION['product_'.$_GET['plus']] < 1){
header('Location: checkout.php');
}else{
header('Location: checkout.php');
}
}
if(isset($_GET['remove'])){
$_SESSION['product_'.$_GET['remove']]--;
if($_SESSION['product_'.$_GET['remove']] < 1){
header('Location: checkout.php');
}else{
header('Location: checkout.php');
}
}
if(isset($_GET['delete'])){
$_SESSION['product_'.$_GET['delete']] = '0';
header('Location: checkout.php');
}
$btn_add='<a class="btn btn-success" href="cart.php?plus='.$id.'"><i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i></a>';
$btn_remove = '<a class="btn btn-warning" href="cart.php?remove='.$id.'"><i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i></a>';
$btn_delete='<a class="btn btn-default delete_btn" href="cart.php?delete='.$id.'"><i class="fa fa-times fa-lg" aria-hidden="true"></i></a>';
<script>
function doChanges(job,div,id) {
try { req = window.XMLHttpRequest?new XMLHttpRequest():
new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { /* No AJAX Support */ }
req.open('get','yourphp.php?job='+job+'&id='+id);
// let the php echo the resultvalue
req.onreadystatechange = function() {
handleResponse(div);
};
req.send(null);
}
function handleResponse(div) {
if ((req.readyState == 4) && (req.status == 200)) {
val=req.responseText;
document.getElementById(div).value=val;
}
}
</script>
<div id="result"></div>
<a href="javascript:doChanges('inc','result','optionalcartitemid'> increase</a>
<a href="javascript:doChanges('dec','result','optionalcartitemid'> decrease</a>
然后你的 php 需要為 inc/dec 做案例工作
如果 ($_GET[job]=='inc') 然后增加
如果 ($_GET[job]=='dec') 然后減少
(或刪除,無論你想發生什么)任何輸出都將在 responseText 中結束
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.