in a $.each() I do a AJAX-request:
$.each(all, function(i,v) {
$.ajax({
url: "/mycontroller/"+encodeURIComponent(v),
success: function(data){
$('#inner').append(data);
}
});
});
now I would like to show a message if every AJAX-request in the $.each() is complete. But how can I do this, As AJAX is asynchronous?
You can utilize jQuery.when(). This method
provides a way to execute callback functions based on zero or more objects, usually Deferred objects that represent asynchronous events.
var ajaxRequests = all.map(function(x) {
return $.ajax({
url: "/mycontroller/"+encodeURIComponent(x),
success: function(data){
$('#inner').append(data);
}
});
jQuery.when.apply(this, ajaxRequests).then(function() {
// do what you want
});
With simple javascript you can do it in following way:
var counter = 0;
$.each(all, function(i,v) {
$.ajax({
url: "/mycontroller/"+encodeURIComponent(v),
success: function(data){
$('#inner').append(data);
counter++; //increment the counter
},
error: function(){
counter++; //increment the counter
},
complete : function(){
//check whether all requests been processed or not
if(counter == all.length)
{
alert("All request processed");
}
}
});
});
use async :false to make ajax request to be completed before the browser passes to other codes
$.each(all, function(i,v) {
$.ajax({
type: 'POST',
url: "/mycontroller/"+encodeURIComponent(v),
data: row,
success: function(data){
$('#inner').append(data);
}
error: function() {
console.log("Error")
}
}); });
Related
excuse me sir/ma'am
i'm new to ajax, i'm trying to do multiple ajax call in one function to dislay info after an option in dropdown is selected and it goes into separate field ,something like
a goes into description field, b goes into schedule field
i already got the function for a 1 call but when i'm trying to do 2 it's just doesn't work
here is the code that i made for multiple call
<script>
// multiple ajax calls code that i make
// #paket is the dropdown id
$.when(
$('#paket').unbind('change');
$('#paket').change(function(){
var opt_sel = $('#paket').val();
$.ajax({
url:'bttdev3/tour/s1',
method: "POST",
data: {
sel_op:opt_sel
}
}),
$.ajax({
url:'bttdev3/tour/s2',
method: "POST"
data: {
sel_op:opt_sel
}
});
});
);
.then(function(a,b){
$.('#detail').html(a);
$.('#jadwal').html(b);
});
</script>
here is the previous code that works for 1 data call
<script>
1 call function
(function(){
$('#paket').unbind('change');
$('#paket').change(function(){
var opt_sel = $('#paket').val();
var baseurl = "www.dev3.gatra.com/bttdev3";
$.ajax({
method:"POST",
url: '/bttdev3/tour/s1',
// url: "/bttdev3/tour/" + s1,
data:{
sel_op:opt_sel
}
}).done(function(a){
$('#detail').html(a);
}).fail(function(){
alert("gagal memanggil data.");
});
});
});
</script>
any help would be appreciated
try this one
$(document).on('change', '#packet', function(){
_ajax('bttdev3/tour/s1', 'POST', {sel_op: $(this).val()}, function(res){
$('#detail').html(res);
});
_ajax('bttdev3/tour/s2', 'POST', {sel_op: $(this).val()}, function(res){
$('#jadwal').html(res);
});
});
function _ajax(url, method, data, callback){
$.ajax({
method,
url,
data
}).done(function(a){
if(typeof(callback) != 'undefined'){
callback (a);
}
}).fail(function(){
alert("gagal memanggil data.");
});
}
I'm doing an AJAX call within a timer. The AJAX call gives me certain data which I need to make calculations based on the "new" and "old" data. The problem is that the data is overwritten.
function go_timer() {
var x_total = $('.old_value').text();
$.ajax({
type: 'GET',
url: 'http://scrape4me.com/yahoo?url=http://finance.yahoo.com/webservice/v1/symbols/asml.as/quote%3Fformat%3Dxml%26view%3D%E2%80%8C%E2%80%8Bdetail',
dataType: 'xml',
success: xmlParser
});
function xmlParser(xml) {
$('table tr.rows').remove();
$(xml).find('resource').each(function () {
$('table').append('<tr class="rows"><td class="movers"></td></tr>');
});
//end function
}
$('.old_value').text($('table tr td').text());
setTimeout(go_timer, 5000);
}
go_timer();
I would like to do x_total(old) + x_total(new) and then hold on to the outcome of that number.
var x_total = 0;
function go_timer() {
$.ajax({
type: 'GET',
url: 'http://scrape4me.com/yahoo?url=http://finance.yahoo.com/webservice/v1/symbols/asml.as/quote%3Fformat%3Dxml%26view%3D%E2%80%8C%E2%80%8Bdetail',
dataType: 'xml',
success: xmlParser
});
function xmlParser(xml) {
$('table tr.rows').remove();
$(xml).find('resource').each(function () {
$('table').append('<tr class="rows"><td class="movers"></td></tr>');
});
x_total = x_total + parseInt($('table tr td').text());
//end function
}
setTimeout(function(){ go_timer()}, 5000);
//here you can have add logic
}
go_timer();
I know there are many question like this but i didn't found a proper solution for me.
I am calling API using ajax so my problem is my web page gets unresponsive so some where I have found that this is just because of the improper ajax handling can you please help to know where do I put my ajax.I need ajax to be called on the load of the page.
I have tried calling ajax without any function like..
show('ajax Call start for player');
$('#loading').show();
$.ajax({
url: '/home/getPlayers',
success: function (data) {
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
// show(playerData);
showPlayers(1);
show('ajax Call complete for player');
flag = 1;
}
});
show('ajax Call start for loadplayeronpitch');
$.ajax({
url: '/home/checkUserTeam',
success: function (data) {
while (true) {
if (flag) {
loadUserTeampitch(data);
break;
}
}
show('ajax Call complete for loadplayeronpitch');
}
});
This is not working which cause the unresponsive page.
then from other questions I have tried calling the ajax in following functions
$(document).load(function(){
});
$(function(){
});
$(document).bind("load", function () {
});
but this all are also not working properly can you help me for this?
Thank you.
The unresponsiveness is caused by your while(true) loop, so never ever do this again :-)
What you want to do is: Run the second ajax call only after the first one finishes. So you should put both ajax calls into separate functions, then call the first function on page load.
In the success part of the first ajax (inside the first function), call the second function. Done.
function firstAjax() {
$.ajax({
url: '/home/getPlayers',
success: function (data) {
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
//show(playerData);
showPlayers(1);
show('ajax Call complete for player');
secondAjax();
}
});
}
function secondAjax() {
$.ajax({
url: '/home/checkUserTeam',
success: function (data) {
loadUserTeampitch(data);
}
});
}
$(function() {
firstAjax();
});
This should work like you want to, but I can't test it right now.
$('#loading').show();
var deferedA = $.ajax({
url: '/home/getPlayers',
success: function (data) {
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
// show(playerData);
showPlayers(1);
show('ajax Call complete for player');
}
});
show('ajax Call start for loadplayeronpitch');
var deferedB = $.ajax({
url: '/home/checkUserTeam'
});
//wait until both request are finished
$.when(deferedA, deferedB)
.done( function (dataA, dataB) {
loadUserTeampitch(dataB);
show('ajax Call complete for loadplayeronpitch');
});
EDIT I would suggest to use Promise instead $.when (the Promise like implementation of jQuery is a bit strange), but the problem with Promise is that it is only available with the newer browser, for older one you need a library like bluebird or when
EDIT : If you want to go simple than you can use below approach..
<script type="text/javascript">
$(function() {
var flag = 0;
var data1;
$('#loading').show();
$.ajax({
beforeSend: function() {
show('ajax Call start for player');
},
url: '/home/getPlayers',
success: function(data) {
flag++;
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
showPlayers(1);
show('ajax Call complete for player');
checkFlag();
}
});
$.ajax({
beforeSend: function() {
show('ajax Call start for loadplayeronpitch');
},
url: '/home/checkUserTeam',
success: function(data) {
flag++;
data1 = data;
show('ajax Call complete for loadplayeronpitch');
checkFlag();
}
});
function checkFlag()
{
if (parseInt(flag) == parseInt(2))
{
loadUserTeampitch(data1);
}
}
});
</script>
I have a variable in the success part of ajax and I want to reuse it in another function (which executed every 3 seconds), I tried to declare it global, but it does not work; Tdata is not known.
I know that $.ajax is an asynchronous function and I saw some posts similar to mine but it did not help me.
Help me please. Thank you.
This is a part of my code:
<script language='Javascript'>
var Tdata;
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
Tdata=jQuery.parseJSON(data);
////
}
});
window.setInterval(function() {
$(window).load(function() {
$.each(Tdata, function(variable) {
/////////////
});
});
}, 3000);
</script>
Why not wait until the AJAX request has successfully returned data before starting your interval? Since any executions of the interval's function aren't going to do anything (due to no data) before that point waiting isn't going to change the way the page would function in any way.
$.ajax({
method: "GET",
url: "load-data.php",
dataType: "json"
success: function(data) {
var Tdata = data;
// do some more stuff with the response of the AJAX request
var interval = setInterval(function() {
$.each(Tdata, function(variable) {
// do something with variable
});
}, 3000);
}
});
Note that I've removed the binding of the load event to the window every time the interval runs because doing so really doesn't seem to make any sense. I've also added a dataType property with a value of json to the options object passed to $.ajax() so you don't have to parse the response as JSON yourself.
try this,
<script language='Javascript'>
var Tdata;
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
Tdata=jQuery.parseJSON(data);
////
}
});
$(window).load(function() {
window.setInterval(function() {
$.each(Tdata, function(variable) {
/////////////
});
}, 3000);
});
</script>
Function that uses the variable from AJAX call should be called from inside AJAX success, like this:
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
Tdata=jQuery.parseJSON(data);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.each(Tdata, function(variable) {
/////////////
});
}, 3000);
}
is callback tdataAjax function ajax success method run; #param parseJSON
var tdataAjax = function(callback) {
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
var Tdata=jQuery.parseJSON(data);
setInterval(function() {
callback(Tdata);
}, 3000);
}
});
};
is Callback function #param data in tdataAjax function
tdataAjax(function(data) {
$.each(data, function(variable) {
// code
});
});
tdataAjax ++ :)
tdataAjax(function(data) {
$.each(data, function(variable) {
// cla bla
});
});
I have 2 elements on my page that I am trying to reload via ajax - however I can only ever seem to update one. Below is my code,
$('#messages_send').live('click', function() {
$.ajax({
url: base_url + 'ajax/send_message',
data: {
username: $('#messages_username').val(),
message: $('#messages_message').val(),
saveid: $('#messages_savedid').val(),
},
success: function(data) {
sending_message();
var x = jQuery.parseJSON(data);
if(x) {
if(x.gp_id==80)
{
$('#spn_ucredit').load(base_url + 'ajax/userdata/credits');
$('#overlay_credits').load(base_url + 'ajax/userdata/credits');
}
}
//$('#spn_ucredit').html($('#ncd_id').val());
//tmp_cost = $('#spn_ucredit').html()-$('#ncd_id').val();
//$('#ncd_id').val($('#ncd_id').val()-tmp_cost);
//alert(data);
setTimeout(message_sent, 2000);
setTimeout(remove_modal_box, 3000);
setTimeout(message_revert, 3500);
$("#saved_messages").load(base_url + 'messages #saved_messages > form');
$("#messages_content").load(base_url + 'messages #messages_content > form');
}
});
return false;
});
Am I doing something wrong?
sico,
There's a number of things you can do to debug/improve the code, chief amongst which is to reduce the number of HTTP requests. With $.get() instead of .load(), it should be possible to use the HTTP responses twice each.
Something like this :
$(document).on('click', '#messages_send', function() {
sending_message();
$.ajax({
url: base_url + 'ajax/send_message',
data: {
username: $('#messages_username').val(),
message: $('#messages_message').val(),
saveid: $('#messages_savedid').val(),
},
dataType: 'json',
success: function(data) {
var creditsPromise, messagesPromise;//vars that allow .when() later.
if(data.gp_id == 80) {
creditsPromise = $.get(base_url + 'ajax/userdata/credits', function(data) {
$('spn_ucredit').html(data);
$('#overlay_credits').html(data);
});
}
else {
creditsPromise = (new $.Deferred()).resolve().promise();
}
messagesPromise = $.get(base_url + 'messages', function(data) {
var $data = $(data);
$("#saved_messages").empty().append($data.find('#saved_messages > form'));
$("#messages_content").empty().append($data.find('#messages_content > form'));
});
$.when(creditsPromise, messagesPromise).done(function() {//fires when both $.get()s have successfully responded
message_sent();
setTimeout(remove_modal_box, 1000);
setTimeout(message_revert, 1500);
});
}
});
return false;
});
This reduces the number of HTTP requests from five to three.
You could further reduce the number of HTTP requests to one, though you would need to write a server-side script to perform everything currently performed by ...ajax/send_message, ...ajax/userdata/credits and ...messages, and json-encode a composite response.
The client-side code could then simplify to something like this:
$(document).on('click', '#messages_send', function() {
sending_message();
$.ajax({
url: base_url + 'ajax/send_message',
data: $("#messages form").serialize(),//assumed
dataType: 'json',
success: function(data) {
if(data.gp_id == 80) {
$('#spn_ucredit').html(data.credits);
$('#overlay_credits').html(data.credits);
}
$("#saved_messages").html(data.saved_messages);
$("#messages_content").html(data.messages_content);
message_sent();
setTimeout(remove_modal_box, 1000);
setTimeout(message_revert, 1500);
}
});
return false;
});