Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reloading a page via AJAX when window.location=self.location doesn't work

On my homepage I got:

<ul id="login">
  <li> <a id="loginswitch" href="./login-page">log-in</a> | </li>
  <li> <a id="signupswitch" href="./signup-page">sign-up</a> </li>
</ul>

Via MooTools, I get these anchor elements by id so that once they're clicked, a flashy div will popup below them that contains the login or signup form (with methods to stop the propagation of events of course) and upon filling-up the fields the AJAX call kicks in - that's supposed to create a session and reload the page so that the user would have a visual that he is now logged in and user-level-controls appears etc..

The ajax call is initiated by the MooTools AJAX class and evalScripts option is set to true. The AJAX page returns the script code:

<script type="text/javascript">window.location = self.location;</script>

This system works perfectly - now I'm wondering why if I change the anchors' href values to href="#" my scripts won't work anymore?

Does it have anything to do with the window?

Did it change its property when I clicked a link or so even when the event's propagation was stopped??

like image 390
lock Avatar asked Oct 08 '08 02:10

lock


1 Answers

window.location = self.location;

This JavaScript is executing.

When it executes, the browser is being told to replace the value of window.location with a new value. Not all browsers will react the same way here. Some will probably work as you expect, but others will get smart about it and compare the two values. The browser knows what page it's on, and it knows that you're just asking for it to go to the same page.

Browser Cache

The browser even has a copy of your current page in cache. It can talk to the server and ask whether the page it has in cache is still valid. If the cache is valid, it may decide not to force a reload of the page. Behind the scenes, this happens with HTTP headers. Browsers and servers can communicate over HTTP in many ways. In this case, your browser sends a quick request to the server saying something like this:

GET /stackoverflow.com/posts/196643/index.html
HTTP/1.1
Host: www.stackoverflow.com
User-Agent: Mozilla/5.0
If-Modified-Since: Sun, 12 Oct 2008 20:41:31 GMT

This is called a conditional GET request. By saying If-Modified-Since, your browser is saying, "Give me that file, but only if it has been modified since the last time I saw it."

Long story short, you haven't explicitly told the browser to reload the page.

Here's how you can:

location.reload( true );

The "true" is an optional parameter, for forcing a reload. The browser won't even look at the cache. It will just do as you say.

like image 59
keparo Avatar answered Oct 12 '22 23:10

keparo