When using back button AJAX results have been lost - javascript

So I've set up a pagination system similar to Twitter's where where 20 results are shown and the user can click a link to show the next twenty or all results. The number of results shown can be controlled by a parameter at the end of the URL however, this isn't updated with AJAX so if the user clicks on one of the results and then chooses to go back they have to start back at only 20 results.
One thought I've had is if I update the URL when while I'm pulling in the results with AJAX it should—I hope—enable users to move back and forth without losing how many results are shown.
Is this actually possible or have I got things completely wrong?
Also, how would I go about changing the URL? I have a way to edit the URL with javascript and have it be a variable but I'm not sure how to apply that variable to the URL.
Any help here would be great!
A side note: I'm using jQuery's load() function to do all my AJAX.

Not mentioned in the duplicate threads, but useful nonetheless: Really Simple History (RSH).

This would be the answer I would put here:
Browser back button and dynamic elements

You can't actually change the url of the page from javascript without reloading the page.
You may wish to consider using cookies instead. By setting a client cookie you could "remember" how many results that user likes to see.
A good page on javascript cookies.

The answer for this question will be more or less the same as my answers for these questions:
How to show Ajax requests in URL?
How does Gmail handle back/forward in rich JavaScript?
In summary, two projects that you'll probably want to look at which explain the whole hashchange process and using it with ajax are:
jQuery History (using hashes to manage your pages state and bind to changes to update your page).
jQuery Ajaxy (ajax extension for jQuery History, to allow for complete ajax websites while being completely unobtrusive and gracefully degradable).

First 3 results google returns:
first
second
third
I'll eat my shorts if none of them are useful. ^^
And yeah - you can't change URL through JS.

Related

Forward redirect to previous page

I have a webpage which is linked to from a number of different webpages, a user clicks a link on one of the parent pages, arrives at the webpage and completes a task. When the task is complete the user needs to be redirected to the previous page.
I'm aware I could use the window.history.back() / window.history.go(-1) functions - however what i'd really like is something which the browser considers a 'forward' action so as not to confuse the users if they click the forward/back button after a redirect.
I've tried using document.referrer but this gets blanked in the event of a page reload on the webpage.
The solution would need to be compatible back to IE8 (unfortunately!). Any suggestions would be much appreciated.
Fetching referrer URLs can be unreliable no matter which language you use https://stackoverflow.com/determining-referer-in-php
The best option is to pass the parent url to the task along with the data that you are already sending, despite the initial time outlay (updating the parent pages to do this) it would be the most reliable.
You could try and do a similar thing with a session or cookie to store the url upon starting the task, but it depends on how you have written the current task as to wether you would still need to modify the parent pages.
What about providing a parameter (it may be even the whole url to go after the action) that will let the page know where to go? (like login pages usually do).
It will probably imply modifying all your pages, so it may not be a solution in your case.

(Temp) Storage of JSON Search Results in Web App

I'm working on a search function for my Web app (HTML, JS & CSS only). I'm using jQuery's .getjson() method to retrieve data from a feed and display those results on a page. Inside of an .each() statement I'm adding HTML markup to the results making some of the elements links to outside sources.
The issue is when a visitor initiates a search on my Web app and clicks on a link from the results to an outside page, then uses the Back button on the browser to go back to the results page, all of the search results are cleared and another search needs to be initiated.
I'd like to temporarily save the search results so if a user clicks on a link from the results, then presses the Back button to come back to the app, all of the results will be available without the new for another search.
Taking this one step further, it would also be cool is the results for past searchs also persists so if the visitor continues to press the Back button, they can see all of their previous searches (with a given limit of course).
HTML5 sessionStorage seems to be ideal for this, but the information that I found points to a tedious coding solution. Can't I just save all of the json results as a JS object and have them re-rendered by my each statement when the visitor presses the Back button? I'm definitely open to using a code library or plugin for this problem.
http://brian.io/lawnchair/ is a good little library for API for persistence. You can use the same syntax as an abstraction for different storage options http://brian.io/lawnchair/adapters/
You have two ways to approach this issue, one is caching the results on your server and populating the view on-demand, and number two is like you previously mentioned - use sessionStorage. sessionStorage (IMO) has a very straightforward API. You can either use sessionStorage.setItem(key, value) or sessionStorage.getItem(key) -- other methods are available as well such as sessionStorage.key(index), sessionStorage.removeItem(key) and sessionStorage.clear(). It would probably be useful to include a cross-browser polyfill solution for sessionStorage, you can check out the "Web Storage" polyfills section at Modernizr: https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills -- Have fun :-/
Off the top of my head:
Every time the user searches, change the hash in the url to a unique string (e.g. 'search-{userInput}' ... you could of course just forget about the 'search-', but I like my urls in pretty). This should give you back-button support. Then:
Alternative A:
Listen for the hashChange Event, parse the window.location.hash and resend the request to your search URL. Theoretically, unless adding the timestamp to the URL or crazy stuff like that, the caching mechanism of your browser should kick in here. If not, it means an additional request, but that should be ok, shouldn't it?
Alternative B:
Extend your existing search query mechanism by caching the results to localStorage (just don't forget to JSON.stringify it beforehand and use a something-{timestamp} key). Then listen for the hashChange Event and pull the results from your localStorage. Personally, I wouldn't recommend this solution as you're clogging up the localStorage (afaik there's a limit at 2.5mB for some browsers).
You're probably going to have to find ways to circumvent missing browser support for at least the hashChange Event, JSON stringify/parse and LocalStorage, but I'm optimistic that there are enough libs/plugins out there by now.
You think too complicated: your search form most likely does not change the url! Use GET instead of POST and you have the desired result. Right now the browser has no way of knowing which state of the website you want to show and by default shows the first - the empty search form
Caching could be added as suggested, but that really is not the problem here

