I'm learning how to use jQuery methods of making AJAX calls, at the moment what I would like to know is how I use the $.ajax function to return a certain elements content. I realize this can be done easily enough using .load() but would like to get the results using .ajax(). At the moment I am fetching the clicked href attribute and returning the whole pages data when I would like to just return the #container content of the page?
Sample code being used:
jQuery(document).ready(function() {
/* Ajax load in portfolio pages */
var ajaxLoader = $('#ajax-loader');
var folioContainer = $('#folio-container');
ajaxLoader.hide();
$('div.wp-pagenavi a', 'div#content').click(function(e) {
$.ajax({
url : this.href,
method : 'get',
success : function(data){
folioContainer.html(data);
}
});
e.preventDefault();
});
});
You should be able to .filter() the response from the server to select only the data you want:
success : function(data){
folioContainer.html($(data).filter('#container'));
}
Here's a jsfiddle of this solution: http://jsfiddle.net/jasper/5HSzB/
Here's an optimized version of your code:
jQuery(function($) {
/* Ajax load in portfolio pages */
var ajaxLoader = $('#ajax-loader').hide();
$('.wp-pagenavi', '#content').find('a').click(function(e) {
$.ajax({
url : this.href,
method : 'get',
success : function(data){
$('#folio-container').html($(data).filter('#container'));
}
});
e.preventDefault();
});
});
You may be better off using the load method http://api.jquery.com/load/ , read the section "Loading Page Fragments"
not sure but try:
jQuery(document).ready(function() {
/* Ajax load in portfolio pages */
$('#ajax-loader').hide();
$('div.wp-pagenavi a', 'div#content').click(function(e) {
$.load(this.href + ' #folio-container');
e.preventDefault();
});
});
Related
I have following javascript code which loads information from multiple json files and appends them in HTML table if "info" parameter in URL is true.
$(document).ready(function(){
var appList=["app1","app2","app3"];
//function to get url parameters
var parameters = new URL(window.location).searchParams;
var info=parameters.get('info');
if (info=="true"){
for (var i=0;i<appList.length;i++){
setInfoAndDateUtil(app)
}
}
function setInfoAndDateUtil(app){
$.ajax({
url:'server_name/'+ app + '/info.json';
method: 'GET',
dataType: 'json',
contentType:'application/json',
success: function(jsonData){
var info=jsonData.info;
td=$("#" + app);
td.text(info).css("text-align", "center");
}
})
}
The ajax requests are taking some time since they are loading about 16 json files. So I want to add loading screen while this function executes.
I have tried few methods like this but none of them are working.
$(document).ajaxStart(function(){
$("#wait").css("display", "block");
});
$(document).ajaxComplete(function(){
$("#wait").css("display", "none");
});
Can anyone tell me how to do it exactly?
Use this approach using JQuery:
// Add Loader on ajax calls
$("body").prepend("<div id='spinner'><img src='/images/spinner.gif'></div>");
$(document).ajaxSend(function(){
$('#spinner').show();
});
$(document).ajaxComplete(function(){
$('#spinner').hide();
});
I am doing an ajax call and replacing the response inside a div class. At the first ajax call the response is replaced inside the class properly but 2nd time I got the data from response but the response in not replacing the data inside the class.
I am trying the below way.
$(document).on('click', '#approveallusers', function(){
var checked_ids = []
$("#UserList").find('input[type=checkbox]').each(function () {
var $this = $(this);
if($this.is(":checked") && $this.hasClass('selectbox')){
checked_ids.push($this.attr("userid"));
}
});
$.ajax({
url : '/approve-website-users',
method : 'POST',
data : JSON.stringify({'checked_ids':checked_ids}),
contentType : "application/json",
success : function(data) {
if(data.status == 'success') {
alert(data.res)
$('.users').replaceWith(data.res);
}
}
});
})
here data.res is an html element and its rendering from the server side.
Thanks..
.replaceWith will replace the div including html tags so there won't be any class users.
see this for more info:
http://api.jquery.com/replacewith/#replaceWith-function
maybe you need .innerHTML or .html
check here: http://api.jquery.com/html/#html-htmlString
I am building a Wordpress site. I am using Ajax to pull in content from another page to fill an empty div when a particular element is clicked. Each element has a different URL so I made the Url a variable. I need Ajax to only pull in a particular element from this URL. Instead it keep pulling in the entire page. I've tried using various methods to select the specific element, but I've hit a wall and need a little help.
(function($) {
function find_page_number( element ) {
return parseInt( element.html() );
}
$('.member-info').on('click', function (event) {
event.preventDefault();
page = find_page_number( $(this).clone() );
var memberSrc = $(this).attr('href');
$.ajax({
url: memberSrc,
type: 'get',
dataType:'html',
data: {
action: 'ajax_pagination',
query_vars: ajaxpagination.query_vars,
page: page
},
success: function( html ) {
$("#main").empty();
$('#main').append( html);
}
});
})
})(jQuery);
You can filter the answer with jQuery:
$('#main').append( $(html).find('#main').html() );
I am using JQuery when. The syntax looks like this:
$.when(
// Get the HTML
$.get("/feature/", function(html) {
globalStore.html = html;
}),
// Get the CSS
$.get("/assets/feature.css", function(css) {
globalStore.css = css;
}),
// Get the JS
$.getScript("/assets/feature.js")
).then(function() {
// Add CSS to page
$("<style />").html(globalStore.css).appendTo("head");
// Add HTML to page
$("body").append(globalStore.html);
});
My question
How can I do error handling when one of the call to the server results in exception (failure scenario) or error handling for any other scenario?
Since I am making Ajax request here, how can I define timeout period for the Ajax request?
deferred.then( doneCallbacks, failCallbacks ) can take a failure filter like
$.when(
// Get the HTML
$.get("/feature/", function(html) {
globalStore.html = html;
}),
// Get the CSS
$.get("/assets/feature.css", function(css) {
globalStore.css = css;
}),
// Get the JS
$.getScript("/assets/feature.js")
).then(function() {
// Add CSS to page
$("<style />").html(globalStore.css).appendTo("head");
// Add HTML to page
$("body").append(globalStore.html);
}, function(){
//there is an exception in the request
});
To setup the timeout, you can use the timeout option.
You can use it either globally like
jQuery.ajaxSetup({
timeout: 5000
})
or use $.ajax() instead of the short version $.get() with the timeout option
I think it is because the calls are async. When using:
$.ajax({
url: "file.php",
type: "POST",
async: false,
success: function(data) {
}
});
The call is synchronous.
I'm stuck in a rut. I hope some one can help.
Basically, I am building an AJAX mobile web app with jQuery. I am able to parse a specific XML file just fine, but I want the option to parse other XML files based on the link they were clicked on and load them on the fly into the same DIV or UL.
So:
click on Link1, loads XML1
click on Link2, loads XML2
I would like to be able to do this all client side, so no PHP (or is that a bad idea?). This the jquery code I've been using:
$(document).ready(function() {
$("a.load_ajax").click(loadAjax());
function loadAjax() {
var fileID = get('?lineID=');
var dataID = "xml/" + fileID + ".xml"
$.ajax({
type: "GET",
url: dataID,
dataType: "xml",
success: parseXml
});
function parseXml(xml) {
$(xml).find("train").each(function() {
$("ul#ajax-output").append('<li>' + $(this).find("time").text() + '</li>');
});
}
}
});
Its just not working at all. I have been passing the variable using GET in the url. So the link in the HTML goes to /?lineID=SBD_to_Union and it should load the XML file called SBD_to_Union.xml
Making sense to anyone? I'd appreciate some help.
What you seem to be struggling with is obtaining the line from the url in the anchor. Use $(this) to get the href attribute of the clicked link. You could then use a regex, if the url is as described, to remove all but the line id to use in constructing the link for the XML. I presume that the XML is server side and relative to the current url. If not, then you'll need to adjust the path. I've taken the liberty to compress things a bit by putting the functions inline. Edit: and the click handler should return false to prevent the link from actually performing its default action.
$(function() {
$("a.load_ajax").click( function() {
var fileID = $(this).attr('href').replace(/.*?lineID=/,'');
var dataID = "xml/" + fileID + ".xml"
$.ajax({
type: "GET",
url: dataID,
dataType: "xml",
success: function(xml) {
$(xml).find("train").each(function() {
$("ul#ajax-output").append('<li>' + $(this).find("time").text() + '</li>');
});
}
});
return false;
});
});
Have you checked if the get function returns the correct data ?
add an alert(fileID); right after the get(..); line..
But why don't you create the urls to point directly to the xml files instead of parsing and creating urls on the fly ?
just make the link in the html to point to xml/SBD_to_Union.xml
On first glance, I think your ajax() syntax is a little off.
Are you using query strings for a particular reason? If no, I'd try giving the HTML links the absolute URL to the XML file you are trying to fetch:
Then try this:
$("a.load_ajax").click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
type: 'GET',
url: url,
dataType: 'xml',
success: function(response) {
$(response).find('train').each(function() {
$('ul#ajax-output').append('<li>' + $(this).find('time').text() + '</li>');
}
});
});
I haven't tested this, but it should do what you want.
Link1
Link2
You can do things depending on the id of the href (or another of its attributes or its href value).
$(function() {
$("a.load_ajax").click(loadAjax);
});
function loadAjax()
{
if ($(this).attr("id") == "link1")
{
alert("link1"); //load xml1
}
else
{
alert("link2"); //load xml2
};
}