Ajax URL # isn't updating - ajax

I have a little problem with my script here. For some reason, it doesn't enable the #-tags and I don't know why. I created this javascript using the help of this tutorial. (The loading of the pages works well with no problems at all.)
Could someone please look it over and tell me why it doesn't work?
var default_content="";
$(document).ready(function(){ //executed after the page has loaded
checkURL(); //check if the URL has a reference to a page and load it
$('ul li a').click(function (e){ //traverse through all our navigation links..
checkURL(this.hash); //.. and assign them a new onclick event, using their own hash as a parameter (#page1 for example)
});
setInterval("checkURL()",250); //check for a change in the URL every 250 ms to detect if the history buttons have been used
});
var lasturl=""; //here we store the current URL hash
function checkURL(hash)
{
if(!hash) hash=window.location.hash; //if no parameter is provided, use the hash value from the current address
if(hash != lasturl) // if the hash value has changed
{
lasturl=hash; //update the current hash
loadPage(hash); // and load the new page
}
}
function loadPage(url) //the function that loads pages via AJAX
{
// Instead of stripping off #page, only
// strip off the # to use the rest of the URL
url=url.replace('#','');
$('#loading').css('visibility','visible'); //show the rotating gif animation
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0) //if no errors
{
$('#content').html(msg); //load the returned html into pageContet
} $('#loading').css('visibility','hidden');//and hide the rotating gif
}
});
}

You can simplify this immensely by adding a function to listen to the hashchange event, like this:
$(window).on("hashchange", function() {
loadPage(window.location.hash);
});
This way you don't need to deal with timers or overriding click events on anchors.
You also don't need to keep track of lasthash since the hashchange even will only fire when the hash changes.

Related

jquery .get download content fully before rendering

Is there a way to render content only after it's fully downloaded using AJAX/get/load with jQuery?
As it stands currently, the loader shows while the 'html' is being downloaded, but once that's done it starts rendering. There's lots of images in the html so they start loading independently after the render.
Is this good design practice? In my opinion once the loader disappears, everything should render 100%, but of course this will increase load time.
Can I achieve this without any 'hacks'?
$(document).ready(function() {
$('#clicks').click(function(){
$('#portfolio').append("<div id='loader'><img src='images/loader.gif'/></div>");
$.get("moreProjects.html", function(datas){
$('#portfolio').append(datas);
}, 'html').complete(function() {
$('#loader').hide();
});
return false;
});
});
You could always store the data returned in a variable and then append it in the complete function:
var returnedData;
$('#clicks').click(function(){
$('#portfolio').append("<div id='loader'><img src='images/loader.gif'/></div>");
$.get("moreProjects.html", function(datas){
returnedData = datas;
}, 'html').complete(function() {
$('#portfolio').append(returnedData);
$('#loader').hide();
});
return false;
});
Another option would be to use a hidden div container to load the content and then show on complete:
$('#clicks').click(function(){
$('#portfolio').append("<div id='loader'><img src='images/loader.gif'/></div>");
$('#portfolio').append("<div id='content' style='display:none'></div>");
$.get("moreProjects.html", function(datas){
$('#portfolio #content').append(datas);
}, 'html').complete(function() {
$('#portfolio #content').show();
$('#loader').hide();
});
return false;
});
Get the HTML, place it on your page or preload with JS, if placing it on your page the images can not be hidden if they are to be loaded, but they can be placed of screen.
When the images are loaded, move the HTML to your portfolio element.
The code below is just an example, not tested, and the load function will probably fire on the first image that is loaded, I think ?
If so you will have to count the images, place a load function on each image, and then show the HTML when all images have loaded, or you could try just attaching the load function to the last image in your HTML, but there is no guarantee that the last image in the markup is also the last to load, but it often is.
There could also be a problem with load if images are cached by the browser, if so you need to find another solution, or turn of caching in $.ajax!
$('#clicks').on('click', function(){
$('#portfolio').append("<div id='loader'><img src='images/loader.gif'/></div>");
var jqxhr = $.ajax({
type:'GET',
url: 'moreProjects.html',
datatype: 'html',
done: function(datas) {
$('<div id="somediv"></div>').append(datas)
.css({position: 'fixed', left: -5000})
.appendTo('body');
}
});
jqxhr.always(function() {
$('img', '#somediv').on('load', function() {
$('#loader').remove();
$('#portfolio').append($('#somediv').contents());
});
});
return false;
});
Check this link, the last post: Wait untill all images are loaded
In my opinion what you have to do is to save the html in a variable,
then filter out all the img tags and pass it to the _loadimages function
in the post i give you setting the complete callback.
Something like this:
var $retData = $(datas);
var $imgs = $retData.find('img');
_loadimages($imgs,function(){
$('#portfolio #content').append($retData);
});

