weixin_33725807 2015-11-23 06:42 采纳率: 0%
浏览 133

AJAX被调用两次

I am trying to add values to database using ajax & php. i have a modal popup which asks user for input, and in modal popup there are text fields and submit button. when user fills the fields and hit submit button, the ajax is called which adds values to database.

$('.dup-product').click(function(){    
    var owners = $(".total_product_owner").val();
        $(".getmailfields").empty();
        if(owners == 0){
            $(".getmailfields").empty();
        } else {
            for (i = 1; i <= owners; i++) {        
                $(".getmailfields").append("<div class='form-group email_forms'><label class='control-label col-sm-2' for=invite-"+i+">Member "+i+" email</label><div class='albox col-sm-10'><input type='email' class='form-control' name='invitefriends[]' placeholder='sam@unclejohn.com' required></div></div>");
            }
        }
});

below code is action from modal popup

$('.duplicate_product').click(function(){
    var prodid = $(this).attr('pid');
    var userid = $(this).attr('oid');  
    $.ajax({
        type : "post",
        url : "user.php",
        data: { 
                product_id: prodid,
                user_id: userid,
             },
        cache:false,
        success : function(html){
              location.reload();
            }
        });
});

when i hit submit from popup the data is getting added twice to database.how can i resolve it?

php:

<?php   
$pid = $_POST['product_id']; 
$uid = $_POST['user_id'];

if (isset($pid) && !empty($uid)){  
    duplicate($pid,$uid);
} else {   
    echo "Are you trying to do something nasty??";
}

duplicate($pid,$uid){
 echo "Duplicated";
}

?>
  • 写回答

1条回答 默认 最新

  • weixin_33712987 2015-11-23 06:51
    关注

    There could be any of below situations

    1. There are two elements with the class duplicate product. If this is the case use id to bind the click event

      $('#duplicate_product').click(function(){
      var prodid = $(this).attr('pid');
      var userid = $(this).attr('oid');  
      $.ajax({
          type : "post",
          url : "user.php",
          data: { 
                  product_id: prodid,
                  user_id: userid,
               },
          cache:false,
          success : function(html){
                location.reload();
              }
          });
      

      });

    Then put id="duplicate_product" to the button 2. The event is bound to the button again and again. in such case use below code

    $('.duplicate_product').unbind('click').bind('click', function(){
    var prodid = $(this).attr('pid');
    var userid = $(this).attr('oid');  
    $.ajax({
        type : "post",
        url : "user.php",
        data: { 
                product_id: prodid,
                user_id: userid,
             },
        cache:false,
        success : function(html){
              location.reload();
            }
        });
    

    });

    评论

报告相同问题?