Hi there!

I'm using PHP together with jQuery/AJAX to submit a login form without reloading the page. Basically the code works like this:

Login.php (The actual form) -> process-login-admin.php (server-side validation and authentication) -> Echo error message
The error messages is displayed in a hidden div (#feedback) on "Login.php" that i set to visible once "login-process.php" echos something.

This is how i do it:

$.post('process-login-admin.php', $("#loginprocess").serialize(), function(data) {
                                                     $("#feedback").html(data).show("slow");
                                                     });
                                              }

Everything works just fine except one thing. When a user successfully logs in i would like to do a simple header location to the users dashboard/profile page. However the dashboard loads inside the message div i created instead of changing url.

Anyone that could give me a few pointers on how to solve this?

Dani AI

Generated

AJAX calls do not change the browser location; they just fetch a response and hand it to your callback. If the server sends a 3xx Location header, the XHR will follow it and return the final HTML to your callback, but the top-level URL will not change. To redirect after a successful login, return structured data (e.g., JSON) that tells the client what to do, then navigate in JavaScript.

Example pattern:

$.ajax({
  url: 'process-login-admin.php',
  method: 'POST',
  data: $('#loginprocess').serialize(),
  dataType: 'json'
}).done(function(res) {
  if (res && res.ok && res.redirect) {
    window.location.replace(res.redirect); // avoids creating a back button entry
  } else {
    $('#feedback').text(res.message || 'Login failed.').show();
  }
}).fail(function(xhr) {
  $('#feedback').text('Unexpected error (' + xhr.status + '). Please try again.').show();
});

On the server, respond with JSON and an appropriate status:

header('Content-Type: application/json; charset=UTF-8');
if ($authenticated) {
    echo json_encode(['ok' => true, 'redirect' => '/dashboard']);
} else {
    http_response_code(401);
    echo json_encode(['ok' => false, 'message' => 'Invalid credentials.']);
}
exit;

If you also support non-AJAX form posts, detect them server-side and do a normal redirect (e.g., 303 See Other) for progressive enhancement. As a security note, regenerate the session ID on login and set secure cookie flags.

See jQuery.ajax, MDN Location.replace, and the OWASP guidance on session management at the Session Management Cheat Sheet.

Recommended Answers

All 4 Replies

Because you are using AJAX, you will have to handle the redirect in Javascript, not PHP. So instead of doing the header in PHP, notify Javascript with a particular string (or JSON), to do the redirect for you.

Thank you pritaeas!
I seem to have solved it by doing this once the user is logged in:

echo '<script>location.href="index.php";</script>' ;

Is there any downside to this approach? Will this work in all browsers?

echo '<script>location.href="index.php";</script>' ;

why not just do header('Location: index.php"); if you are echoing it out?

There should be a point in your js where the login succeeds and redirect then:

messageDiv.innerHTML = req.responseText;
if(req.responseText == 'Success'){window.location = 'index.php';}

i always thought it was window.location, since your login is javascript the redirect should 100% work window.location is a very wide standard

or you could just fill in the div contents with the contents of the dashboard if you have that available in ajax

if(req.responseText == 'Success'){
contentDiv.innerHTML = getMyDashboard();
}

Thanks Biiim!

Your answer got me in the right direction. I have solved this by implementing your "responsText" method.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.