AJAX loading a page without reload - javascript

I am trying to load content from a new page using AJAX. The test website I am working on is dev.dog-company.com.
This is my code:
$('a[rel="load"]').click(function(){
//var siteurl = "";
var link = $(this).attr("href");
$(this).attr("href", '#');
$('#slider-wrapper').slideUp();
$('#content').wrap('<div id="wrap"></div>').css('opacity', '0.75').css('background-color', 'black');
$.ajax({
type: 'POST',
url: link,
success : function(data){
var response = $(data);
var head= response.find('head');
var slider = response.find('#slider-wrapper');
var content = response.find('#content');
$('#content').unwrap('<div id="wrap"></div>')
jQuery("head").html(head);
if(slider != null)
jQuery("#slider-wrapper").html(slider).slideDown();
jQuery("#content").html(content);
return false;
}
$(this).attr("href", link);
})
});
I am trying load the content on click but the page reload everytime without the click working. Also I am not sure if I need to be doing something else other than what I am doing to my code. The rel="load" is only on home, info->AboutUs & FAQ.
Your help is appreciated.
Update:
I still can't get it to work. This is my latest code. And the site is still running it. When i use the debugging for chrome it never goes through my code. is it the re="load" that is causing the problem?
Update:
My initial problem was not having the document ready. But not I think the way I am parsing the information isn't working. I tried find and filter both seem to not work correctly. Also how do I change the url in the browser after I it pushes the post.
Update
After a lot of messing around with it I got it to partially work. One thing I can't do it replace head. and then the data pushed in slider is there but it does not seem to work on the website. It doesn't slide down like I have it in the code.
$('document').ready(function() {
$('a[rel="load"]').click(function(e){
//var siteurl = "";
e.preventDefault();
var link = $(this).attr("href");
$('#slider-wrapper').slideUp();
$('#content').wrap('<div id="wrap-overlay"></div>');
/*$('#wrap').css({
'opacity': '0.75',
'background-color': 'black',
'z-index' : '10'
});*/
$.ajax({
//ajax setting
type: 'POST',
url: link,
dataType: 'html',
success : function(data){
//parse data
var response = $("<div>").html(data);
console.log(typeof(response));
console.log(response);
//var head = response.find('<head>').html();
slider = response.find('#slider-wrapper').html();
var content = response.find('#content').html();
console.log(content);
//console.log(head);
//console.log(slider);
//Post data
$('#content').unwrap();
//jQuery("head").empty().append(head);
if(slider != null){
jQuery("#slider-wrapper").empty().slideDown().append(slider);
}
jQuery("#content").empty().append(content);
return false;
}
})
});
});

Try this:
$('a[rel="load"]').click(function(e) {
e.preventDefault();
// ...
});
You need to stop default browser behaviour on link click, which is following it.

Related

e.preventDefault() on a link still loads the page

