So, I have a page that has several links with onClick events that will retrieve data from external files and fill a div with this data. This works as intended. When I refresh the page, however, the div empties again. What I would like to happen is that after a refresh, the div will maintain the last content retrieved.
I'd prefer not to go down the road of cookies and have looked into adding data to the URL which I think is the way I want to go with this.
Is there some nice JQuery calls that can append data to url when a link is clicked and then on refresh restore the required content to the div?
My loadContent function is:
function loadContent (url, container) {
var target = $(container);
target.load(url, function (text, statusText) {
if (statusText === "success") {
target.find("a[rel^='gridnav']").initgn();
}
});
}
edit: I forgot to mention, the line
target.find("a[rel^='gridnav']").initgn();
is used to re-initialise a script on the new content loaded.
So when I click a link, the onClick event calls the function like this
TEST</li>
where xyz.html contains only the data I want inside the div "#right"
Is there a way to edit this function to do what I want ?
You can append data to the url by using
window.location.hash
https://developer.mozilla.org/en-US/docs/DOM/window.location
If you search for QueryString in jQuery plugins, there should be dozens of plugins that simplify this task.
I'd use localStorage. It's like cookies but much, much easier to maintain. The only downside is that it's not supported by all legacy browsers (See http://caniuse.com/#search=localStorage for browser support). For an orview on thhe feature, see https://developer.mozilla.org/en-US/docs/DOM/Storage If you want to go with completely no cookie like features at all; well then it has to be done server side to the best of my knowledge
Without cookies, your task will be a little bit harder. But I may have two solution for you:
Using session on server, you can control which ajax has been call, so next time when the main page is loaded, you can append the new content to it.
Using url hash to append ajax anchor has been click #anchorname so you can click it a gain after reload.
The comment tells you how you can modify the url without a page load. You could use that. If you have to work with older browsers, then you can still use the fragment (or do both things).
There are some history plugins for jQuery/JavaScript that manage this .. it's a technique called "deep linking." You may be able to find something simple to work with. Basically when loadContent runs you would want to update the url from /whatever to /whatever#right with the fragment indicating the load-content ID or something like that.
Another alternative would be to set some flag on the server that loads into that div when the page loads initially, which would save you an ajax request too. Depending on how your server code is set up that may not work for you, though.
Related
I need something to detect changes on the url but the page doesn't do post back, it changes dynamically adding just the div inside the html, so the URL page is something like this
http://www.examplepage/conversations/44455
and when I click on another section of the page it it is
http://www.examplepage/conversations/44874
it changes not only at the end but like this
http://www.examplepage/settings
without doing post back and reloading the javascript so my question is, is there a way to detect those changes? and event listener but how?
I search and everyone says hash event but I don't have any value after any hash so it doesn't work
EDIT
Just for the record I have no code of the page nor I have access, I'll explain better, I am doing a background google extension and I just added a slide out to an existing page, this page changes its url the way I explained above. the url changes like every page does, but they change the div inside the html so that the page doesn't have to charge everything again
You need to store the URL when the page loads as a starting point and setInterval to check for changes and modify based on that.
The following code does this check twice a second (500ms):
// store url on load
let currentPage = location.href;
// listen for changes
setInterval(function()
{
if (currentPage != location.href)
{
// page has changed, set new page as 'current'
currentPage = location.href;
// do your thing..
}
}, 500);
There is no "clean", event-based way to detect such URL changes from a content script.
They are done with history.pushState API - and using that API doesn't emit any DOM event.
Two possible indirect event-based approaches, besides the already mentioned poll-based one:
An extension can override history.pushState with an injected script to additionally emit a DOM event that can be listened to in a content script.
This approach is described in detail here.
The downside is that, depending on the code of the page in question, the injected script may need to be injected early, needing run_at: document_start which is suboptimal for page load performance.
Use a background page that listens to chrome.webNavigation.onHistoryStateUpdated event.
If you need to detect this in a background page — perfect,
you're done, without ever needing a content script.
If you need to detect this in a content script, you can use details.tabId in the event listener to send a message to the right content script.
My situation
First of all, I hope I can explain it right; I have an admin panel which will be fully ajax driven. It uses jquery to bind all internal (everything that uses domain.com/admin///* ) and instead of following the link it gets the page via ajax.
Problem
Lets say I have a table of news in which i want to dynamically delete one, it links to page which deletes the page. This link has the event to get the page dynamically linked to it, (because all the links are binded).
I want a good way to get feedback from the global ajax function handling the grabbing of the page and fadeout the row in the table. And thus a good way to reuse this.
$.ajaxcomplete works, but it KEEPS doing whatever i define, no way to reset it.
There are many questions that ask how to change the class of a div in a JavaScript click handler, e.g., here: Change Div style onclick. I understand that well (just change .className), and it works.
However, when I follow a link from my page to somewhere else, and then click the back button, the class names are reverted. (Safari and Firefox get it right, Chrome does not.) In Chrome, most other changes I make dynamically, e.g., to click handlers, are also reverted when I go back to the page (although it remembers freshly inserted new divs).
Note that neither Chrome nor the other browsers are reloading the page when I press "back"; they must just take it from the cache. (I update the state on the server using ajax, so it works fine when the browsers reload the page.)
I am not really a web developer, so this is a bit puzzling. What is the standard practice here? Should I use history.replaceState() every time I change the divs? Should I save the changes in a state variable and reload them every time there is a popstate event? Instead of changing div classnames, should I delete the div and insert a fresh one (with all the old div's children)?
I am using vanilla JavaScript here (no jquery even) and would prefer to keep it that way if possible.
It is possible, but you will need additional ways to remember it
You could try one of these:
Cookies: This definitely looks like the best way to go
Pass Vars on the URL: example: www.mywebsite.com?myvar=red. This would be easier using PHP, but still is possible in pure JS (but I don't recommend it)
Store it on Database: (don't recommend this at all)
Store it in input elements: In current browsers, input element values (of radio buttons, hidden, etc.), persist after POST-ing, and returning using the back button.
These are just some options, but I don't recommend using them for what you want (it is a waste of time and effort if you weight the Pros and Cons of what you want to do)
You can save state in cookies and restore it when page loaded.
Also you can save it on server-side (send state using ajax, when it changed). And send prepared document to client when it requested again.
Browser forget all states when you reload page.
How do I change the URL with jQuery without reloading the page?
Set location.hash
jQuery has nothing to do with it though, this is basic DOM 0.
You can only change the hash part of an url without a page refresh through location.hash.
Adding get parameters (?foo=bar) or a complete url change will always reload the page.
In HTML5 you get more options to change URL's, but right now (2010) it's not yet viable since crappy browser die out hard.
In general, leaving aside the new HTML history API, you can't.
It is possible to add data to the URL after the hash (using location.hash as David Dorward describes). However, if you want to do this to affect behaviour of the page, you will also need to read these changes via jQuery (or triggered by the same process that sets the hash.)
Outside of the History API you will not be able to add a parameter, and have the page 'just know about it'.
In testing document.location.href, I have observed that when the user initiates an action that results in javascript that assigns to document.location.href, the new URL is added to the history.
However, if the call is initiated by javascript that is result of, say, state change of an XMLHTTPRequest, the entry for the current page in the history is over-written. Have I characterized this correctly? Is there a way to get the page change to be reflected in the history in this latter case?
I was facing the same problem and found this workaround which worked for me
instead of
function onAjaxCallback(evt){
location.href=newLocation;
}
i wrapped the location.href call around a setTimeout. Seems to do the trick. My history's behaving fine now. Hope that helps
function onAjaxCallback(evt){
setTimeout(function(){
location.href=newLocation;
},0)
}
You could change the location without having the browser display a Back button like this:
window.location.replace(new_url);
However, the original address remains in the browser's history and may be accessed using something like CTRL+H
Reference:
https://developer.mozilla.org/en/DOM/window.location#replace
https://developer.mozilla.org/En/DOM/Window.history#Notes
study: window.location.replace() and window.location.assign()
URL can be manually added to history before redirecting the user.
if (window.history) {
history.pushState({}, window.location.href);
}
window.location.replace("/login/?next=" + window.location.pathname);
Read the original question more carefully. The question is not about content loaded by an XHR, but about content loaded by a script loaded by an XHR. I had the same problem and the setTimeout method seems to work well.
Alas, your question can't be answered, AJAX requests have nothing to do with browser history, and if you loaded some dynamic content with them, then the user clicked the browser back button, the previous page is loaded (this which was loaded with an ordinary GET or POST request), which corrupts the sequence you display content in.
Dmitri's answers means that you will maintain your own history for the dynamic content using the fragment part of the url (this after the # symbol), maybe you'll provide your own back and forward buttons, but still you're not protected from the effect of the browser back and forward buttons.
If only they had provided some kind of events to handle user clicks on these buttons with the ability to cancel.