douchuoxuan3177 2016-06-27 08:03
浏览 60
已采纳

Ajax发布表单自动提交加载

I'm trying to post a form to a database using ajax. I have tested the form and the php which all work when I manually submit. But the issue I have is when I try to auto-submit on page load using ajax it just doesn't seem to fire.

I don't get any console errors and the form does get removed. It is just the ajax that doesn't kick in.

setTimeout(function() {
  $("form.display-hide").submit(function(e) {
    e.preventDefault();
    $.ajax({
      url: '//www.mysite.com/inc/page-trustpilot.php',
      type: "POST",
      data: $(this).serialize(),
      success: function() {
        alert('hello');
      }
    }); // AJAX Get Jquery statment

  });
  $("form.display-hide").remove();
}, 2000);
<form class="display-hide" method="post">
  <input class="totaltrsut" type="text" value="" name="totaltrsut">
  <input class="totalreviews" type="number" value="" name="totalreviews">
  <input type="hidden" name="token" value="<?php echo $newToken; ?>">
  <input class="committodb" type="submit" value="Add Stats">
</form>

<?php
 if (!empty($_POST)) {
 global $wpdb;

 $successa=$wpdb->update( '6H921_dc_additional', array( 'addi_value' => $_POST['totaltrsut'] ), array( 'addi_id' => 1 ), array( '%s', '%d' ), array( '%d' ) );
 $successb=$wpdb->update( '6H921_dc_additional', array( 'addi_value' => $_POST['totalreviews'] ), array( 'addi_id' => 2 ), array( '%s', '%d' ), array( '%d' ) );
if($successa && $successb){
    //echo 'data has been saved'; 
} else {
    //echo 'data has not been saved'; 
    }
 }
?>

</div>
  • 写回答

3条回答 默认 最新

  • dongmanzui8486 2016-06-27 08:14
    关注

    it seems that you removing the form, before you submit it:

    setTimeout(function() {
        //registering submit handler
        $("form.display-hide").submit(function(
             //some code
         });
    
         //removing the form immediatly
         $("form.display-hide").remove();
    }, 2000);
    

    Maybe you want to submit the form before removing it:

    setTimeout(function() {
        //registering submit handler
        $("form.display-hide").submit(function(
             //some code
         });
    
         //submit the the form, which would invoke the submit handler
         $("form.display-hide").submit();
    
         //removing the form immediatly
         $("form.display-hide").remove();
    }, 2000);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?