the title may be a bit misleading but I'm not sure how to phrase it better, so I apologize for that.
I'm creating a custom handler so the site doesn't refresh when new content is pressed (similar to how youtube works, for example).
For that I'm using this script:
$('.sidebar2 li a').click(function (e) {
test = true;
var button = $(this);
var noteId = button.data("noteid");
$(".sidebar2 li.active").removeClass("active");
var postData = { id: noteId };
$.ajax({
url: '/API/Note',
type: 'get',
data: postData,
success: function (resp) {
if (resp.success == true) {
$('#app-bar-left').html(resp.note.navBarHTML);
$('#cell-content').html(resp.note.noteContentHTML);
window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
document.title = resp.note.title;
$('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")
e.preventDefault();
test = false;
return false;
}
}
});
});
even though I've stated e.preventDefault() to trigger, javascript loads the new content into the current frame without refreshing, but the browser refreshes again anyway.
I've tried to use href="#" however in this case when I go back and handle that, I always end up with two same pages, one without and one with # at the end, and in addition to that it wouldn't be very user friendly to have all links href="#"
What am I doing wrong to make the browser redirect "normally" even though I've told him no no no?
I've also tried adding onclick="javascript:void(0)" on a elements and that didn't help
ajax is async. By the time success callback is called event will already be bubbled up the DOM tree and processed. You need to call preventDefault before sending a request.
$('.sidebar2 li a').click(function (e) {
e.preventDefault(); // here for example
test = true;
var button = $(this);
var noteId = button.data("noteid");
$(".sidebar2 li.active").removeClass("active");
var postData = { id: noteId };
$.ajax({
url: '/API/Note',
type: 'get',
data: postData,
success: function (resp) {
if (resp.success == true) {
$('#app-bar-left').html(resp.note.navBarHTML);
$('#cell-content').html(resp.note.noteContentHTML);
window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
document.title = resp.note.title;
$('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")
test = false;
// returning here makes no sense also
// return false;
}
}
});
});

Can't find storyboards using Ajax

Hey you all.
var $storyboards; // This is the wrapper were all stroy boards are.
// Listen to URL changes when clicking the back or forward buttons in the browser.
window.onpopstate = function(event) {
LoadPage(document.location.pathname, !history.state || stateCount > history.state.stateCount);
};
var stateCount = 0;
$( document).ready(function() {
$storyboards = $('#storyboards');
$('.storyboard').attr('data-url', location.pathname);
setTimeout(function(){
$('body').addClass('splash-screen-hidden');
}, 3000);
$(document).on('mouseover mouseout','#menu a', function(e){
$('#menu a').not(this).toggleClass('toggle');
}).on('click', '#menu a', function(e){
if(e.metaKey || e.ctrlKey) return;
// Listen to the click event on the a tags in the menu
// Prevent the default behavior so the browser doesn't load the page.
e.preventDefault();
var $this = $(this);
var url = $this.attr('href');
var title = $this.attr('title');
NavigateToPage(url, title);
})
});
function LoadPage(url, back){
var $all_storyboard = $('.storyboard'); // This is all the storyboards we have in the page.
var $storyboard = $all_storyboard.filter('[data-url="' + url + '"]');
var storyboard_exists = $storyboard.length > 0;
PreparePageForLoad();
if(storyboard_exists)
StoryboardIsLoaded($storyboard.hide());
else {
console.log("we do not have the storyboard.. go load it!");
$.ajax({
url: url,
success: function(data){
$storyboard = $('.storyboard', data);
$storyboard.attr('data-url', url);
$storyboards.append($storyboard);
StoryboardIsLoaded($storyboard.hide());
},
error: function(){
alert('Oops! We could not load this page!.');
GoToRoot();
}
})
}
}
I really have a huge problem since I have to deliver my website project tomorrow morning and right now it's not working very well.
The real problem is I'm having trouble with loading between my pages. I'm using storyboard and ajax to switch out the code/content in the HTML without making a page load. So I get these sweet smooth transition between my pages.
I tested it on my own server and domain and it all works fine, but because I have to deliver the project/folder on another server the shit won't work. The main reason is that I have to put it all in a folder on the server and it's messing up the root navigation.
When I click on the link it goes: http://websitename.com/html-document/
But it should be: http://websitename/myfolder/html-document/
So the problem is it's going out of my folder and looking for the HTML document outside my folder instead of looking at it.
Here is the link to the website: http://franklyone.com/sylvester-svend/
Thanks in advance - Love

jQuery load won't work without alert even with a callback function in place

I load html content along with javascript (using getScript) on a page using the jquery load function with a callback. But I am encountering a strange situation in that the javascript that is being loaded isn't recognized either on the first try (it does work on the 2nd or subsequent try) or without an alert in place. I have read through similar situations and the suggested solution is to have a callback function for load. But I already have a callback function in place. Here is the code:
$("[id^=ajax_]").click(function(e){
var linkid = $(this).attr("id");
var arr = linkid.split("_");
var link = arr[1];
ajax_load_content_and_get_script(link);
});
function ajax_load_content_and_get_script(link) {
var url = "/" + link;
$("#pagecontent").load(url + "/ajax", function() {
//alert(); //works with this un-commented
$.getScript("/js/" + link + ".js");
});
}
As you could see above, the script that is being loaded (with getScript) is recognized and works fine if I have the alert statement uncommented. But without the alert, the script isn't recognized. I am already using a callback function for the load as seen above.
Thanks for your help with this.
look like this?
$("button").click(function(e){
var linkid = $(this).attr("id");
var arr = linkid.split("_");
var link = arr[1];
ajax_load_content_and_get_script(link);
});
function ajax_load_content_and_get_script(link) {
var url = "/" + link;
$.ajax({
url: url + "/ajax",
type: 'POST',
async:false
}).success(function(data){){
$("#pagecontent").html(data);
$.getScript("/js/" + link + ".js");
});
}
http://jsfiddle.net/aswzen/w4068ygL/3/

pushState and back button works but content doesn't change

It does load a new page and the url does update, but when I press the back button, only the url has changed without refreshing but the content doesn't.
$('button').click(function(){
window.history.pushState({}, '', 'page2.php');
$('body').html('<div class="loading.gif"></div>');
//Load Page
$.get('page2.php', function(data){
$('body').html(data);
};
//Edited
$(window).bind('popstate', function(){
//What should I code here??
});
});
I did something like that :
$(window).bind('popstate', function(){
window.location.href = window.location.href;
});
And it work wonderful.
The code is taking the location from the url and redirect to this url.
I use this to change bar adress and save current state, including current html body, and i reload it on back bouton click without any other ajax call. All is saved in your browser :
$(document).ajaxComplete(function(ev, jqXHR, settings) {
var stateObj = { url: settings.url, innerhtml: document.body.innerHTML };
window.history.pushState(stateObj, settings.url, settings.url);
});
window.onpopstate = function (event) {
var currentState = history.state;
document.body.innerHTML = currentState.innerhtml;
};
You need to implement the popstate event. When you click the back button after pushing a state, the page receives the popstate event. In it you need to replace the page contents with the correct page.
See an example from MDN
Updated code:
$('button').click(function(){
// Store some information in the state being pushed
window.history.pushState({url:'page2.php'}, '', 'page2.php');
$('body').html('<div class="loading.gif"></div>');
//Load Page
$.get('page2.php', function(data){
$('body').html(data);
};
//Edited
$(window).bind('popstate', function(event){
var url = null;
if (event.state && event.state.url) {
url = event.state.url;
} else {
url = 'index.html'; // or whatever your initial url was
}
// Update the contents of the page with whatever url was stored in the state.
$.get(url, function(data){
$('body').html(data);
};
});
});

Hide loading bar on no .HTML file found

I have the code below to find the next sequential page number and load it at the bottom of the page once the user hits the bottom of the screen.
the loading div slides down and as it is loading and up once it is done... it is set to "display:none" by default
What i need is a line of code in there which basically hides the #loading div if no more pages can be found to load... " var url = "page"+nextpage+".html";" finds the new page... titled 'page 2.html, page3.html' and so on.
Any help would be appreciated. I'm assuming it is easy but I can't find a solution anywhere...
alreadyloading = false;
nextpage = 2;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
if (alreadyloading == false) {
$("#loading").slideDown();
var url = "page"+nextpage+".html";
alreadyloading = true;
$.post(url, function(data) {
$('#newcontent').children().last().after(data);
alreadyloading = false;
nextpage++;
$("#loading").slideUp();
});
}
}
});
If there is no such file then the AJAX request will fail, so you can do what you need from inside a "failure" handler. To be able to specify that, you one solution is to move from using $.post to using the more configurable $.ajax, which gives you all the necessary options:
$.ajax({
type: 'POST',
url: url,
success: function(data) {
$('#newcontent').children().last().after(data);
nextpage++;
},
complete: function() {
alreadyloading = false;
$("#loading").slideUp();
}
});
The complete callback contains code which will be executed no matter what happens with the request; the success callback will be executed before complete, but only if the request was successful.

Categories

Resources