我正在尝试使用 ajax 将表单发布到数据库。我已经测试了表单和 php,当我手动提交时它们都可以工作。但我遇到的问题是,当我尝试使用 ajax 在页面加载时自动提交时,它似乎没有触发。
我没有收到任何控制台错误,并且表单确实被删除了。只是 ajax 没有启动。
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';
}
}
?>
最佳答案
您似乎在提交之前删除了表单:
setTimeout(function() {
//registering submit handler
$("form.display-hide").submit(function(
//some code
});
//removing the form immediatly
$("form.display-hide").remove();
}, 2000);
也许您想在删除表单之前提交表单:
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);
关于javascript - Ajax 表单加载时自动提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38048726/