How to use AJAX as an alternative to iframe

I'm trying to put together a snappy webapp, utilizing JS, Prototype and AJAX for all my requests once the GUI has loaded. The app is simple: A set of links and a container element to display whatever the links point to, just like an iframe. Here's an approximate HTML snippet:
<a class="ajax" href="/somearticle.html">An article</a>
<a class="ajax" href="/anotherarticle.html">Another article</a>
<a class="ajax" href="/someform.html">Some form</a>
<div id="ajax-container"></div>
The JS that accompanies the above (sorry it's a bit lengthy) looks like this:
document.observe('dom:loaded', function(event) {
ajaxifyLinks(document.documentElement);
ajaxifyForms(document.documentElement);
});
function ajaxifyLinks(container) {
container.select('a.ajax').each(function(link) {
link.observe('click', function(event) {
event.stop();
new Ajax.Updater($('ajax-container'), link.href, {
method: 'get',
onSuccess: function(transport) {
// Make sure new ajax-able elements are ajaxified
ajaxifyLinks(container);
ajaxifyForms(container);
}
});
});
});
}
function ajaxifyForms(container) {
console.debug('Notice me');
container.select('form.ajax').each(function(form) {
form.observe('submit', function(event) {
event.stop();
form.request({
onSuccess: function(transport) {
$('ajax-container').update(transport.responseText);
// Make sure new ajax-able elements are ajaxified
ajaxifyLinks(container);
ajaxifyForms(container);
}
});
});
});
}
When clicking a link, the response is displayed in the container. I'm not using an iframe for the container here, because I want whatever elements are on the page to be able to communicate with each other through JS at some point. Now, there is one big problem and one curious phenomenon:
Problem: If a form is returned and displayed in the container, the JS above tries to apply the same behavior to the form, so that whatever response is received after submitting is displayed in the container. This fails, as the submit event is never caught. Why? Note that all returned form elements have the class="ajax" attribute.
Phenomenon: Notice the console.debug() statement in ajaxifyForms(). I expect it to output to the console once after page load and then every time the container is updated with a form. The truth is that the number of outputs to the console seems to double for each time you click a link pointing to a form. Why?
I found another way to achieve what I wanted. In fact, the code for doing so is smaller and is less error prone. Instead of trying to make sure each link and form element on the page is observed at any given time, I utilize event bubbling and listen only to the document itself. Examining each event that bubbles up to it, I can determine whether it is subject for an AJAX request or not. Here's the new JS:
document.observe('submit', function(event) {
if (event.target.hasClassName('ajax')) {
event.stop();
event.target.request({
onSuccess: function(transport) {
$('ajax-container').update(transport.responseText);
}
});
}
});
document.observe('click', function(event) {
if (event.target.hasClassName('ajax')) {
event.stop();
new Ajax.Updater($('ajax-container'), event.target.href, {
method: 'get'
});
}
});
Works like a charm :)

Return false not working for jQuery live

Well this has me well and truly stumped. After searching for the last few hours I still cannot seem to work out where I am going wrong.
I am trying to append an AJAX response to a container when it gets clicked. That works fine but I don't want it to append another object when the elements from the AJAX response also gets clicked.... so:
<div id="container">
<!-- AJAX response to get inserted here, for example -->
<span id="ajaxResponse"></span>
</div>
Here is my script:
$('#container').click(function(e) {
var current_el = $(this).get(0);
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
}
});
return false;
});
So it works fine but for some reason the click event on #container also fires when I click on the AJAX response span!?
According to jQuery documentation:
To stop further handlers from
executing after one bound using
.live(), the handler must return
false. Calling .stopPropagation() will
not accomplish this.
But unless I am mistaken, I am calling false? :(
Anyone help me out on this?
UPDATED:
So the only way I can get it to work is by updating my code to this:
$('#container').live('click', function() {
var current_el = $(this).get(0);
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
}
});
});
$('#ajaxResponse').live('click', function(e) {
return false;
});
This seems a little messy though... anyone have a better solution?
Where is live part you mention in the title of the question ?
It is how the event model works.. If you click on element which does not handle the event, the event will travel up the DOM hierarchy until it finds an element that handles the click (and stops its propagation..). Otherwise you would not be able to put an image inside a <a> tag and click on it..
You can bind a canceling handler on the inner element assuming you have someway to target it..
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
// assuming the returned data from ajax are wrapped in tags
$(current_el).children().click(function(){ return false;});
}
});
I think the return false is referring to something else in this case...
you should try calling stopPropagation() - this should stop the "click" function from propagating down to the ajaxResponse span....
One option that you may want to try is switching over to using live(). Essentially, the click event you setup is calling bind(), and the solution you referenced is using live() which is a variation on bind().
For example:
$('#container').live("click", function(e) {
var current_el = $(this).get(0);
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
}
});
return false;
});
HTH