Javascript Refresh One Time Without Utilizing Hashtags

I'm using an orgy of javascript functions and scripts and they're conflicting a bit.
I have a page which already utilizes a hashtag in order to function correctly but one of the functions doesn't work unless the page is refreshed.
I've done a bit searching and have found a few ways to refresh the page but it checks to see there is a hashtag already in the url... and in my case I already do so it doesn't help.
I want to be able to refresh the page ONE time and that's all... without checking to see if there are hashtags in the url.
Help would be appreciated. Thanks
This might be what you are looking for:
function doRefreshOnce(){
if(localStorage["refreshed"]=="false"){
localStorage["refreshed"]="true"
location.reload();
}
}
What do you mean by once?
Once ever? Once per user? Once per visit? What if a user has two tabs with the same page open? should it refresh in one of those tabs or both?
if you need once ever that needs to be handled server side.
once per user could be handled using local storage or a cookie
once per "visit" (i.e. once per set of tabs) could be handled by a cookie
once per tab/visit needs to be handled by the URL, be that using fragment identifiers or a querystring.

Facebook makes their AJAX calls through iframe?

I want to implement AJAX like facebook, so my sites can be really fast too. After weeks of research and also knowing about bigPipe (which is not ajax).
so the only thing left was how they are pulling other requests like going to page/profile, I opened up firebug and was just checking things there for what I get if I click on different profiles. But the problem is, firebug doen'tt record any such request and but still page gets loaded with AJAX and changes the HTML also, firebug does show change on html.
So I'm wondering, if they are using iframe to block firebug to see the request or what? Because I want to know how much data they pull on each request. Is it the complete page or only a part of page, because page layout changes as well, depending on the page it is (for example: groups, page, profile, ...).
I would be really grateful if a pro gives some feedback on this, because i cant find it anywhere for weeks.
The reason they use iframe, usually its security. iframes are like new tabs, there is no communication between your page and the iframe facebook page. The iframe has its own cookies and session, so really you need to think about it like another window rather than part of your own page (except for the obvious fact that the output is shown within your page).
That said - the developer mode in chrome does show you the communications to and from the iframe.
When I click on user's profile at facebook, then in Firebug I clearly see how request for data happens, and how div's content changing.
So, what is the question about?
After click on some user profile, Facebook does following GET request:
http://www.facebook.com/ajax/hovercard/user.php?id=100000655044XXX&__a=1
This request's response is a complex JS data, which contain all necessary information to build a new page. There is a array of profile's friends (with names, avatar thumbnails links, etc), array of the profile last entries (again, with thumbnails URLs, annotations, etc.).
There is no magic, no something like code hiding or obfuscation. =)
Looking at face book through google chromes inspector they use ajax to request files the give back javascript which is then used to make any changes to the page.
I don't know why/wether Facebook uses IFRAMEs to asynchroneously load data but I guess there is no special reason behind that. We used IFRAMEs too but now switched to XMLHttpRequest for our projects because it's more flexible. Perhaps the IFRAME method works better on (much) older browsers, but even IE6 supports XMLHttpRequest fine.
Anyway, I'm certain that there is no performance advantage when using IFRAMEs. If you need fast asynchroneous data loading to dynamically update your page, go with XMLHttpRequest since any modern browsers supports it and it's fast as HTTP can be.
If you know about bigPipe then you will be able to understand that,
As you have read about big pipe their response look like this :-
<script type="text/javascript"> bigpipe.onPageArrive({ 'css' : '', '__html' : ' ' }); </script>
So if they ajax then they will not able to use bigpipe, mean if they use ajax and one server they flush buffer, on client there will no effect of that, the ajax oncomplete only will call when complete data received and connection closed, In other words they will not able to use their one of the best page speed technique there,
but what if they use iframe for ajax,, this make point,, they can use their bigpipe in iframe and server will send data like this :-
<script type="text/javascript"> parent.bigpipe.onPageArrive({ 'some' : 'some' });
so server can flush buffer and as soon as buffer will clear, browser will get that, that was not possible in ajax case.
Important :-
They use iframe only when page url change, mean when a new page need to be downloaded that contains the pagelets, for other request like some popup box or notifications etc they simple send ajax request.
All informations are unofficial, Actually i was researching on that, so i found,
( I m not a native english speaker, sorry for spelling and grammer mistakes! )
when you click on different profile, facebook doesn't use ajax for loading the profile
you simple open a new link plain old html... but maybe I misunderstood you

To build a `Delete` -button efficiently with JavaScript / PHP

Which of the following code is better in building a delete -action for removing a question?
1 My code
<a href='index.php?delete_post=777>delete</a>
2 Stack Overflow's code
<a id="delete_post_777>">delete</a>
I do not understand completely how Stack Overflow's delete -button works, since it points to no URL.
The id apparently can only be used by CSS and JavaScript.
Stack Overflow apparently uses JavaScript for the action.
How can you put start the delete -action based on the content of CSS -file by JavaScript?
How can you start a SQL delete -command by JavaScript? I know how you can do that by PHP, but not by JavaScript.
Your method is not safe as a user agent could inadvertently crawl the link and delete the post without user intervention. Googlebot might do that, for instance, or the user's browser might pre-fetch pages to speed up response time.
From RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1
9.1.1 Safe Methods
Implementors should be aware that the
software represents the user in their
interactions over the Internet, and
should be careful to allow the user to
be aware of any actions they might
take which may have an unexpected
significance to themselves or others.
In particular, the convention has been
established that the GET and HEAD
methods SHOULD NOT have the
significance of taking an action other
than retrieval. These methods ought to
be considered "safe". This allows user
agents to represent other methods,
such as POST, PUT and DELETE, in a
special way, so that the user is made
aware of the fact that a possibly
unsafe action is being requested.
Naturally, it is not possible to
ensure that the server does not
generate side-effects as a result of
performing a GET request; in fact,
some dynamic resources consider that a
feature. The important distinction
here is that the user did not request
the side-effects, so therefore cannot
be held accountable for them.
The right way to do this is to either submit a form via POST using a button, or use JavaScript to do the deletion. The JavaScript could submit a hidden form, causing the entire page to be reloaded, or it could use Ajax to do the deletion without reloading the page. Either way, the important point is to avoid having bare links in your page that might inadvertantly be triggered by an unaware user agent.
Bind a click event on the anchor which start with "delete_post_" and use that to start an Ajax request.
$("a[id^='delete_post_']").click(function(e){
e.preventDefault(); // to prevent the browser from following the link when clicked
var id = parseInt($(this).attr("id").replace("delete_post_", ""));
// this executes delete.php?questionID=5342, when id contains 5342
$.post("delete.php", { questionID: id },
function(data){
alert("Output of the delete.php page: " + data);
});
});
//UPDATE
With the above $.post(), JavaScript code calls a page like delete.php?id=3425 in the background. If delete.php contains any output it will be available to you in the data variable.
This is using jQuery. Read all about it at http://docs.jquery.com/How_jQuery_Works.
The url you are looking for is in the js code. Personally I would have an id that identifies each <a> tag with a specific post, comment... or whatever, and then have a class="delete_something" on each one, this then posts to the correct place using javascript.
Like so:
Delete
<script type="text/javascript">
jQuery('a.delete_post').live('click', function(){
jQuery.post('delete.php', {id: jQuery(this).attr('id')}, function(data){
//do something with the data returned
})
});
</script>
You're quite correct that absent an href="..." attribute, the link would not work without JavaScript.
Generally, what that JavaScript does is use AJAX to contact the server: that's Asynchronous JavaScript and XML. It contacts a server, just as you would by visiting a page directly, but does so in the background, without changing what page the browser is showing.
That server-side page can then do whatever processing you require. In either case, it's PHP doing the work, not JavaScript.
The primary difference when talking about efficiency is that in a traditional model, where you POST a form to a PHP page, after finishing the request you must render an entire page as the "result," complete with the <head>, and with all the visible page content.
However, when you're doing a background request with AJAX, the visitor never sees the result. In fact, it's usually not even a human-readable result. In this model, you only need to transfer the new information that JavaScript can use to change the page.
This is why AJAX is usually seen as being "more efficient" than the traditional model: less data needs to travel back and forth, and the browser (typically) needs to do less work in order to show the data as part of the page. In your "delete" example, the only communication is "delete=777" and then perhaps "success=true" (to simplify only slightly) — a tiny amount of information to communicate for such a big effect!
It all depends on how your application is built, what happens at Stack Overflow is that the delete link click is caught by JavaScript and an Ajax request is being made to delete the post.
You can use a JavaScript library to easily catch clicks on all elements that match your selector rule(s).
Then you can use Ajax to send a request to the PHP script to do the SQL work.
On a side note, ideally you would not use GET for deleting entries, but rather POST, but that's another story.

Categories

Resources