PHP 表单按钮需要点击两次才能运行

时间:2021-02-15 12:38:35

标签: javascript php

此表单需要单击“添加到购物车”按钮两次才能生效。第一次点击重新加载页面,第二次点击将其添加到购物车。

<form id="offerForm" method="post" action="<?=$_SERVER['SCRIPT_NAME'];?>">
   <input name="faction" type="hidden" value="addSpecialOffer">
     <? 
        /* 
        // Offer Key Here
        */
     ?>
   <input type="hidden" name="offerKey" value="<?=$offerKey;?>">
     <?
        /*
        // Offer Key Ends
        */
     ?>
   <button class="offerMonthly-buttonCTA">ADD TO BASKET</button>                
</form>

这是运行的 PHP:

<?
$faction=(isset($_REQUEST['faction'])) ? $_REQUEST['faction'] : '';
$specialOfferKey=(isset($_REQUEST['offerKey'])) ? $_REQUEST['offerKey'] : '';

if(IS_DEVELOPMENT_SERVER){
    $offerKey = "abcd1234-1234-1234-1234-12345678901"; 
}else{
    $offerKey = "abcd1234-1234-1234-1234-12345678901"; 
}
/*
** Check if offer is live - start
*/
$found = false;
$ok = $nwc->sendRequest("GetSpecialOffers", array("MaxNumber"=>"99","SpecialOfferPK"=>""));

if($ok && $nwc->success()){
    $offersArray=(isset($nwc->getValue('MySpecialOffers')->SpecialOffers->SpecialOffer)) ? $nwc->getValue('MySpecialOffers')->SpecialOffers->SpecialOffer : array();
    foreach($offersArray as $offer){
        if($offer->SpecialOfferPK == $offerKey){
            $found = true;
            break;
        }
    }
    if(!$found){
        header(sprintf("Location: %s", $locale->getLanguageURL("landing/expired/")));
        exit();
    }
}
/*
** Check if offer is live - end
*/
if($faction == "addSpecialOffer"){
    $ok = $nwc->sendRequest("UpdateShoppingCart", array("ProductCode"=>$specialOfferKey,"Quantity"=>1,"UpdateType"=>"Fixed"));
    
    if($ok && $nwc->success()){
        header(sprintf("Location: %s", $locale->getLanguageURL("cart/")));
        exit();
    }
}

$ok = $nwc->sendRequest("GetPageContent", array("PageName"=>"GenericLandingPage"));

if($ok && $nwc->success()){
}else{
    $locale->throwServiceError($nwc);
    exit;   
}

?>

它应该做的是在第一次点击时将商品添加到购物车。我尝试使用 AJAX 来分别调用脚本,但这不起作用 - 页面每次都重新加载。
我对 PHP 比较陌生,所以不完全理解这个表单是如何工作的。

1 个答案:

答案 0 :(得分:0)

使用<form onsubmit="return false" ...<button type="submit"

并使用 ajax 处理添加到购物篮的功能