0

Am trying to redirect to a page based on my response. But am doing it wrong. Tried the answers Here But not working. my Ajax script is below.

   success: function (response) {
      if (response === 'success') {
        window.location.replace("home");
      } else {
        $(".error_message").fadeIn();
        $(".error_message").html("");
        $(".error_message").html(response);
        $(".error_message").fadeOut(5000);
      }
    }

My php code is below

            if ($stmt->execute()) {
                echo "success";
            }
            $stmt->close();

It echoes the message after the form was submitted successfully.

But i want it to reload not getting stuck at the same page.

1 Answer 1

1

Try the following:

AJAX:

   success: function (response) {
      if (response.success) {
        alert(response);
        location.reload();
      } else {
        $(".error_message").fadeIn();
        $(".error_message").html("");
        $(".error_message").html(response);
        $(".error_message").fadeOut(5000);
      }
    }

PHP:

if ($stmt->execute()) {
    return json_encode(array("success" => true));
}
$stmt->close();

I changed the PHP so that it's sending a JSON response instead of plain text, along with it being in an array that has a success field which will be checked by the JavaScript to see if it's true or false.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks but still stays on the same page.
@Everythinggood are you expecting a reload or the jquery replacing the existing html?
Thanks for your help. I want it to be the reload.
Try adding alerts in the if statement to see if you get a response from it. I updated my answer with the alerts if you want to go off of that. Basically, I'm trying to see whether the response.success is true or not. If it doesn't pop up with an alert, then I'm going to move the alert above the if-else statement and alert the response.success variable to see what it's returning.
Thanks for your help. i was wrong at my php code. just went through it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.