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.

Everything good
  • 321
  • 4
  • 10

1 Answers1

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.

Channing
  • 68
  • 7
  • Thanks but still stays on the same page. – Everything good Nov 03 '20 at 22:49
  • @Everythinggood are you expecting a reload or the jquery replacing the existing html? – Channing Nov 03 '20 at 22:51
  • Thanks for your help. I want it to be the reload. – Everything good Nov 03 '20 at 22:53
  • 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. – Channing Nov 03 '20 at 23:01
  • Thanks for your help. i was wrong at my php code. just went through it – Everything good Nov 03 '20 at 23:07