gpt4 book ai didi

javascript - 我想在提交后加载 php 一条消息以隐藏表单,但 event.preventDefault();破坏了对我的 .php 文件的 "already exists"检查

转载 作者:行者123 更新时间:2023-12-03 09:36:16 25 4
gpt4 key购买 nike

提交后必须存在3种可能的状态:

  1. 数据已保存,PHP 消息已加载到表单所在的位置。
  2. 数据已经存在,我加载了一个不同的 php 通知用户。
  3. 发生错误,显示警告,要求用户重试。

这就是我的提交 .php 的样子:

$test="select * from launchpage where email_launchPage ='$email'";
$testing=$link->query($test);
$alreadyExists=$testing->num_rows;

if($alreadyExists ==1){
echo "<script>alert('already exists');window.history.go(-1);</script>";
} else{
$sqlInsertListingType="insert into launchpage(email_launchPage,language_launchPage) values('".$email."','".$language."')";
$link->query($sqlInsertListingType);
echo "<script>alert('saved');window.history.go(-1);</script>";
}

它本身工作得很好,这是我尝试提交 ajax 请求:

$(document).on("submit","#form",function(event){
event.preventDefault();
var formURL = $(this).attr("action");
var formType = $(this).attr("method");
var formData = $(this).serialize();
$.ajax({
url: formURL,
type: formType,
data: formData,
success:function(data, textStatus, jqXHR){
console.log('went through ajax');
},
error: function(jqXHR, textStatus, errorThrown){
console.log("i've ruined something");
}
});
});

这也有效,但是因为 .preventDefault();我“不”知道数据是否已保存。

我不知道我应该尝试做什么来将这两者结合在一起,或者是否有更好的方法来做到这一点......

我猜这一定很容易解决,我只是错过了一些我还没有学到的东西。

最佳答案

不要返回JS或其他html。返回一些 json:

<?php

... process form data
if (processing succeeds) {
$msg = array(
'code' = 1,
'message' = 'Success'
);
} else {
$msg = array(
'code' => 0,
'message' => 'Failed, something dun blowned up'
);
}
echo json_encode($msg);

然后在您的成功处理程序中:

success: function(data) {
if (data.code == 1) {
do_success_stuff();
} else {
alert('requested failed with error #' + data.code + " and message '" + data.message + "'");
}
}

关于javascript - 我想在提交后加载 php 一条消息以隐藏表单,但 event.preventDefault();破坏了对我的 .php 文件的 "already exists"检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31325767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com