douji2520 2015-07-09 18:44
浏览 46
已采纳

我想加载带有消息的php以在提交后隐藏表单但是event.preventDefault(); 破坏我的.php文件中的“已存在”检查

After submitting there must exist 3 possible states:

  1. Data saved and php message is loaded onto where the form was.
  2. Data already exists and I load a different php informing the user.
  3. An error occurred, show an alert asking the user to please try again.

This is what my submit .php looks like:

$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>";
}

It works fine on it's own and this is my try at an ajax request to submit:

$(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");
        }
    });
});

Which also works, but because of the .preventDefault(); I "don't" know if the data was saved or not.

I have no idea what I should try to do to bring these 2 together, or if there's a better way to do this...

I'm guessing this must be rather easy to solve, I'm just missing something I haven't learned yet.

  • 写回答

1条回答 默认 最新

  • duanlan8763 2015-07-09 18:51
    关注

    Don't return JS or other html. return some 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);
    

    Then in your success handler:

    success: function(data) {
            if (data.code == 1) {
                 do_success_stuff();
            } else {
                alert('requested failed with error #' + data.code + " and message '" + data.message + "'");
            }
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?