Ajax call after 10 second automatic inside a loop - ajax

jQuery:
// Load message
(function loadAdmin() {
$.ajax({
type: 'POST',
data: 'c_id=' + $(this).data('c_id') + '&offset=' + $(this).data('offset'), //'foo='+ bar+'&calibri='+ nolibri,
dataType: 'json',
url: $("#webroot").text() + 'chats/loadMsg',
success: function (data) {
var id = 0;
$.each(data, function (i, item) {
if (item.Chat.status == 'active') {
$('.temp_msg').remove();
}
if (!$('#' + item.Chat.id)[0]) {
if (item.Chat.admin_message) {
$('<div class="msg_a" id="' + item.Chat.id + '">' + item.Chat.admin_message + '</div>').insertBefore('.' + $(this).data('c_id') + ' .msg_push');
}
if (item.Chat.client_message) {
$('<div class="msg_b" id="' + item.Chat.id + '">' + item.Chat.client_message + '</div>').insertBefore('.' + $(this).data('c_id') + ' .msg_push');
}
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}
id = item.Chat.id;
});
$('.' + c_id + ' .msg_head').data('offset', id)
},
complete: function () {
// Schedule the next request when the current one's complete
setTimeout(loadAdmin, 10000);
}
});
})();
// END load message
I set c_id statically.This works fine. But I want to do this same action for all activated class.
This is something like this:
$('.activated').each(function () {
// do ajax call
loadAdmin();
});
Here crucial situation is for first iteration there start a recursion of loadAdmin(); function calling, then again start first iteration and never step up to second iteration. How can I meet my situation. Thanks

you can use setInterval() function for complete your requirements.
Like this :
$('.activated').each(function () {
// do ajax call
setInterval(loadAdmin(), 10000); // This will call this function in every 10 sec
});
Try this. I hope you will found it.

Related

AJAX dropdown list down not update with var string variable

I have a test script to update a county drop down list whenever the year or state is updated. When I used a literal string when year is selected, the county list updated fine. However when I tried to the county list using an ajax call and used a (var options) to build the list, the drop down list value changed to an empty list even though I verified the value of (var options) contains valid drop down list options.
Please help!
Thanks,
$('#State').on("change", function () {
var state = $('#State').val();
var year = $('#Year').val();
var obj = {
state: state,
year:year
};
alert("State changed:" + state + ":" + year);
AjaxCall('/RIC/GetCounties', JSON.stringify(obj), 'POST').done
(function (response) {
if (response) {
$('#DataId').html("<option value='test'>Test</option>");
var options = '';
options += "<option value='Select'>Select</option>\n";
for (i in response) {
options += "<option value='" + response[i].DataId + "'>" + response[i].County + "</option>\n";
}
$('#DataId').html("<option value='Select'>Select-S</option><option value='16'>Alameda-S</option>");
alert("Statitical Areas(S): " + options);
//$('#DataId').html(options); //This should work. How to get the value of options into the string
//$('#DataId').append(options);
}
}).fail(function (error) {
alert("County Error:" + error.StatusText);
});
});
$('#Year').on("change", function () {
var state = $('#State').val();
var year = $('#Year').val();
var obj = {
state: state,
year: year
};
alert("Year changed:" + state +":"+ year);
AjaxCall('/RIC/GetCounties', JSON.stringify(obj), 'POST').done
(function (response) {
if (response) {
$('#DataId').html("<option value='test'>Test</option>");
var options = '';
options += "<option value='Select'>Select</option>\n";
for (i in response) {
options += "<option value='" + response[i].DataId + "'>" + response[i].County + "</option>\n";
}
//$('#DataId').html("<option value='Select'>Select-Y</option><option value='16'>Alameda-Y</option>");
$('#DataId').html(options); //This should work. How to get the value of options into the string
alert("Statitical Areas(Y): " + options);
//$('#DataId').append(options);
}
}).fail(function (error) {
alert("County Error:" + error.StatusText);
});
});
});
function AjaxCall(url, data, type) {
  return  $.ajax({
     url:  url,
     type:  type  ?  type  :  'GET',
     data:  data,
     contentType:  'application/json'
   });
}  
Instead of using another function to call your $.ajax why not call it immediately. There’s no performance improvement on what you had done. Try to revert your code and just add async property if you want to wait the response before proceeding to your lower conditions.
I hope this will help you

