Loading Content Via Ajax - ajax

Ok, so I'm pretty new to ajax and loading content externally and would appreciate any insight to my problem.
I currently have a hidden div that is empty where the ajax content should load in after a link is clicked.
<div id="#ajax-wrap"></div>
I currently have a list of links that all have the same class and I'd like to have, when clicked, the blank div do a slide toggle and then load in the content from the page that the link was to.
Link:
Current jQuery:
$("a.home-right").click(function () {
$('#ajax-wrap').slideToggle();
});
Being as I'm new to Ajax and loading the external content, I'd like to know how to load content from the linked page that's house in the #content tag. So essentially, I'd like a .home-right link, #ajax-wrap would slide toggle, and then Ajax would pull content from the linked page (which is always going to be a different random link) and it's #content div, placing that content in #ajax-wrap.
Thanks in advance for any help folks!

You want to set the ajax for the links. Requirements:
Writing a handler for links.
We must cancel the default behaviour of browser when somebody click on a link (that redirect to the page).
Removing old data ajax recieved from server and make the #ajax-wrap fresh.
Load the remote page via ajax and set it to #ajax-wrap.
Now slide it down.
// Document Ready
$(function () {
// attaching click handler to links
$("a.home-right").click(function (e) {
// cancel the default behaviour
e.preventDefault();
// get the address of the link
var href = $(this).attr('href');
// getting the desired element for working with it later
var $wrap = $('#ajax-wrap');
$wrap
// removing old data
.html('')
// slide it up
.slideUp()
// load the remote page
.load(href + ' #content', function () {
// now slide it down
$wrap.slideDown();
});
});
});

You can simply use the ajax like this:
$("a.home-right").click(function () {
$.ajax({
type: "get",
url: "YOUR URL HERE",
success: function(data){
$('#ajax-wrap').html(data);
$('#ajax-wrap').slideToggle();
},
error: function(){
alert("An error occured");
}
});
});

try this:
$(function(){
$("a.home-right").click(function () {
$('#ajax-wrap').slideUp();
var url = $(this).attr("href")
$.ajax({
type: "get",
url: url,
success: function(msg){
$('#ajax-wrap').html(msg)
$('#ajax-wrap').slideDown();
},
error: function(){
alert("An error occured");
}
});
})
})

Use get:
// Inside click handler
$.get('url_that_returns_data')
.done(function(response){
var $response = $(response);
$('#ajax-wrap').html($response.find('#content')).slideToggle();
});

Related

Load whole page in AJAX

