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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料