Trying to access Instagram API using jQuery

I'm trying to use the Instagram API and I'm making AJAX requests in a do-while loop until the next_url is null. All I want this code to do is to fetch all the followers by making continuous requests until it's done. What is wrong in this code?
When I remove the do-while loop it doesn't gives me an error, but as soon as a I use the AJAX request within a loop, it never stops. Clearly the $next_url string is not changing to the newly fetched next_url - why? What is wrong?
$(document).ready(function(e) {
$('#fetch_followers').click(function(e) {
var $next_url = 'https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100';
var $access_token = '{access-token}';
var $is_busy = false;
var $count = 0;
do {
while($is_busy) {}
$.ajax({
method: "GET",
url: $next_url,
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$is_busy = true;
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
$next_url = data.pagination.next_url;
},
error: function(jqXHR, textStatus, errorThrown) {
$is_busy = true;
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
},
complete: function() {
++$count;
$is_busy = false;
}
});
} while($next_url !== '' || $count <= 50);
});
});
After I failed in my logic, I added the $count variable that can break the do-while loop, because the do-while loop was running infinitely. After adding it, it still runs infinitely, and I have no idea why.
Have the function call itself in the ajax success callback with the new url as a parameter:
$(document).ready(function() {
$('#fetch_followers').click(function() {
var $access_token = '{access-token}';
pollInstagram('https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100');
});
});
function pollInstagram(next_url, count) {
$.ajax({
method: "GET",
url: next_url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
// If the next url is not null or blank:
if( data.pagination.next_url && count <=50 ) {
pollInstagram(data.pagination.next_url, ++count);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
}
});
}​

Kill an ajax process

