I have this Jquery Ajax function to login in a web page.
url=\"createUrl(\"security/login\") ?>\"
$.ajax({
It seems a lot of people are confused about client vs server when it comes to Ajax. Let me see if i can clear that up:
Your JS runs in the browser (client). PHP runs on the server. The two are different languages that run on entirely different machines; they don't share the same variables or anything. They do not talk directly to each other, or really even know anything about each other. Their sole means of communication is via HTTP requests. (Well, there's WebSockets too...but that's a bit advanced yet.)
JS and PHP typically do not even run at the same time. Depending on your setup and where this script lives, one of two things is happening, and in this case, neither one is what you want.
The JS is in a file of some type the server doesn't feed to PHP. The PHP code is still in the file when the browser sees it -- and being invalid JS, causes a syntax error when you try to run it. Probably before you even get to do the Ajax post.
The JS is in a file of some type the server does feed to PHP. The PHP interpreter dutifully goes through the file, finds all the PHP code in it, and parses and runs it. The PHP code in it runs on the server, possibly before the page is even sent to the browser. (And since PHP doesn't speak JS, and doesn't even care if what it generates is valid HTML or JS...any non-PHP code in the page is irrelevant.) Anyway, by the time the browser runs your script above, it looks like this:
...
success: function (jsonResponse) {
var json=JSON.parse(jsonResponse);
if(json.result == "SUCCESS")
{
}
},
...
because PHP has already gone through the file and interpreted the bit about setting $_SESSION['LOGGED_USER']
. If the user has an active session at all, logged in or not, that LOGGED_USER variable is set the second his browser requests that page.
The PHP script that's handling requests for security/login
needs to set the session variable. Your JS won't be able to do it, as the session data is entirely server-side, and you can't let the browser just up and tell the server to run arbitrary PHP code without opening up a massive security hole. (Picture what could happen if the browser could say "hey, PHP, run this". All i'd have to do is pop up a JS console, see how you're doing it...and at the very least, i could write a line of JS in the console to set that variable whether i'm logged in or not.)
Or, if you really wanted, you could create another page that the JS posts to, that sets the session data. That seems a waste, though...and it might be quite difficult to do securely. (If PHP doesn't already know you're logged in, you'd have to re-authenticate and all that.) I wouldn't consider it unless for some reason security/login
can't be modified.