JQM (jQueryMobile) problem with AJAX content listview('refresh') not working

This is a mock of what I'm doing:
function loadPage(pn) {
$('#'+pn).live('pagecreate',function(event, ui){
$('#'+pn+'-submit').click( function() {
$.mobile.changePage({
url: 'page.php?parm=value',
type: 'post',
data: $('form#'+pn+'_form')
},'slide',false,false);
loadAjaxPages(pn);
});
});
function loadAjaxPages(page) {
// this returns the page I want, all is working
$.ajax({
url: 'page.php?parm=value',
type: 'POST',
error : function (){ document.title='error'; },
success: function (data) {
$('#display_'+page+'_page').html(data); // removed .page(), causing page to transition, but if I use .page() I can see the desired listview
}
});
}
in the ajax call return if I add the .page() (which worked in the past but I had it out side of the page function, changing the logic on how I load pages to save on loading times), make the page transition to the next page but I can see the listview is styled the way I want:
$('#display_'+page+'_page').html(data).page();
Removing .page() fixes the transition error but now the page does not style. I have tried listview('refresh') and even listview('refresh',true) but no luck.
Any thoughts on how I can get the listview to refresh?
Solution:
$.ajax({
url: 'page.php?parm=value',
type: 'POST',
error : function (){ document.title='error'; },
success: function (data) {
$('#display_'+page+'_page').html(data);
$("div#name ul").listview(); // add div wrapper w/ name attr to use the refresh
}
});
Be sure to call .listview on the ul element
If it didn't style earlier, you just call .listview(), bot the refresh function. If your firebug setup is correct, you should have seen an error message telling you that.
I didn't have time to get down to creating some code before you posted your fix, but here's a little recommendation from me:
if(data !== null){ $('#display_'+page+'_page').html(data).find("ul").listview() }
This is a bit nicer than a new global selector. Also - you don't need the div and you can provide a detailed selector if you have multiple ULs.
caution: the above code requires data !== null. If it's null - it will throw an error.
If you add items to a listview, you'll need to call the refresh() method on it to update the styles and create any nested lists that are added. For example:
$('#mylist').listview('refresh');
Note that the refresh() method only affects new nodes appended to a list. This is done for performance reasons. Any list items already enhanced will be ignored by the refresh process. This means that if you change the contents or attributes on an already enhanced list item, these won't be reflected. If you want a list item to be updated, replace it with fresh markup before calling refresh.
more info here.

jquery ajax post - not being fired first time

I'm trying to do an ajax post after a button is clicked, and it works in firefox but not in IE the first time the page is loaded. It does work if I refresh the page and try again second time - but not first time and this is crucial.
I've scanned over various web pages - could it be anything to do with the listener? (I've just seen this mentioned mentiond somewhere) Is there something not set correctly to do with ajax and posting when page first loads?
$(document).ready(function() {
$('#btnCont').bind('click',function () {
var itm = $("#txtItm").val();
var qty = $("#txtQty").val();
var msg = $("#txtMessage").val();
var op_id = $("#txtOp_id").val();
//if i alert these values out they alert out no prob
alert(itm+'-'+qty+'-'+msg+'-'+op_id);
$.ajax({
type: "POST",
url: "do_request.php?msg="+msg+"&itm="+itm+"&qty="+qty+"&op_id="+op_id,
success: function (msg) {
document.getElementById('div_main').style.display='none';
document.getElementById('div_success').style.display='block';
var row_id = document.getElementById('txtRow').value;
document.getElementById('row'+row_id).style.backgroundColor='#b4e8aa';
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error submitting request.');
}
});
});
I would start debugging the click event. I.e. if you try to put .bind into a a href tag, the tag itself has a click event that may act on an unwanted way. There exist a command that are named something like event.preventDefaults() that avoids the standard feature of click. After All, you try to manipulate the DOM last of all actions (document.load).
$('#btnCont').bind('click',function () { .. }
I would also try to debug the same functionality with adding onClientClick to the tag instead of adding bind to the document load.
I hope that bring some light.

Resources