GET_DATA()
GET_DATA() contains this:
var xhr;
...
function get_data( phrase ) {
xhr = function get_data( phrase ) {
$.ajax({
type: 'POST',
url: 'http://intranet/webservice.asmx/GetData',
data: '{phrase: "' + phrase + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function( results ) {
$("#div1").empty();
if( results.d[0] ) {
$.each( results.d, function( index, data ) {
$("#div1").append( data.Group + ':' + data.Count + '<br />' );
});
} else {
alert( "results.d does not exist..." );
}
},
error: function(xhr, status, error) {
$('#spanLoading').empty();
var err = eval("(" + xhr.responseText + ")");
alert(err.Message) ;
}
});
}
function get_default() {
$('#div1').empty().append("default stuff goes here");
}
UPDATE 2 CODE
I've also tried this, which doesn't work either, no error messages, just returns the results of when the textbox had 2 characters when it finishes processing even if I delete everything before the process has finished:
$('#TextBox1').keyup( function() {
if(xhr && xhr.readystate != 4){
xhr.abort();
}
if ($("#TextBox1").val().length >= 2) {
get_data( $("#TextBox1").val() );
} else {
get_default();
}
});
UPDATE 1 CODE:
$('#TextBox1').keyup( function() {
if ($("#TextBox1").val().length >= 2) {
get_data( $("#TextBox1").val() );
} else {
if(xhr)
{
xhr.abort();
}
get_default();
}
});
ORIGINAL QUESTION:
I have the following code:
$('#TextBox1').keyup( function() {
if ($("#TextBox1").val().length >= 2) {
get_data( $("#TextBox1").val() );
} else {
get_default();
}
});
This has a slight glitch where if I type something really fast and then I delete it equaly fast, I see the data from get_default() flash on the screen, then it gets replaced by a previous ajax request where the value in the textbox was 2 which had not finished processing.
So basically, what I think is happening is that when the textbox has 2 characters in it, the ajax request starts which takes a second or 2. While this is happening, if I delete the 2 characters, I see the get_default() being successful, but it seems to replace it with the ajax data when the ajax data finishes.
How do I stop this from happening?
Thank you for posting get_data.
The reason why your AJAX call is not getting aborted is that xhr is not defined in the appropriate (window) scope; therefor, xhr.abort() doesn't do anything (and quite probably throws an error if you take a look at your console).
Please try the following:
var xhr = false;
function get_data( phrase ) {
xhr = $.ajax({ /* ... etc */
}
The rest should work as is.
Place a time delay before you execute your ajax request.
function pausecomp(ms) {
ms += new Date().getTime();
while (new Date() < ms){}
}

AJAX Jquery: execution order of events

I have a webpage with different elements (a list of links and two select boxes) connected between them. Clicking on them may affect one of the other element and all of their values contribuite to update a value to show on the page.
So, the code is this:
$(document).ready(function() {
var someVar = '';
$("select#size").bind('change', function() {
someVar = $(this).val();
console.log('first');
});
my_change();
console.log('second' + someVar);
});
function my_change() {
$.getJSON("photos/change_product", {json_stuff}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("select#size").trigger('change');
$("select#options").html(options.join('')).trigger('change');
})
};
};
When I load the page the my_change function is called. It does some stuff and then triggers a change event on a select-box. I need to update a value using what's inside this select box and only then let the execution to proceed. So what I need this code to do would be to print 'first', and then 'second' with the value of the variable. What actually happen is that it prints 'second' 'first'.
I think it's because I'm doing asynchronous calls. What can I do?
There's several ways to do this.
You could use jQuery $.when and call the console.log after the ajax response finishes.
$(document).ready(function() {
var someVar = '';
$("select#size").bind('change', function() {
someVar = $(this).val();
console.log('first');
});
$.when( my_change() ).then(function(){
console.log('second' + someVar);
});
});
function my_change() {
return $.getJSON("photos/change_product", {json_stuff}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("select#size").trigger('change');
$("select#options").html(options.join('')).trigger('change');
})
};
};
Or you could add a callback argument to the my_change(callback) function.
$(document).ready(function() {
var someVar = '';
$("select#size").bind('change', function() {
someVar = $(this).val();
console.log('first');
});
my_change(function(){ console.log('second' + someVar) } );
});
function my_change(callback) {
return $.getJSON("photos/change_product", {json_stuff}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("select#size").trigger('change');
if( typeof callback !== 'undefined' && typeof callback === 'function' )
callback();
$("select#options").html(options.join('')).trigger('change');
})
};
};
The 'second' console.log() is being called first since the asynchronous $.getJSON() call waits for the response from the server before firing its callback function. You could save the jqXHR object to a variable and then use that to run your 'second' consone.log() with $.when():
$(function() {
var someVar = '';
$("#size").on('change', function() {//on() is the same as bind() here
someVar = $(this).val();
console.log('first');
});
//save the jQuery XHR object from your $.getJSON request
var jqXHR = my_change();
//when the above jQuery XHR object resolves, it will fire the second console.log
$.when(jqXHR).then(function () {
console.log('second' + someVar);
});
});
function my_change() {
//here we return the jQuery XHR object for the $.getJSON request so we can run code once it resolves
return $.getJSON("photos/change_product", {json_stuff}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("#size").trigger('change');
$("#options").html(options.join('')).trigger('change');
})
};
Here is documentation for $.when(): http://api.jquery.com/jquery.when
A quick side-note: it is generally slower to add a tag-type to a selector, especially when you are selecting IDs as that is already a very fast method of selecting elements.
Any code that relies on the response of the getJSON must be placed in, or called from, the getJSON callback.
That's what a callback is for.
You should note that your my_change function will not have access to the someVar variable because it is local to the ready() callback.
To remedy this, move the my_change function inside the ready() callback.
Or just pass a function directly to my_change.
my_change(function() {
console.log('second' + someVar);
});
And have the getJSON callback invoke the function.
function my_change( func ) {
$.getJSON("photos/change_product", {json_stuff}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("select#size").trigger('change');
$("select#options").html(options.join('')).trigger('change');
func();
});
}

