【问题标题】:Page redirect after successfully inserting data to db with php and jquery使用 php 和 jquery 成功将数据插入数据库后的页面重定向
【发布时间】:2026-02-14 03:45:01
【问题描述】:

我有一个 html 表单,我使用 Jquery 通过 Php 进行验证。成功将数据插入数据库后,它会在html 页面中显示成功消息并重定向到不同的页面。好吧,它工作正常,但如果出现错误,它也会重定向到不同的页面。

我想要什么:
如果有错误,它应该留在这个页面上。如果没有错误,那么它应该重定向到不同的页面。我怎样才能用 jquery 做到这一点?

<center><img id="loading-image" src="images/loading-image.gif" style="display:none; margin-bottom:10px !important;"/></center>
<div id="result"></div>

$('body').on('click', '#request_tutor', function (e) {
    e.preventDefault();

    var formData = new FormData($(this).parents('form')[0]);
    $("#loading-image").show();
    $.ajax({
        url: 'request_tutor_process.php',
        type: 'POST',
        xhr: function () {
            var myXhr = $.ajaxSettings.xhr();
            return myXhr;
        },
        success: function (data) {
            $("#loading-image").hide(); //hide loading          
            $("#result").html(data);

            setTimeout(function () {
                $('input[type=submit]').attr('disabled', false);
                window.location.href = "login/index.php";
            }, 2000);

        },

        complete: function () {
            $("#loading-image").hide(); //hide loading here
        },

        data: formData,
        cache: false,
        contentType: false,
        processData: false
    });
});

PHP页面:

$err =  array();
// required eata validation checking...
if(isset($name) && isset($tutoring_location) && isset($pcode) && isset($mphone) && isset($email) && isset($tutor_level)){
    if(empty($name) && empty($tutoring_location) && empty($pcode) && empty($mphone) && empty($email) && empty($tutor_level)){
        $err[] = "Please fill up required field which is indicated by *";
    }else{
        if(empty($name))    
            $err[] = "Your name required";
        elseif(strlen($name) > 30)
            $err[] = "Your name is too long";

        if(empty($tutoring_location))   
            $err[] = "Write your tutoring location";
        elseif(strlen($tutoring_location) > 255)
            $err[] = "Tutoring location address is too long";

        if(empty($pcode))   
            $err[] = "Postal code required";
        elseif(strlen($pcode) > 6)
            $err[] = "Invalid postal code"; 
        elseif(!is_numeric($pcode))
            $err[] = "Invalid postal code";

        if(empty($mphone))  
            $err[] = "Mobile phone number required";
        elseif(strlen($mphone) > 8)
            $err[] = "Invalid mobile phone number";     
        elseif(!is_numeric($mphone))
            $err[] = "Invalid mobile phone number"; 

        if(empty($email))   
            $err[] = "Your email address required.";    
        elseif(@!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
            $err[] = "Invalid email address";
        elseif($num_email == 1)
            $err[] = "Email address <strong>$email</strong> is already exits, please choose another";       

        if(empty($tutor_level)) 
            $err[] = "Select your tutor level";         
    }

    if(!empty($err)){
        echo "<div class='error'>";
        foreach($err as $er){
            echo "$er. <br/>";
        }
        echo "</div>";
    }else{
        ecoh "success";
    }
}

【问题讨论】:

  • 您如何使用 jQuery 验证 PHP? PHP 是服务器端,jQuery 是客户端。他们不能直接互动。你真的确定要在整个身体上设置点击事件吗?你的 PHP 代码是什么样的?
  • @Zarathuztra 按下提交按钮后,它使用 jquery on click 方法调用 php 页面。将数据插入到 db php 后,将成功消息返回给 jquery,即$("#result").html(data);
  • @John Barca 感谢您编辑我的问题。

标签: php jquery


【解决方案1】:

你的问题是它总是会进入成功块,对吧?

如果是这样,请按照@Zarathuztra 的回答并在您的 PHP 代码中将 HTTP 代码设置为 200 以外的任何值,并添加一个错误块来处理错误。 参考这个答案Return errors from PHP run via. AJAX?

或者你可以检查数据的值,看看是否有错误。

【讨论】:

  • 哦。我明白了。谢谢你的链接。
【解决方案2】:

这可能是罪魁祸首

setTimeout(function () {
    $('input[type=submit]').attr('disabled', false);         
    window.location.href = "login/index.php"; 
},   2000); 

代码成功后,您将设置一个全局超时,每两秒重定向一次页面。出于某种原因,由于您没有显示您的 PHP 代码,它总是成功的。基本上,只要响应返回为有效(HTTP 响应代码 200),它就会始终成功。如果 PHP 端出现错误,需要设置相应的错误头,以便调用 jQuery 错误函数。

底线:您很可能没有向 AJAX 函数返回 HTTP 错误代码,导致成功函数始终被调用。

【讨论】:

    【解决方案3】:

    不要使用前端语言来验证表单输入。

    我看到对“request_tutor_process.php”的 AJAX 调用使用 POST,所以 request_tutor_process.php 应该有类似的内容:

    if($_POST['action'] == 'formSubmit'){
        //Let's say you have this function called 'add_to_database'
        attemptToAdd = add_to_database();
        //Let's say something went wrong with the form validation, and you return 'false'
        if(attemptToAdd === false) echo "Failed to submit, please try again later";
        //Let's say it worked, but it was unsuccessful (the username already exists)
        if(attemptToAdd === "unsuccessful") header('Location: /failed.php');
        //Let's say it worked fully...
        if(attemptToAdd === "successful") echo "It worked, click *here* to continue;
    }
    

    【讨论】:

    • 出于用户体验目的,您实际上应该结合使用前端和服务器端。
    • @1owk3y 我更新了我的问题。你可以看到我的php代码。
    【解决方案4】:

    试试这个:

         success: function (data) {
              $("#loading-image").hide(); //hide loading          
              $("#result").html(data);
    
            if(data == "success") {
              setTimeout(function () {
                $('input[type=submit]').attr('disabled', false);
                window.location.href = "login/index.php";
              }, 2000);
            } else {
              alert('error');
              return false;
            }
    

    顺便说一句,PHP 有点乱,但这不是问题所在。本质上是因为数据具有成功的价值,而您没有处理错误

    【讨论】: