Ajax提交表单,并解除成功/错误

时间:2016-04-30 18:24:00

标签: php jquery ajax

我使用jQuery和Ajax将表单提交给PHP脚本。

用户将输入他们的详细信息,单击提交按钮,PHP脚本将运行并且将执行所需的操作或失败。

此时我想根据错误类型显示成功或错误消息。

<script>
$( "#contact-form" ).submit(function(event) {
    event.preventDefault();
    $.ajax({
        url: "includes/contact-us.php",
        type: "post",
        data: $("#contact-form").serialize(),
        success:function(data) {
         alert(data);
        },
        error:function(){
            alert("failure");
        }   
    }); 
});
</script>

因此,在上面的jQuery中,当提交表单时,它会阻止默认action="path to script.php"然后执行提交。我已经完成了这项工作,用户已禁用Javascript,因此至少基本功能将在那里。

PHP

<?php                  
    if(isset($_POST['contact']) && !empty($_POST['contact'])){

            $link = new mysqli("example", "example", "example", "example");

            if($link->connect_errno > 0) {
                die('Unable to connect to database [' . $link->connect_error . ']');
            }

            $name = $_POST['name'];
            $email = $_POST['email'];
            $website = $_POST['website'];
            $subject = $_POST['subject'];
            $message = $_POST['message'];

            $stmt = $link->prepare("INSERT INTO contact (name, email, website, subject, message) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("sssss", $name, $email, $website, $subject, $message);

            if($stmt->execute()){

                $rtn = "Success";

                echo json_encode($rtn);

                } else {

                $rtn = "Failed";

                echo json_encode($rtn);

            }                              
            $stmt->close();
            $link->close();
}

但是,在此示例中,警告框显示为空。在firebug或Apache日志中没有错误。

是否可以:当我使用Ajax执行提交时,我可以接收echo "Text from error or success box";然后我可以将其置于引导警报中?

我写的代码是新的,所以我会考虑适应新的库。这纯粹是为了显示错误或成功消息的UI增强功能,如果用户禁用了javascript,则无法阻止表单默认操作 - 他们只是看不到成功或错误消息。

我看到的是"Javascript promises"我不介意使用Javascript,如果这在可用性方面更好,因为我不想在提交时冻结浏览器。< / p>

感谢您的时间

2 个答案:

答案 0 :(得分:1)

你可以在php中使用try catch()

<?php
    // ...
    try{
       // your code
       $msg = 'Success';
       return json_encode($msg);
    }catch(Exception $e){
       $msg = 'Error';
       return json_encode($msg);           
    }

&GT;

答案 1 :(得分:1)

您的代码看起来应该是这样的

我会从PHP传回标准形式的成功/错误。所以失败可能是这样的:

json_encode(['success'=>false]);

然后在Javascript中对此进行操作将如下所示:

$.ajax({
    url: "includes/contact-us.php",
    type: "post",
    data: $("#contact-form").serialize(),
    success:function(data) {
        data = JSON.parse(data);

        if (data.success)
            alert('success!');
        else
            alert('got failure response from PHP');
    },
    error:function(){
        alert("failure");
    }   
});