.setPostData jqgrid not working

I want to reload jqgrid with new parameters.I'm using .setPostData().Please look at my code below.It always give me error at .setPostData().M I missing something? format?
$('table[id$="'+tabID+'_BBGrid"]').jqGrid({
url:'/Controls/Advertiser/BBControlNew.ascx.ashx?action=getBBData&advertiserID=' + $('#advertiser_id').text() + '&startDate=' + $('input[id$="' + tabID +
'_FromCalBuyBack_CalendarTbx"] ').val() + '&endDate=' + $('input[id$="' + tabID + '_ToCalBuyBack_CalendarTbx"] ').val(),
datatype: 'json',
mtype: 'POST',
height:'100%',
width:'100%',
colNames: result.colNamesData,
colModel: result.colModelData,
//pager: '#RequestLeadspager',
rowNum : 100,
shrinkToFit :false,
...........
function BuyBackGridReload(tabID,NoSelectedValues)
{
$('table[id$="'+tabID+'_BuyBackGrid"]').setPostData({
advertiserID:$('#advertiser_id').text(),
CampaignsDdlSelectedValue: $('select[id$="CampaignDdl"] option:selected').val(),
startDate: $('input[id$="'+tabID+'_FromCalBuyBack_CalendarTbx"] ').val(),
endDate: $('input[id$="'+tabID+'_ToCalBuyBack_CalendarTbx"] ').val(),
NoSelectedValue: NoSelectedValues
}).trigger("reloadGrid");
};
I have search btn.I'm getting values for NoSelectedValues inside that search btn. here is the code for button click.
$('input[id$="'+tabID+'_BuyBackSearchBtn"]').click(function(){
var values = [];
$('div[id$="' + tabID + '_SelectedBuyBackFilterDiv"] .children').each(function (){
$(this).find('option').each(function (){
var attr = $(this).attr('rel');
if (typeof attr == 'undefined' ){
values.push($(this).val());
}
});
});
BuyBackGridReload(tabID,values);
}); //End search click
ERROR:
$("table[id$=\"" + tabID +
"_BuyBackGrid\"]").setPostData({advertiserID:
$("#advertiser_id").text(),
CampaignsDdlSelectedValue:
$("select[id$=\"CampaignDdl\"]
option:selected").val(), startDate:
$("input[id$=\"" + tabID +
"_FromCalBuyBack_CalendarTbx\"]
").val(), endDate: $("input[id$=\"" +
tabID + "_ToCalBuyBack_CalendarTbx\"]
").val(), NoSelectedValue:
NoSelectedValues}) is undefined
I also don't want to pass as a querystring for new parameters.
Any suggestion?
Thanks
A
You don't need to use setPostData to set the postData parameter. You can use setGridParam function instead. See here examples.
I suppose if you will use postData parameter which contain functions you will not need to set any postData parameter at all. The url and postData parameters of jqGrid can look like
url:'/Controls/Advertiser/BBControlNew.ascx.ashx",
postData: {
action: "getBBData"
advertiserID: function() { return $('#advertiser_id').text(); },
startDate: function() { return $('input[id$="' + tabID + '_FromCalBuyBack_CalendarTbx"] ').val(); },
endDate: function() { return $('input[id$="' + tabID + '_ToCalBuyBack_CalendarTbx"] ').val(); },
advertiserID: function() { return $('#advertiser_id').text(); },
CampaignsDdlSelectedValue: function() { return $('select[id$="CampaignDdl"] option:selected').val(); },
startDate: function() { return $('input[id$="'+tabID+'_FromCalBuyBack_CalendarTbx"] ').val(); },
endDate: function() { return $('input[id$="'+tabID+'_ToCalBuyBack_CalendarTbx"] ').val(); },
NoSelectedValue: function() { return NoSelectedValues; }
}
The variables tabID and NoSelectedValues must be defined before. On every grid reloading the function from every postData property will be called and you can read the current values from the corresponding controls.

Resources