Currently, I have a wordpress website. I want to load the whole page of the website. I am aiming to put a footer player on the website, and that will only work if the rest of the pages are loaded with AJAX.
The goal is to click on the link of for example an article, and that then the website with the article will load. Because the lay-out of the article page differ from the homepage, just loading one div is not enough (see http://newtheme.favoritefm.com).
I have tried this:
$.fn.initLinks = function() {
$("a",this).click(function() {
var url = $(this).attr("href");
// transition to loading phase ...
// Ajax post parameter tells the site lo load only the content without header/footer
$.post(href,"ajax=1",function(data) {
$("#content").html(data).initLinks();
// transition to normal phase ...
});
return false;
});
};
$(function() {
$("body").initLinks();
});
Doesn't do anything. What to do?
Use the full jQuery Ajax Method: $.post instead of $.post.
So your code should look like this:
$.fn.initLinks = function() {
$("a", this).click(function() {
var url = $(this).attr("href");
// transition to loading phase ...
// Ajax post parameter tells the site lo load only the content without header/footer
$.ajax({
url: url // your href attr..
success: function(data) {
$("#content").html($(data).filter('#content').html());
// This fills in the #content on the current page with the html in #content from
// the Request page
},
error: function() {
alert('Could not load Data!!');
}
});
return false;
});
};
$(function() {
$("body").initLinks();
});

jquery tabs not firing after content loaded via ajax

I have an index page, in wich I have jquery.js and jquery.tabs.js included.
this page load content via ajax into a . The content is a set of tabs, their contents and at the bottom of the loaded content I have a call to tabs().
in FF it only works when I load content after refreshing the index page, and if I hit the link to reload the content, it stops working. in IE it's not working at all.
These are my tabs:
<ul id="horz-tabs">
<li>tab1</li>
<li>tab2</li>
<li>tab3</li>
</ul>
then I have the containers following, and at the very end of the page loaded via ajax I have:
<script type="text/javascript"><!--
$('#horz-tabs a').tabs();
//--></script>
My ajax function loads the page properly. I am wondering how I can fix this issue. Thanks for any help or advice.
The ajax loading function is as follow
<script>
function async(target, href) {
var loading = '<div class="loading">Loading</div>';
jQuery.ajax({
url: href,
beforeSend: function() {
$(target).prepend(loading);
},
error: function() {
$(target).html("<span class='error'>Failed</span>");
},
success: function(results) {
$(target).html(results);
}
})
}
</script
Look like you are loading the tab html via ajax, that could be the problem since when your script is running the dom for the tab elements may not be existing.
So you need to have a success callback to the async load method and add execute $('#horz-tabs a').tabs(); in the load success callback.
function async(target, href) {
var loading = '<div class="loading">Loading</div>';
return jQuery.ajax({
url : href,
beforeSend : function() {
$(target).prepend(loading);
},
error : function() {
$(target).html("<span class='error'>Failed</span>");
},
success : function(results) {
$(target).html(results);
}
});
}
Then
async('some-div', 'tab-url').done(function(){
$('#horz-tabs a').tabs();
})

Load Ajax Content to Hidden Tab - Instead of Current Tab

I have a dashboard UI that utilizes a jQuery tabs script. Each tab loads its content via separate Ajax requests.
Here's the issue I'm having:
A user will open multiple tabs, one right after the other
Each tab is created and an Ajax request is made for each
The last tab to be created is currently open and each tab's content is displayed on this tab once the requests are complete
Once a user clicks on any tab, the content is set as it should be.
Basically, if the user opens a new tab ahead of a recent tab's Ajax request completing, both Ajax requested contents display on the current open tab until the user clicks on any tab and then everything is displayed as it should be.
I've tried setting the Ajax calls to async: false which solves the issue as it forces the ajax requests to complete and load on the current tab before allowing the user to open another tab, however the user feedback has been negative in that users think that the dashboard froze (which it has).
I've also set a timeout function to load the tab with a loading .gif and then make the async: false Ajax request. The user feedback as been the same, even with the timeout function as the loading gif stops it's animation once the Ajax request is made.
The Ajax requests looks like this:
$.ajax ({
url: report,
cache: false,
success: function(html) {
$("#loading").hide();
$("#tabcontent").append('<div id="c'+count+'" class="tabContentContainer">'+html+'</div>');
},
error: function(x, status, error) {
$.ajax ({
url: 'admin/error_notification.php',
type: "POST",
data:{
error: error
}
});
},
async:true
});
Keep track of the last request in some way and abort it when creating another request:
var jqxhr = {abort: function () {}};
/* various other code */
function loadTabOrWhatever() {
jqxhr.abort();
jqxhr = $.ajax({
/* ajax call in your question */
I would suggest having a separate tabcontent div that is paired with each tab (not just one #tabcontent div), and show/hide those when switching tabs. Then if a previous ajax call comes back later, and populates a tabcontent div that is now hidden, there's no harm done.
function loadTab(tabName) {
// Hide all tab content panes, then just show the one we want
$(".tab-pane").hide();
$("#tab-" + tabName).show();
$.ajax ({
...
success: function(html) {
$("#loading").hide();
$("#tab-" + tabName).append('<div id="c'+count+'" class="tabContentContainer">'+html+'</div>');
<snip>
Create your content panes like:
<div class="tab-pane" id="tab-firsttab"></div>
And trigger links would be something along the lines of:
First Tab
I believe it would make it harmless then for users to quickly click on multiple tabs, firing off multiple ajax calls, since each ajax call will only load the content into it's own content pane.
I figured out that if I create the tabContentContainer div prior to the Ajax request, then the tab selector has a object to then hide when another tab opens. Then, once the Ajax response is loaded, the visibility of it has already been set. See below:
$("#tabcontent").append('<div id="c'+count+'" class="tabContentContainer"></div>');
$.ajax ({
url: report,
cache: false,
success: function(html) {
$("#loading").hide();
$("#c"+count+"").html(''+html+'');
},
error: function(x, status, error) {
$("#tabcontent").append('<div id="c'+count+'" class="tabContentContainer"><div class="alert alert-error" style="margin-top:70px;"><button type="button" class="close" data-dismiss="alert">×</button><strong>Don\'t worry… It\'s not you, it\'s us.</strong> We were unable to connect to your data and deliver results. We are looking into this now.</div></div>');
$.ajax ({
url: 'admin/error_notification.php',
type: "POST",
data:{
error: error
}
});
},
async:true
});
I have such a setup. You call the function below indicating what tab you're loading into. I make sure each new tab has a unique ID (UUID) and that the function gets that ID to load the page.
There is a snag, however - I have found that if the sub pages loaded contain javascript code, that needs to initialize objects internally to the page,
they may be confused by the fact that the page is 'hidden'. Sometimes when
I get back to the tab with such elements, I would find they have a 'small' size.
This function also store the data submitted to the backend, so that you easily can create a 'reload' button.
function LoadView(ident, view, data) {
var img = $('<img>', {
src : '/images/ajax-loading.gif'
});
$('#' + ident).html(img);
data.view = view;
data.viewid = ident;
// console.log(data);
$.ajax({
url : '/cgi-bin/browser.cgi',
data : data,
type : 'GET',
dataType : 'html',
timeout : 30000000,
success : function(result) {
$("#" + ident).html(result);
// set data on view
$("#" + ident).data('data', data);
},
error : function(xhr, status, error) {
var img = $('<img>', {
src : '/images/exclamation_micro.png'
});
$('#' + ident).html(img.html() + error);
// alert("Error processing request " + error);
},
timeout : function() {
var img = $('<img>', {
src : '/images/exclamation_micro.png'
});
$('#' + ident).html(img.html() + ' Timeout');
// alert("Timeout processing request");
}
});
}
function ReloadView(view, ident) {
// Retrieve the data for the view
var data = $('#' + ident).data('data');
// Reload the view
LoadView(ident, data.view, data);
}

How to know when page has been loaded with references completely after post in jquery ajax

I am using the below to get the whole page when I submit a form, now the page takes time to load as it calls its CSS and JavaScript.
I need to show that data is still being loaded in that page, before anybody uses it again.
I would like to use a modal popup with loading and once the page is loaded completely I will close the popup
How canI achieve that?
$.ajax({
type: "POST",
url: $url,
data: "post=" + post,
// data: form_data,
success: function(data) {
if(data!=""){
$('body').html(data);
...
additonal data:
I have two frames in a window. in the right side frame my page has links which when clicked will post certain data in hidden fields and get the whole right side page with the changed data. now my right side page has links such as
<link rel="Stylesheet" href="abc.css" type="text/css" />
<script src="jquery-1.6.3.min.js"></script>
<link href="jquery-ui.css" rel="stylesheet" type="text/css"/>
These files take time to be retrieved form server once the page is loaded by $('body').html(data); I want these files to be loaded and then let the user do his work
Use ajaxStart and ajaxEnd to show the loading message.
$("#myjaxloader").bind("ajaxStart", function(){
$(this).show();
}).bind("ajaxStop", function(){
$(this).hide();
});
Add the message and image in myajaxloader
You can use blockUI if you want more blocking features.
Since you are applying load to the entire body element, any modal popup display prior to this will be removed ready for the new content.
Therefore, I would suggest loading your content into a variable first by using $.get():
var content;
$.get($url, "post=" + post, function(data){
content = data;
});
This means you can have a loading icon displayed during this process, then load the content into the body which will remove the loading icon:
//show modal popup here
$.get($url, "post=" + post, function(data){
var content;
content = data;
if (content!=null){
$("body").html(content);
}
});
My syntax might not be quite right as I haven't been able to test this, but it should give you an idea of the logic which would work.
$(form).on('submit', function(e) {
e.preventDefault(); // to stop the page from reloading
$.ajax({
type: "POST",
url: $url,
data: "post=" + post, //use form.serialize to send the whole form
beforeSend: function () {
$(modal).show();
}
}).done(function(data) {
if(data!=""){ $('body').html(data); }
)).always(function() {
$(modal).hide();
});
});
You need to use the onload event of the loaded frame. If both your frames are on the same domain, you can do something like this:
navigation window:
$.post(url, data).then(
function() { // success handler
window.errorTimer = setTimeout(showErrorPopup, 10);
}, function() { // error handler
showErrorPopup();
}
);
showLoadingPopup();
content window:
$(function() { // runs after everything is loaded
window.top.otherFrame.clearTimeout(window.top.otherFrame.errorTimer);
window.top.otherFrame.hideLoadingPopup.call(window.top.otherFrame);
});

Ajaxify hyperlink so on success will load content otherwise redirect as default

I have a <a href> hyperlink. I used JQuery so clicking the link will load contents into a div in the current page (i.e. stay in the same page), and it works now.
However I also want that, if the request fails, the link act normally and go to the href url.
I tried e.preventDefault(); and return false; in the success: callback function, but they are not in the correct scope. If I place e.preventDefault() in the calling function, I can't reverse that effect later.
Here is my code:
$('a.more-link').click(function(e){
var postId=$(this).closest('div.post').attr("id").replace(/^post-(.*)$/,'$1');
var postContent=$(this).parent();
$.ajax({
url:"?action=ajax_load_post&id="+postId,
success:function(data){
postContent.html(data);
// Can't access e.preventDefault, nor return false;
},
error:function(data){
}
});
e.preventDefault();
});
Don't worry about the preventDefault(), just redirect the user in the error function like this:
$('a.more-link').click(function(e){
var postId=$(this).closest('div.post').attr("id").replace(/^post-(.*)$/,'$1');
var postContent=$(this).parent();
var _this = $(this);
$.ajax({
url:"?action=ajax_load_post&id="+postId,
success:function(data){
postContent.html(data);
},
error:function(data){
window.location = _this.attr('href');
return false;
}
});
});

Resources