Ajax Request on another's success ( jQuery ) - javascript

I want to run the another ajax request on one's success.
THE CODE
$(document).ready(function(){
$('*[data-load-template]').each( function () {
var template = $(this).data('load-template');
var element = $(this);
$.ajax({
url : "templates/" + template + '.tpl',
method : "GET",
success : function (htmlData) {
$.ajax({
url : "data/" + template + '.json',
method : "GET",
success : function (jsonData) {
console.log(jsonData); // why isn't this one working???
}
});
element.html(htmlData); // this is working
}
});
});
}); // dom ready event
My question is why isn't this code working and how to make it work.

Related

Need to be able to run an ajax call with element loaded after document.ready()

I've got checkbox inputs on a page and am filtering the results using ajax.
One search option is type and the vendors option updates depending on the type selected. But this means that the change function used to update the actual results no longer works within the document.ready(). To rectify this, I also call the function within .ajaxComplete().
But as an ajax call is being called within the ajaxComplete(), it is causing an infinite loop and crashing the site.
$(document).ready(function(){
$('input[type=radio]').change(function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});
$('#vendor-filter input[type=checkbox]').change(function(){
filterResults(this);
});
});
$(document).ajaxComplete(function(){
$('#vendor-filter input[type=checkbox]').click(function(){
filterResults(this);
});
});
function filterResults($this)
{
var type = $('input[type=radio]:checked').attr("data-id");
var vendor = $($this).attr('data-id');
if($($this).prop('checked'))
{
var action = 'add';
vendors.push(vendor);
}
else
{
var action = 'remove';
var index = vendors.indexOf(vendor);
if(index >= 0)
{
vendors.splice(index, 1);
}
}
$.ajax({
method: 'POST',
url: 'assets/ajax/filter-results.php',
data: {'vendor' : vendor, 'action' : action, 'vendors' : vendors, 'filter_type' : type},
success: function(data)
{
$('#results').empty();
if(action == 'add')
{
window.history.pushState("", "Title", window.location.href+"&v[]="+vendor);
}
else if(action == 'remove')
{
var newUrl = window.location.href.replace("&v[]="+vendor, "");
window.history.replaceState("", "Title", newUrl);
}
$('#results').html(data);
}
});
}
How do I get the .change function to still work after the input checkbox has been called via ajax previously and without causing a loop with .ajaxComplete() ?
Any help would be greatly appreciated.
Thanks
Please try by change function as follow :
$(document.body).on("change",'input[type=radio]',function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});

How to show a progress loader when ajax request sent?

I have a ajax function to got data, when response will get meanwhile show a bootstrap progress loader(circle loader).
How to do this ?
Ajax Function JS:
$('#category_modal').click(function(event) {
var url = $(this).data('url');
var cid = $(this).data('id');
$.ajax({
url: '<?=$this->config->base_url()?>admin_panel/update_popup',
type: 'post',
data: 'id=' + cid
}).done(function(data) {
jQuery('#categoryModal .modal-content').html(data);
$('#categoryModal').modal({
"backdrop" : "static"
});
});
});
https://fortawesome.github.io/Font-Awesome/examples/
animated icon can do the job. Also with css :
http://cssload.net/
add function
beforeSend: function () {
// show loader
}
in your ajax call
You can progress-bar class by jquery.
$('#category_modal').click(function(event) {
/*here append your class to some element
$(element).addClass("progress-bar");
*/
var url = $(this).data('url');
var cid = $(this).data('id');
$.ajax({
url: '<?=$this->config->base_url()?>admin_panel/update_popup',
type: 'post',
data: 'id=' + cid
}).done(function(data) {
/* when u r done remove
$(element).removeClass("progress-bar");
/*
});
});

How call variable outside function .each with Jquery?

I want to be able to access the value of a nested each() function outside of the function.
I have code below or http://jsfiddle.net/z36UK/6/
HTML:
<div id="wrap">
<ul data-role="listview" data-filter="true" data-filter-placeholder="Search..." id="ds-canho">
</ul>
</div>
Javascript:
$(document).ready(function() {
var urlx=[];
parseXml();
alert(urlx);
console.log(urlx);
$.mobile.loading( "show" );
$.ajax({
type: "GET",
url: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%27http://saigonpearl.info/home/notype/-0-trang-chu.html%27%20and%20xpath%3D%22%2F%2Fdiv%5B%40class%3D%27tindang%27%5D%22&diagnostics=true',
dataType: "xml",
success: parseXml
});
function parseXml(xml) {
$(xml).find("div.tindang").each(function() {
var url = $(this).find('a').attr("href"),
urlx= url.replace('#menutop','');
$("ul#ds-canho").append('<li>' + $(this).find('h3').text() + '</li>');
$('ul#ds-canho').listview('refresh');
$.mobile.loading( "hide" );
});
}
});
Please update below js code
$(document).ready(function() {
$.mobile.loading( "show" );
$.ajax({
type: "GET",
url: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%27http://saigonpearl.info/home/notype/-0-trang-chu.html%27%20and%20xpath%3D%22%2F%2Fdiv%5B%40class%3D%27tindang%27%5D%22&diagnostics=true',
dataType: "xml",
success: parseXml
});
$( document ).ajaxComplete(function() {
parseXml();
});
function parseXml(xml) {
window.urlx = '';
$(xml).find("div.tindang").each(function() {
var url = $(this).find('a').attr("href"),
urlx = url.replace('#menutop','');
$("ul#ds-canho").append('<li>' + $(this).find('h3').text() + '</li>');
$('ul#ds-canho').listview('refresh');
$.mobile.loading( "hide" );
});
}
});
EDIT
Add FSFIDDLE
It's not about the each, is it? You can easily put the urlx variable there and assign to it from the inside:
function parseXml(xml) {
var urlx;
$(xml).find("div.tindang").each(function() {
var url = $(this).find('a').attr("href"),
urlx = url.replace('#menutop','');
$("ul#ds-canho").append('<li>' + $(this).find('h3').text() + '</li>');
$('ul#ds-canho').listview('refresh');
$.mobile.loading( "hide" );
});
console.log(urlx);
// if you wanted an array, use `urlx = [];` and `urlx.push(…);`
}
However, where you currently have placed the log and alert statements is
before the ajax request
outside of the ajax request callback
which means that it cannot work. You need to put them inside the callback, because you cannot return the data outside of it.

jquery iframe load dynamically

I am using following jquery script to load another url after successful ajax request.
$(document).ready(function() {
var $loaded = $("#siteloader").data('loaded');
if($loaded == false){
$("#siteloader").load(function (){
if(ad_id != undefined){
var req_url = base_url+'ajax/saveclick/'+ad_id+'/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function() {
$(preloader).show();
$('#adloading').remove();
},
complete: function() {
$(preloader).hide();
},
success: function(result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url+'userpanel/cpa/'+ad_id+'/');
}
});
}
else{
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
});
}
});
<iframe src="remote_url" id="siteloader"></iframe>
I don't want to run ajax again after changing src on iframe and i have also tried to stop it by $("#siteloader").data("loaded", "true");
Please suggest me a good solution for this. thanks.
If you only want to execute the "load" handler once
Simply add the line
$("#siteloader").unbind('load');
In the success callback.
If you want the "load" handler to be executed on each src change, you may do something like that :
$(document).ready(function () {
$("#siteloader").load(function () {
// Move the test in the event Handler ...
var $loaded = $("#siteloader").data('loaded');
if ($loaded == false) {
if (ad_id != undefined) {
var req_url = base_url + 'ajax/saveclick/' + ad_id + '/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function () {
$(preloader).show();
$('#adloading').remove();
},
complete: function () {
$(preloader).hide();
},
success: function (result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url + 'userpanel/cpa/' + ad_id + '/');
}
});
}
else {
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
}
});
});
Maybe your ad_id variable is not well defined / changed ...

How to unbind or turn off all jquery function?

I have constructed an app with push state. Everything is working fine. However in some instances my jquery function are fireing multiple times. That is because when I call push state I bind the particular js file for each page I call. Which means that the same js functions are binded many times to the html while I surf in my page.
Tip: I am using documen.on in my jquery funciton because I need my function to get bound to the dynamical printed HTML through Ajax.
I tried to use off in the push state before printing with no success!
Here is my code:
var requests = [];
function replacePage(url) {
var loading = '<div class="push-load"></div>'
$('.content').fadeOut(200);
$('.container').append(loading);
$.each( requests, function( i, v ){
v.abort();
});
requests.push( $.ajax({
type: "GET",
url: url,
dataType: "html",
success: function(data){
var dom = $(data);
//var title = dom.filter('title').text();
var html = dom.find('.content').html();
//alert(html);
//alert("OK");
//$('title').text(title);
$('a').off();
$('.push-load').remove();
$('.content').html(html).fadeIn(200);
//console.log(data);
$('.page-loader').hide();
$('.load-a').fadeIn(300);
}
})
);
}
$(window).bind('popstate', function(){
replacePage(location.pathname);
});
Thanks in advance!
simple bind new function with blank code
$( "#id" ).bind( "click", function() {
//blank
});
or
used
$('#id').unbind();
Try this,
var requests = [];
function replacePage(url) {
var obj = $(this);
obj.unbind("click", replacePage); //unbind to prevent ajax multiple request
var loading = '<div class="push-load"></div>';
$('.content').fadeOut(200);
$('.container').append(loading);
$.each(requests, function (i, v) {
v.abort();
});
requests.push(
$.ajax({
type: "GET",
url: url,
dataType: "html",
success: function (data) {
var dom = $(data);
//var title = dom.filter('title').text();
var html = dom.find('.content').html();
//alert(html);
//alert("OK");
//$('title').text(title);
obj.bind("click", replacePage); // binding after successfulurl ajax request
$('.push-load').remove();
$('.content').html(html).fadeIn(200);
//console.log(data);
$('.page-loader').hide();
$('.load-a').fadeIn(300);
}
}));
}
Hope this helps,Thank you

Categories

Resources