简体   繁体   中英

Will php or jquery redirect me? Ajax login

I made an ajax call to the php script, which would indicate whether the information input by the user were valid and he would be authorized to sign in. The thing is I'm not really sure about the session variable. Can that php script save session id variable and pass it onto the next php page, where jquery would redirect me upon successful ajax call? Or would php itself redirect me using header location? I hope I made myself clear. It is a theoretical question.

You would set the userid in the session and return a "success" condition back to ajax. the ajax success callback would inspect the returned data to determine if the login was successful and act accordingly (for example, redirect to a logged-in homepage)

You cant not redirect with PHP in this case because the headers are not returned in the http response. you can set a variable in the response that returns the state of your php proccess. something like

data = array(
 "connect"=>true
);

or

data = array(
 "connect"=>false,
 "errors"=>"There is an error in your request"
);

then in the success: function you can check if the variable is true or false and redirect if you need to.

success: function(response){
  if(response.connect){
//succeded
}else{
//not succeded
}

hope that helps. cheers!

I disagree from @Mijail when he says

You cant not redirect with PHP in this case because the headers are not returned in the http response .

With jQuery (or plain XHR), you can verify if you got a redirection with the response status (one of 3xx) and then use getResponseHeader method from xhr object to get the 'location' header to see where you should be redirected :

success: function(data, textStatus, xhr) {
    if(xhr.status > 300 && xhr.status < 400) {
        document.location.href = xhr.getResponseHeader('location') || '/';
    }
}

This is the right way of doing it when you don't want to replicate your redirection rules on the client side too.

In theory you could do it either way, but without seeing your actual code, it's hard to give a definitive answer.

If you are using jQuery to call your auth PHP script and setting your session in that PHP script, you would likely then just use your JS (Ajax) to redirect to the "protected" area on success (returned from your PHP script with session started).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM