I have codeigniter website which is done 1 year ago. No, I want to implement new HTML5 history API (pushstate) function to enable change content based on the url without header refresh. Is there any simple way, to avoid url restructure and load whole content using new HTML5 history API? I was trying to find some way, but most of them are using get methods.
$(function() {
$('nav a').click(function(e) {
$("#loading").show();
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.replaceState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
$("#loading").show();
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.getJSON("content.php", {cid: url, format: 'json'}, function(json) {
// THIS LOOP PUTS ALL THE CONTENT INTO THE RIGHT PLACES
$.each(json, function(key, value){
$(key).html(value);
});
$("#loading").hide();
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}
Here is demo for this : http://sandbox.cergis.com/html5-historyAPI/page1.php
I want to implement new HTML5 history API (pushstate) function to enable change content based on the url without header refresh.
pushState is there to allow you to change the url without loading a new page.
Is there any simple way, to avoid url restructure and load whole content using new HTML5 history API?
Changing the content is the job of DOM.
You can use XMLHttpRequest (or other Ajax techniques) to load new content from the server (and then insert that into the page using DOM manipulation)
Generally, you should use the history API in combination with DOM manipulation. You change the content of the page with DOM, then change the URL to one that the server can use to generate the same page from scratch. This means the page still works for users (including search engines) without JavaScript, and it avoids the homepage loading before being replaced (after a few seconds) with different content.
Related
I have a website where I need to update a status.
Like for a flight, you are departing, cruise or landed.
I want to be able to refresh the status without having my viewers to have and reload the whole page. I know there is a way to do it with AJAX and jQuery, but I don't have any understanding of how that works. I also don't want them to have and click a button.
If anybody knows how that would be done I much appreciate it!
This is typically achieved with a technique called AJAX. This technique loads data asynchronously (in the background) so it can update your content without needing to reload the page.
The easiest way to implement AJAX is with the jQuery load() method. This method provides a simple way to load data asynchronous from a web server and place the returned HTML into the selected element. The basic syntax of this method is: $(selector).load(url, data, complete); where the arguments are:
selector the existing HTML element you want to load the data into
url a string containing the URL to which the request is sent
data (optional) a plain object or string that is sent to the server with the request
complete (optional) a callback function that is executed when the request completes
The required URL parameter specifies the URL of the file you want to load.
The optional data parameter allows you to specify data (i.e. key/value pairs) that is sent to the web server along with the request. The optional complete parameter can be used to reference a callback function. The callback is fired once for each selected element.
A visualisation:
A simple example of using load(), where we load data dynamically when a button is pressed:
DEMO
// no need to specify document ready
$(function(){
// optional: don't cache ajax to force the content to be fresh
$.ajaxSetup ({
cache: false
});
// specify loading spinner
var spinner = "<img src='http://i.imgur.com/pKopwXp.gif' alt='loading...' />";
// specify the server/url you want to load data from
var url = "http://fiddle.jshell.net/dvb0wpLs/show/";
// on click, load the data dynamically into the #result div
$("#loadbasic").click(function(){
$("#result").html(spinner).load(url);
});
});
If you don't want to use the jQuery library, you can also use plain Javascript. Loading content is slightly more difficult that way. Here is an example of how to do it with javascript only.
To learn more about AJAX, you can take a look at https://www.w3schools.com/xml/ajax_intro.asp
Suppose you want to display some live feed content (say livefeed.txt) on you web page without any page refresh then the following simplified example is for you.
In the below html file, the live data gets updated on the div element of id "liveData"
index.html
<!DOCTYPE html>
<html>
<head>
<title>Live Update</title>
<meta charset="UTF-8">
<script type="text/javascript" src="autoUpdate.js"></script>
</head>
<div id="liveData">
<p>Loading Data...</p>
</div>
</body>
</html>
Below autoUpdate.js reads the live data using XMLHttpRequest object and updates the html div element on every 1 second. I have given comments on most part of the code for better understanding.
autoUpdate.js
window.addEventListener('load', function()
{
var xhr = null;
getXmlHttpRequestObject = function()
{
if(!xhr)
{
// Create a new XMLHttpRequest object
xhr = new XMLHttpRequest();
}
return xhr;
};
updateLiveData = function()
{
var now = new Date();
// Date string is appended as a query with live data
// for not to use the cached version
var url = 'livefeed.txt?' + now.getTime();
xhr = getXmlHttpRequestObject();
xhr.onreadystatechange = evenHandler;
// asynchronous requests
xhr.open("GET", url, true);
// Send the request over the network
xhr.send(null);
};
updateLiveData();
function evenHandler()
{
// Check response is ready or not
if(xhr.readyState == 4 && xhr.status == 200)
{
dataDiv = document.getElementById('liveData');
// Set current data text
dataDiv.innerHTML = xhr.responseText;
// Update the live data every 1 sec
setTimeout(updateLiveData(), 1000);
}
}
});
For testing purpose: Just write some thing in the livefeed.txt - You will get updated the same in index.html without any refresh.
livefeed.txt
Hello
World
blah..
blah..
Note: You need to run the above code on the web server (ex: http://localhost:1234/index.html) not as a client html file (ex: file:///C:/index.html).
You can read about jQuery Ajax from official jQuery Site:
https://api.jquery.com/jQuery.ajax/
If you don't want to use any click event then you can set timer for periodically update.
Below code may be help you just example.
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
Above function will call after every 10 seconds and get content from response.php and update in #some_div.
If you want to know how ajax works, it is not a good way to use jQuery directly. I support to learn the native way to send a ajax request to the server, see something about XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://some.com");
xhr.onreadystatechange = function () {}; // do something here...
xhr.send();
I am not sure what to call this but in google plus, when you navigate to different pages, the HTTP address changes but the userbars seem to remain static and not reload. What is happening and how is this done?
I hope this makes sense! Thank you!
AJAX (Asynchronously loading the content)
The content is being loading asynchronously and the url in the address bar is being altered.
An basic example of loading content asynchronously:
$.ajax({
url: 'http://www.example.net/load.html',
dataType: 'html',
success: function(data){
// This will replace all content in the body tag with what has been retrieved
$('body').html(data);
}
});
See here for the $.ajax() documentation.
Modifying the URL without Redirecting
To change the url withour redirecting, you need to use the HTML5 history API. A similar question has been asked here before, please see:
Modify the URL without reloading the page
Extracted answer:
function processAjaxData(response, urlPath){
document.getElementById("content").innerHTML = response.html;
document.title = response.pageTitle;
window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath);
}
For more information on the HTML5 History API, please see here.
It's likely that they're using the HTML5 History API, specifically the pushState method to add new history states. They're also probably using Ajax (XHR) to load in new content and then adding that content to the page via the DOM API.
Check out pjax, a library that takes care of most of this for you.
I'm working on an ajax loading function on a Wordpress single page portfolio.
The principle is that when you click a thumbnail in the gallery, it opens a container (#DrawerContainer) and fetch the ajax content of this article into it. With a lot of help, I'm already able to open the drawer and load the post content when I click a thumbnail.
Here is a fiddle if you want to see it working (the ajax will not load but it works locally). http://jsfiddle.net/RF6df/24/
The part I'm working on now: I need my site to be crawlable and the urls to be shareable. If I give http://mywebsite.com/#!project5 to someone, I need project5 content to be opened when he loads the page.
I thought the hash-bang (#!) urls was the way to go to make this work. With the code below (commented on the jsfiddle), I can update the url and add the hash of the clicked thumbnail.
var pathname = $(this).find('a')[0].href.split('/'),
l = pathname.length;
pathname = pathname[l-1] || pathname[l-2];
window.location.hash = "#!" + pathname;
But when I load a page, the ajax state isn't remembered. I assumed it was because my ajax container was only loaded on click event, but there is no change when I add a persistant container in the php.
Is there a way to load the page with a post content already displayed, or to open the #DrawerContainer when the page is loading a hash-bang url?
Please keep in mind that I'm just learning jquery and ajax. So I'd really appreciate if you explain or comment a little bit what you do, I'll for sure learn at the same time... :)
on onload you should check the window.location.hash and trigger a click on the particular link/div.
$(document).ready(function() {
var hash = window.location.hash;
if ( hash.length > 0 ) {
hash = hash.replace('#' , '' , hash );
$('a[rel="'+hash+'"]').trigger('click');
}
});
I have used the following on sites where I want to trigger via hash changes.
First I bind a hashchange event to get the hash value
$(window).bind('hashchange', function(o){
url = window.location.hash.substring(1);
o.preventDefault();
if (!url) {
return;
}
}
Then I trigger the hashchange when I want - in your case when the page loads i.e. on document ready.
jQuery(document).ready(function($) {
$(window).trigger('hashchange');
});
You can then use the hash value in your function that loads the correct content
I'm working on a site that passes information to my server that returns a page, however I have to re-define the click listener every time I reload the page because jQuery controls all my clicks on every page, so I' m wondering is there a way to permanently define a function?
jQuery code:
$(function(){
$('.lvl1Links').on('click',function(event) {
event.preventDefault();
$('pload').html('<img src="source/image/lbl.gif">');
var page = $(this).attr('id');
var huh = $('input:hidden').val();
var data = 'pop='+huh+'&page='+page;
$.post('source/php/bots/authorize.php',data,function(data){
$('#pager_master_div').html(data).slideDown();
$('pload').html('');
});
});
});
Being a stateless platform, every time the page loads you need to rebind things like this. Here's the pattern I use to make it easier, though:
If this is common across an area of your site, put this type of stuff into an init function in the common file. e.g.
global.js:
function InitSalesPageOrWhatever(){
$(function(){ foo; });
OtherStuffThatRunsOnEverySalesPageLoad();
}
Then in the script block on your pages, e.g. SalesPage:
InitSalesPageOrWhatever();
That's it--just one line in your content pages. Beyond the benefit of the content pages being nice and clean, that big clump of JS can now be cached by the user's browser, making the load on you less and their experience faster.
jQuery (and all Javascript) runs on the client side where permanence is unavailable. There are two ways to approach the permanence you seek.
Write a jQuery plugin and include it in your page.
Write your click handler once, and use your server-side code/scripting language to include it in every HTML page. An example PHP include is here.
This may be a good time to consider HTML templates -- documents that contain standard HTML (header, footer, navigation, etc) that should be included in every page of your site.
I want to add a progress bar before my web page's content loads, so I thought of loading it dynamically via javascript. This content has embedded javascript in its html. I tried using jquery.load() which works perfectly besides the fact that it does not support the js that doesn''t work on the returned content
just to make it clear, what i'm doing is something like this to load all the content:
$("#contentid").html("progressBar.gif");
$("#contentid").load(script.php #content)
$("#contentid").show();
and inside the content returned from script.php there are js calls such as:
jquery.load (to crawl for data and displaying it when ready)
document.getElementById('some_div') (for chart api)
snippets that load widgets
I've been trying to work around with using jquery.ajax though not sure if\how its possible with it yet. would love for some input on that.should i be able to achieve that with it?
Any other idea that might show a progress bar till the script's content is loaded will be great. I'm trying to reduce changes in the code structure, since this long load happens only sometimes.
Thanks.
You may add a div with the progress bar, covering all the page, and remove it after the page is loaded, using:
$(window).load(function() {
$('#progressbar').remove();
});
JQuery's load method takes a callback function as an argument. That function will get called when the load is completed, so you can hide your progress bar at that point. Here is an example from their API docs:
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
In your case, it would be something like:
$("#contentid").load(script.php, function(){
$("#contentid").hide();
});