简体   繁体   中英

e.preventDefault() is not working

The first e.preventDefault() inside the if condition is not working. Only the second e.preventDefault() is working. Any help would be greatly appreciated.

I made following change to the jquery, but then the form submission does not work properly and the page stops at the blank form action page checkcoupon.php instead of further processing of form.

<form name='coupon_discount' id='coupon_discount' action="checkcoupon.php" method='post'>
        <input type="hidden" name="user" value="<?php echo $_SESSION[user_id]; ?>" >
        <input value="" id="couponCode" name="couponcode" class="coupon-placeholder placeholder"  type="text"/>               
        <input type='submit' name='coupon_code_submit' value='Apply' id="cart-coupon" class="sp_apply_btn" >      
  </form>



     jQuery(document).ready(function(){
        jQuery('form#coupon_discount').submit(function(e){
             var   user     = jQuery('input[name="user"]', 'form#coupon_discount').val();
             var couponcode = jQuery('input[name="couponcode"]', 'form#coupon_discount').val();
             if(user != '' && couponcode != '') {
             e.preventDefault();
             var URL = '<?php echo $_conf_vars['ROOT_URL']."ajax.php?usercp=";?>'+user+'&cponcode='+couponcode;
             jQuery.ajax({
                        url:URL,
                        type:'POST',
                        async:true
                      }).done(function(msg,e){
                        if(msg=='Already used!'){ 
                          alert('Coupon code already used!');
                         }else {  
                          jQuery('form#coupon_discount').submit();  
                         }
                      }); 
                   }
                   else{
                     e.preventDefault();
                     alert('Enter a coupon code!');
                   }    
             });  
        });

And this the action page 'checkcoupon.php' code.

  session_start();
    ob_start();

    include("includes/files.php");
    include("classes/class.common.php");

    if(isset($_REQUEST['coupon_code_submit']))
    {
        $obj_common = new common;
        $discount = $obj_common->getCouponCodeDiscount($_REQUEST['couponcode'],$_REQUEST['user']); 
        header("location:payment.php");
    }

Try like this

jQuery(document).ready(function(){
    jQuery('form#coupon_discount').submit(function(e){
        e.preventDefault();   //Put here and do the stuff

         });  
    });

You are putting the e.preventDefault() call inside an asynchronous callback. By the time the code gets there, it's already too late.

Move the e.preventDefault() outside the callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM