Load web pages with AJAX - javascript

Is it possible to load full web pages with AJAX and how would I go about it?
I'm thinking that I can create individual pages as I normally would, and then use AJAX somehow to get that page, and present it where the user currently is. Is that the correct assumption to make?
Basically I'm aiming to make a more dynamic site, so when the user clicks an option it will scroll down and reveal the requested info, without a noticeable page redirect.
Any advice would be great.
Thanks.

Jquery's .load(url) method loads HTML direct into an element. So if you changed every <a> tag to be a .load() on your top-level element you could do this. It would be a bit like using frames, but targeting a DIV instead of a frame.
Of course it would break lots of things like the back-button, form handling etc etc unless you put a lot of work in.
So, like the doctor who when told "It hurts when I do this" replied "well don't do that then", the answer is probably "dont do that".

One possible way is to fetch the HTML and then write it into a div

Yes it is possible. You could create a page/site from pure JavaScript fetching all elements from a web service or similar handler. It's a nightmare to maintain though, and you run into all sorts of problems depending on your needs. I did it as an exercise in learning jQuery, AJAX and a few other things. I found form submissions became tricky. While the data is posted to a web service with AJAX, managing the state of the page became very convoluted, and it only got nightmarish as the needs of the site grew.
I also found that in order to accomplish this, you have to make a choice to refresh the entire interface during transitions or just the section being changed. Refreshing the entire interface is cumbersome and for "rapid" users, the AJAX may not be able to keep up. It also causes collisions on the web service requests. If your page has 4 separate sections being updated, it is not uncommon for a web service request to be "lost" in the middle leaving a section without an update.
So the answer to your question is "yes". Reading your question closely, I would keep the scope of your requests to individual display pages without much functionality. The simpler you keep it, the easier it is to maintain and use.

I know this is an old post but this is a nice little script that can do the job. It can add ajax content loading to a existing non ajax site. Requires jQuery.
Script
<script type="text/javascript">
//Your navigation bar, can be "document" or body
var $navigation = $(".side");
//Your main content that will be replaces
var body = ".page";
var $body = $(body);
$navigation.delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function() {
var newHash = window.location.hash.substring(1);
if(newHash) {
$body.fadeOut(200, function() {
$body.hide().load(newHash + " " + body, function() {
$body.fadeIn(200, function() {
});
});
});
};
});
$(window).trigger('hashchange');
</script>
Details
All the links under $navigation will have a click event added to them that will update the window url hash. The window is listening for the hash change and will use the hash value to make an AJAX request to reload the $body html.
Advantage
History (Back & Forward) navigation will work:
The same site will work with browsers that support JavaScript and browsers that don't;
If you copy past the url the script will load the correct page;
Because we are using the delegate function any links that are added via the result of the ajax load will also have the click event added to them
Disadvantage
You can no longer use anchors on your site
For more information and a example see: http://css-tricks.com/video-screencasts/85-best-practices-dynamic-content/

Related

Loading Pages with Bookmark and Back/Forward Support

I am making a web page that has multiple different pages under multiple directories.
The way this is currently set up is that there is a main page A.
On Page A there is a menu that has links to other pages. These pages are loaded into a div on page A using AJAX.
I'm currently trying to make it so users could bookmark the page with the current content from the menu they selected already loaded. I've done this by making a GET variable and posting the page "directory/name". The issue now though is to make it so the user can press the back button on their browser giving the same functionality of a page that isn't loaded like this.
Is there some way that back functionality can be used to get the previous pages and load them? I know the easiest way of doing this is forgetting about the loading of the pages and it will fix pretty well all of the problems, however at this point I'm curious of a workaround for this.
Javascript is being used but the jQuery library is not.
Cheers.
EDIT: Adding basic code functionality.
<div id="content">
<p>Hello</p>
</div>
<p onclick="load('dir/file')">Link1</p>
<p onclick="load('dir/file')">Link2</p>
<script>
window.onbeforeunload = function() {
load(getVar("page"));
}
function getVar (name) {
name = RegExp ('[?&]' + name.replace (/([[\]])/, '\\$1') + '=([^&#]*)');
return (window.location.href.match (name) || ['', ''])[1];
}
function load(val) {
loadPage(val+".html", "content"); //This just does an ajax call and puts the content into the second value.
window.history.pushState({},"IBM","https://labweb.torolab.ibm.com/groups/websphere/WASL3/l3_new/index.php?page="+val);
}
</script>
I think that's the basic functionality of it.
I think what your asking about is hash tag browsing.
jquery javascript: adding browser history back with hashtag?.
This example uses jquery but all you have to do is put an event when the link is clicked to update the page sounds like you have something like that already.
Change the URL in the browser without loading the new page using JavaScript
This example gives you a better idea of what you would do with just Javascript.
Now this will not when they load the page using the bookmark because there is no browser history but will work when using your pages.
<a href="#hashtag" class="loadpage" data-page="directory/name">

JavaScript in jQuery mobile not working unless I refresh

I'm having a jQuery mobile page with JavaScript inside. The problem is the JavaScript doesn't work unless the page is refreshed. Here is my code:
jQuery(function($) {
var url = window.location.search.substring(1);
$('#mydiv').load('real_news.asp?' + url);
});
To understand this problem you need to understand how jQuery Mobile works.
Your first problem is point where you are trying to initialize JavaScript. From your previous answers I can see you are using several HTML/ASP pages and all of your javascript is initialized form the page <head>. This is the main problem. Only the first HTML file should have JavaScript placed into the <head> content. When jQuery Mobile loads other pages into the DOM it loads only the <div> with a data-role="page" attribute. Everything else, including <head>, will be discarded.
This is because currently loaded page has a <head> already. No point in loading another pages <head> content. This goes even further. If you have several pages in a second HTML file, only the first one is going to be loaded.
I will not try to invent warm water here so here are links to my other 2 answers discussing this problem. Several solutions can be found there:
Why I have to put all the script to index.html in jquery mobile (or in this blog article)
Link fails to work unless refreshing
There's more then enough information there to give you an idea what to do.
The basic solutions to this problem are:
Put all of your JavaScript into a first HTML/ASP file
Move your JavaScript into <body>; to be more precise, move it into a <div> with data-role="page". As I already pointed out, this is the only part of a page that is going to be loaded.
Use rel="external" when switching between pages because it will trigger a full page refresh. Basically, you jQuery mobile that the page will act as a normal web application.
As Archer pointed out, you should use page events to initialize your code. But let me tell you more about this problem. Unlike classic normal web pages, when working with jQuery Mobile, document ready will usually trigger before page is fully loaded/enhanced inside the DOM.
That is why page events were created. There are several of them, but if you want your code to execute only once (like in case of document ready) you should use the pageinit event. In any other case use pagebeforeshow or pageshow.
If you want to find out more about page events and why they should be used instead of document ready take a look at this article on my personal blog. Or find it here.
Your question isn't exactly overflowing with pointers and tips, so I'm going with the thing that immediately sprung to mind when I saw it.
Document ready does not fire on page change with jQuery Mobile, due to "hijax", their method of "ajaxifying" all the links. Try this instead...
$(document).on("pageshow", function() {
var url = window.location.search.substring(1);
$('#mydiv').load('real_news.asp?' + url);
});
Try pageinit like this
$(document).delegate("body", "pageinit", function() { // Use body or page wrapper id / class
var url = window.location.search.substring(1);
$('#mydiv').load('real_news.asp?' + url);
});
seems like nothing ever worked for me. Tried many different fixes, but i made the site too messy, that even position of certain javascript files wouldn't make the site work. Enough talk, here is what i came up with.
// write it in head at top of all javascripts
<script type="text/javascript">
$(document).ready(function() {
// stops ajax load thereby refreshing page
$("a,button,form").attr('data-ajax', 'false');
// encourages ajax load, hinders refresh page (in case if you want popup or dialogs to work.)
$("a[data-rel],a[data-dialog],a[data-transition]").attr('data-ajax', 'true');
});
</script>

How to change style of an element on another page using JavaScript or jQuery?

Ok, this is my problem... I have two pages. On the first page I have a header (h2) element on which I want to apply a border style. On the second page, there is only one link. When clicking on the link from the second page, to navigate to the first page, it should create a border on the first page around the h2 tag.
Any thoughts on how to do this? Is it possible to do it with regular JavaScript or jQuery?
Thanks!
No, JavaScript is client-side and for this you would require the server to remember if the link was clicked, possibly by recording this in a database or session variable.
That's of course if you're using the tradition model of a website, rather than loading pages already using pure JS.
It would be a pretty stupid way of doing it, but it is possible to do it client side. I would seriously recommend to do it server-side though.
On page 2, link back to page 1 with a hash:
Go back to page one and add a border
And on page 1, check if there's a hash:
if (window.location.hash === '#border') {
$('h2').addClass('withBorder');
}
I think if you are looking this kind of scenario you can achieve it with passing some hash to the url:
i passed a hash named 'second' in the second page url and put this script on second page
$(function(){
var url=window.location;
var hash = url.hash.substr(1);
if(hash == "second"){
$('h2').css('border','solid 1px red');
}
});
Checkout this if helps.
Well there is a way you could do this with JavaScript, although it's tricky and server side is a LOT easier. You would need to use some JavaScript to load different pages without refreshing the entire DOM. I do this with something called pjax. The way it works is to have each page act as a container to load all subsequent pages via ajax. By not doing a full page reload, any style changes you make on one page get carried over to other pages (this dose not survive an actual browser refresh).

Looking for a demo website that uses the simplest form of re-use for multiple pages as possible

In teaching students in an intro web class, I want to find the most straight-forward way of building a multipage static site of about 7 pages without having them have to make 7 different pages.
Obviously, I can have them make a separate header, footer, and menu file, and use server side includes, and just put the includes onto 7 different pages of content - but that feels dirty.
In the past I had them doing it this way: http://www.tropicalteachers.com/web110/?Ignore_WEB_119_CLEAN:MX_-old_Extra_Credit:Dynamic_PHP - this was a quick experiment using the assignment as a model: http://www.yetirobotics.org/index2.php?pagename=team_yeti
but i feel like there should be a cleaner/simpler way to do it using javascript, or maybe in php - but i'm not sure of how.
Basically i'd like one main page with a menu -and when the menu items are clicked, it loads different content. I believe it's better to have the content in seven different files, but i could imagine it all being in the same JS within one page- remember, this site should be pretty simple.
I'd like to limit it to html/css/js/php, and preferably js OR php and not both.
with just the index page controlling (and loading) everything.
Thanks!
If you want to create a more modern framework then you should look into using javascript for displaying content dynamically (as you suggested in your question). To do this I would make use of a framework like jQuery as it makes asynchronous request calling far more simple. To do this you would code a single page with a specific area marked for the dynamic content.
Server side you would setup either pages or a database to return the main content area that will change upon request.
Client side you can use jQuery's load to place the requested content into the content area.
$('#contentArea').load('url', function() {
//callback area in case there is other stuff you want to do with js
location.hash = 'blah';
});
It would probably make sense to change the page's hashmark so that pages still seem static and are linkable as content changes.
location.hash = 'blah';
In addition you will need to override default link behavior by returning false when they are clicked.
myLink.click = function() {
$('#contentArea').load('url', function() {
//callback area in case there is other stuff you want to do with js
location.hash = 'blah';
});
return false;
}
I think this would be a good lesson for students as it shows the differentiation between client-side, server-side, and how to connect them dynamically via javascript.

Dynamic content with JavaScript which allows linking

Let's say I want to create a website that contains one page. All the content is dynamic and generated using JavaScript with DOM replacement. The good thing about this is that it creates a better user experience, especially for applications that contain catalogues (online stores, galleries, etc). The problem now comes with linking. Let's say I'm browsing the site and I feel like sharing that particular thing I'm looking at with someone, but the problem is the link is always the same since it's JavaScript that's doing the magic. So the question comes: how can I create a fully JavaScript run website while maintaining the ability to link?
Now there's hash linking, but I'm failing miserably. I've tried overriding all <a> tags, changing the hash, and preventing the default action like so
$("a").click( function(){
window.location.hash = $(this).attr("id");
processHash();
return false;
});
Yet, it will randomly scroll my body for no reason.
I'd like some insights on the restrictions of linking in a fully dynamic website. Thanks.
Here is one simple thing you can do:
window.onload = function () {
processHash();
}
or it can be using jquery $(function () {...});
what happens here is when the page is loaded example http://www.example.com/#some-link
the page content is loaded first then your function that handle links processHash(); will do its work
not even the new and shiny jQuery mobile library is 100% ajax, but it's close. Obviously with a very modern browser, checkout this doc site done in jQuery mobile: http://jquerymobile.com/test/
If you dig in the docs a little you see how they use hash linking with the framework and html5 data-content="page"
each <div data-content="page">Is an independent page, if I remember right</div>

Categories