1

I've an html form which I validate with Php using Jquery. After successfully inserting data to a database it's showing a success message in an html page and redirect to different page. Well, it's working fine but if there is an error it's also redirecting to a different page.

What I want:
If there is an error it's should stay on this page. If there is no error then it's should redirect to a different page. How can I do this with 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 page:

$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";
    }
}
Shibbir
  • 257
  • 4
  • 24
  • How are you validating PHP with jQuery? PHP is serverside, jQuery is client side. They can't interact directly. Are you really sure you want to set a click event on the entire body? What does your PHP code look like? – Zarathuztra Jul 13 '14 at 16:11
  • @Zarathuztra after press the submit button it's call the php page using jquery on click method. After inserted data to db php is return success message to jquery which is `$("#result").html(data);` – Shibbir Jul 13 '14 at 16:13
  • Required reading: [Why check both isset() and !empty()](https://stackoverflow.com/q/4559925/2943403) – mickmackusa Mar 20 '23 at 03:35

4 Answers4

0

This is the likely culprit

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

After your code succeeds, you're setting a global timeout that redirects the page every two seconds. For some reason, since you aren't showing your PHP code, it always succeeds. Basically, as long as a response comes back as valid (HTTP response code 200) it will always be successful. If there is an error on the PHP side, you need to set the appropriate error headers so that the jQuery error function is invoked.

Bottom line: You are very likely not returning an HTTP error code to your AJAX function, causing the success function to be invoked at all times.

Zarathuztra
  • 3,215
  • 1
  • 20
  • 34
0

Don't use a front-side language to validate form input.

I see the AJAX call to 'request_tutor_process.php' uses POST, so request_tutor_process.php should have something like:

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
  • 1,115
  • 1
  • 15
  • 30
0

Your problem is that it will always enter the success block, right?

If so, follow @Zarathuztra answer and set HTTP code to anything other than 200 in you PHP code, and add an error block to deal with the error. Refer to this answer Return errors from PHP run via. AJAX?

Or you can check the value of data and see if it's an error.

Community
  • 1
  • 1
Bhoomtawath Plinsut
  • 1,337
  • 1
  • 16
  • 31
0

Try this:

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

By the way that PHP is a bit of a mess but that's not the question. Essentially because data has a value it's succeeding and you're not handling the error

Rick Calder
  • 18,310
  • 3
  • 24
  • 41