Do while javascript issue - javascript

I'm trying to send multiple post within a do while loop but the result is not added
<script type="text/javascript">
function action() {
var initval = 1;
var endval = 5;
do {
var action_string = 'txtuser=someone';
$.ajax({
type: "POST",
url: "http://localhost/js.php",
data: action_string,
success: function(result){
$('div#append_result').append(initval + ',<br/>');
}
});
initval++;
} while (initval <= endval);
}
</script>
The Output is:
5,
5,
5,
5,
5,
and I need the output to be:
1,
2,
3,
4,
5,

Due to the async nature of AJAX, by the time your success function runs for any of the resulting AJAX requests, the loop has completed and initval is set to 5. You need to capture the state of initval at the start of each request and use that captured state in the success() method. Closing over the value is the simplest way to do it:
function action() {
var initval = 1;
var endval = 5;
do {
var action_string = 'txtuser=someone';
( function( captured_initval ){
$.ajax({
type: "POST",
url: "http://localhost/js.php",
data: action_string,
success: function(result){
$('div#append_result').append(captured_initval + ',<br/>');
}
});
}( initval ) );
initval++;
} while (initval <= endval);
}
Understand, though, that one or more requests could get hung up at the server allowing a latter request to complete first, which could result in 1, 2, 5, 3, 4 or something like that.
Also, using an element's ID is much faster than prefixing the hash selector with the elements tag name. Plus you should avoid re-querying the DOM for your result DIV every time the success runs. Grab it once and use it when needed:
function action() {
var initval = 1;
var endval = 5;
do {
var action_string = 'txtuser=someone',
$AppendResult = $('#append_result');
( function( captured_initval ){
$.ajax({
type: "POST",
url: "http://localhost/js.php",
data: action_string,
success: function(result){
$AppendResult.append(captured_initval + ',<br/>');
}
});
}( initval ) );
initval++;
} while (initval <= endval);
}

The Ajax request is asynchronous, which means by the time the success handler returns, the loop is already completed. Instead, you can create a closure to preserve the value:
success: (function(i){
return function() {
$('div#append_result').append(i + ',<br/>');
}
})(initval)

This is because of the async behavior of ajax:
Here is a modified version:
var initval = 1;
var endval = 5;
function action(){
var action_string = 'txtuser=someone';
$.ajax({
type: "POST",
url: "http://localhost/js.php",
data: action_string,
success: function(result){
$('div#append_result').append(initval + ',<br/>');
initval++;
if(initval<=endval)
action();
}
});
}
This is now somewhat a sequential approach.
Note: I assumed every ajax request returns success, if there is an error, you should handle them on the error callback.

Related

Ajax calls inside loop need sequential responses

I need to make 3 or less ajax calls, and the responses need to be appended to the dom in the same order they were requested.
I have the following function, but the problem is that the responses that I get are not necessarily in the correct order when they get appended to the dom.
I wouldn't want to use the async: false property because it blocks the UI and it's a performance hit of course.
mod.getArticles = function( ){
//mod.vars.ajaxCount could start at 0-2
for( var i = mod.vars.ajaxCount; i < 3; i++ ){
//mod.vars.pushIds is an array with the ids to be ajaxed in
var id = mod.vars.pushIds[i];
$.ajax({
url: '/ajax/article/' + id + '/',
type: "GET",
dataType: 'HTML',
error: function() {
console.error('get article ajax error');
}
}).done( function( data ) {
if (data.length) {
mod.appendArticle( data );
} else {
console.error('get article ajax output error');
}
});
}
};
You need to append the article to a certain position, based on for example the i variable you have. Or you could wait for all of the requests and then append them in order. Something like this:
mod.getArticles = function( ){
var load = function( id ) {
return $.ajax({
url: '/ajax/article/' + id + '/',
type: "GET",
dataType: 'HTML',
error: function() {
console.error('get article ajax error');
});
};
var onDone = function( data ) {
if (data.length) {
mod.appendArticle( data );
} else {
console.error('get article ajax output error');
}
};
var requests = [];
for( var i = mod.vars.ajaxCount; i < 3; i++ ){
requests.push(load(mod.vars.pushIds[i]));
}
$.when.apply(this, requests).done(function() {
var results = requests.length > 1 ? arguments : [arguments];
for( var i = 0; i < results.length; i++ ){
onDone(results[i][0]);
}
});
};
Here is an example using i to append them in the proper order when they all finish loading:
mod.getArticles = function( ){
// initialize an empty array of proper size
var articles = Array(3 - mod.vars.ajaxCount);
var completed = 0;
//mod.vars.ajaxCount could start at 0-2
for( var i = mod.vars.ajaxCount; i < 3; i++ ){
// prevent i from being 3 inside of done callback
(function (i){
//mod.vars.pushIds is an array with the ids to be ajaxed in
var id = mod.vars.pushIds[i];
$.ajax({
url: '/ajax/article/' + id + '/',
type: "GET",
dataType: 'HTML',
error: function() {
console.error('get article ajax error');
}
}).done( function( data ) {
completed++;
if (data.length) {
// store to array in proper index
articles[i - mod.vars.ajaxCount] = data;
} else {
console.error('get article ajax output error');
}
// if all are completed, push in proper order
if (completed == 3 - mod.vars.ajaxCount) {
// iterate through articles
for (var j = mod.vars.ajaxCount; j < 3; j++) {
// check if article loaded properly
if (articles[j - mod.vars.ajaxCount]) {
mod.appendArticle(articles[j - mod.vars.ajaxCount]);
}
}
}
});
}(i));
}
};
var success1 = $.ajax...
var success2 = $.ajax...
var success3 = $.ajax...
$.when(success1, success2, success3).apply(ans1, ans2, ans3) {
finalDOM = ans1[0]+ans2[0]+ans3[0];
}
Check this for more reference. This is still async, but it waits for all of them to complete. You know the order of invocation already, as its done through your code, so add the dom elements accordingly.
Solutions that rely solely on closures will work up to a point. They will consistently append the articles of a single mod.getArticles() call in the correct order. But consider a second call before the first is fully satisfied. Due to asynchronism of the process, the second call's set of articles could conceivably be appended before the first.
A better solution would guarantee that even a rapid fire sequence of mod.getArticles() calls would :
append each call's articles in the right order
append all sets of articles in the right order
One approach to this is, for each article :
synchronously append a container (a div) to the DOM and keep a reference to it
asynchronously populate the container with content when it arrives.
To achieve this, you will need to modify mod.appendArticle() to accept a second parameter - a reference to a container element.
mod.appendArticle = function(data, $container) {
...
};
For convenience, you may also choose to create a new method, mod.appendArticleContainer(), which creates a div, appends it to the DOM and returns a reference to it.
mod.appendArticleContainer = function() {
//put a container somewhere in the DOM, and return a reference to it.
return $("<div/>").appendTo("wherever");
};
Now, mod.getArticles() is still very simple :
mod.getArticles = function() {
//Here, .slice() returns a new array containing the required portion of `mod.vars.pushIds`.
//This allows `$.map()` to be used instead of a more cumbersome `for` loop.
var promises = $.map(mod.vars.pushIds.slice(mod.vars.ajaxCount, 3), function(id) {
var $container = mod.appendArticleContainer();//<<< synchronous creation of a container
return $.ajax({
url: '/ajax/article/' + id + '/',
type: "GET",
dataType: 'HTML'
}).then(function(data) {
if (data.length) {
mod.appendArticle(data, $container);//<<< asynchronous insertion of content
} else {
return $.Deferred().reject(new Error("get article ajax output error"));
}
}).then(null, function(e) {
$container.remove();//container will never be filled, so can be removed.
console.error(e);
return $.when(); // mark promise as "handled"
});
});
return $.when.apply(null, promises);
};
mod.getArticles() now returns a promise of completion to its caller, allowing further chaining if necessary.
Try utilizing items within mod.vars array as indexes; to set as id property of $.ajaxSettings , set returned data at this.id index within an array of responses. results array should be in same order as mod.vars values when all requests completed.
var mod = {
"vars": [0, 1, 2]
};
mod.getArticles = function () {
var results = [];
var ids = this.vars;
var request = function request(id) {
return $.ajax({
type: "GET",
url: "/ajax/article/" + id + "/",
// set `id` at `$.ajaxSettings` ,
// available at returned `jqxhr` object
id: id
})
.then(function (data, textStatus, jqxhr) {
// insert response `data` at `id` index within `results` array
console.log(data); // `data` returned unordered
// set `data` at `id` index within `results
results[this.id] = data;
return results[this.id]
}, function (jqxhr, textStatus, errorThrown) {
console.log("get article ajax error", errorThrown);
return jqxhr
});
};
return $.when.apply(this, $.map(ids, function (id) {
return request(id)
}))
.then(function () {
$.map(arguments, function (value, key) {
if (value.length) {
// append `value`:`data` returned by `$.ajax()`,
// in order set by `mod.vars` items:`id` item at `request`
mod.appendArticle(value);
} else {
console.error("get article ajax output error");
};
})
});
};
mod.getArticles();
jsfiddle http://jsfiddle.net/6j7vempp/2/
Instead of using a for loop. Call your function in response part of previous function.
//create a global variable
var counter = 0;
function yourFunc(){
mod.getArticles = function( ){
//mod.vars.ajaxCount could start at 0-2
//mod.vars.pushIds is an array with the ids to be ajaxed in
var id = mod.vars.pushIds[counter ];
$.ajax({
url: '/ajax/article/' + id + '/',
type: "GET",
dataType: 'HTML',
error: function() {
console.error('get article ajax error');
}
}).done( function( data ) {
if (data.length) {
mod.appendArticle( data );
} else {
console.error('get article ajax output error');
}
//increment & check your loop condition here, so that your responses will be appended in same order
counter++;
if (counter < 3)
{ yourFunc(); }
});
};
}
I'm faced same problem i'm solve this problem using following way.
just use async for get sequence wise response
<script type="text/javascript">
var ajax1 = $.ajax({
async: false,
url: 'url',
type: 'POST',
data: {'Data'},
})
.done(function(response) {
console.log(response);
});

Javascript global variables used as flags

I am trying to use global variables as flags and cant get it to work. I have two functions:
This function sets a flag to be false when it is done.
function buildYearsTable(btn) {
//console.log ("At build years table")
var fundCode = document.getElementById("fundCode").value
buildYearsFlag = true;
$.ajax({url: "/scholarship/scholarshipMaintenance/buildYearsTable", method: "POST",
cache: false, data: {fundCode: fundCode},
complete: function(xhr, statusCode){
console.log("inside build years table")
data = $.parseJSON(xhr.responseText)
$('#myTable tbody').html('');
data = data.sort()
data = data.reverse()
for(var i = data.length - 1; i >= 0; i--) {
moveYearOption(data[i])
addYearRow(data[i])
}
buildYearsFlag = false;
//$('#yearsTable').html(xhr.responseText)
console.log("done in build years table")
}})
}
This function is called when the first one is called, but i need it to perform its ajax call ONLY once the flag is set to false by the first function. I am not sure how to accomplish this. I was thinking a while loop (polling kind of idea) but not sure how to go about it.
function rebuildYearSelects(btn) {
//console.log ("At rebuild selects")
var fundCode = document.getElementById("fundCode").value
while (buildYearsFlag == false) {
$.ajax({url: "/scholarship/scholarshipMaintenance/rebuildYearSelects", method: "POST",
cache: false, data: {fundCode: fundCode},
complete: function(xhr, statusCode){
console.log("got inside rebuild years select")
data = $.parseJSON(xhr.responseText)
selectedYears = data.sortedSelectedYears
unselectedYears = data.sortedUnselectedYears
$('#yearsModal').replaceWith(data.html)
fixModals();
buildYearsFlag = true;
console.log("done in rebuildYearSelects")
}})
}
}
The best way to accomplish this is by using callbacks.
You just need to call the second function after the response from the first.
You should use 'done' instead of 'complete'.
function buildYearsTable(btn) {
var fundCode = document.getElementById("fundCode").value
$.ajax({url: "/scholarship/scholarshipMaintenance/buildYearsTable", method: "POST",
cache: false, data: {fundCode: fundCode},
done: function( data ){
// Your code goes here
// Call the function only after the response
rebuildYearSelects();
}})
}
Html:
onclick="buildYearsTable();"
Remove the flags and the while loop, everything should work.

Javascript with AJAX inside another function

Javascript with AJAX inside another function
http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/dynamic-update/
From this example, instead of placing the first 19 points with random values, I want to pass a value from my server through AJAX.
And I am talking about the code here.
series: [{
name: 'Random data',
data: (function () {
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
And since the key of series is also data I have no idea how I am gonna get data from AJAX GET call.
The AJAX call that I want to use is:
$.ajax({
type: "GET",
url: "/getData",
success: function(data) {
var y1 = data.count;
series.addPoint([x, y1], true, true);
}
});
But I tried to use this but it does not seem to work, like the following:
series: [{
name: 'Random data',
data: (function () {
var data1 = [],
time = (new Date()).getTime(),
i;
$.ajax({
type: "GET",
url: "/getData",
success: function(data) {
var y1 = data.count;
for (i = -19; i <= 0; i += 1) {
data1.push({
x: time + i * 1000,
y: data.count
});
}
}
});
return data1;
}())
}]
Please let me know how to GET for the Highchart data
First off see this reference for why you can't return data from your outer function like you're trying to:
How do I return the response from an asynchronous call?
Then, understanding that you will have to use the data from the success handler, that means that you will have to move the ajax call outside of the data declaration and do it afterwards, but you will have to recognize that the data will NOT be available until sometime later when the ajax call finishes. You cannot use it immediately. If you need to know when the data is available, then put the data into the data structure and call some other function from the success handler.
Like they said the AJAX call is async = not blocking, it means that the browser is making the ajax call in your function and instantly goes on at the next line, in your case return data1 but the data1 var is not updated since the ajax call is still being executed.
Documentation:http://api.jquery.com/deferred.done/
There are also some things I don't understand in your code, did you try to lint hit with JSHint or JSLint?, here is my version with some corrections:
// define var outside of function so they are not scoped
var time = (new Date()).getTime(),
data1,series;
$.ajax({
type: "GET",
url: "/getData",
success: function(data) {
// since you are using i only here just define it in the cycle
for (var i = -19; i <= 0; i += 1) {
data1.push({
x: time + i * 1000,
y: data.count
});
}
}
}).done(function() {
series = {
name: 'Random data',
data: data1
};
});

Javascript scope when using ajax post and functions in general

I'm relatively new to javascript, and I have a restful api I'm connecting to that returns me a json string, which I can parse properly like so:
$.ajax({ url: './php/bandwidth.php',
data: { prop_id : "1" },
type: 'post',
success: function(output) {
var json = $.parseJSON(output);
for( var i = 0 ; i < json.response.length; i++ ){
times.push (json.response[i].time);
}
}
});
Inside of the success callback the variables in the array exist. I also have times array instantiated outside the ajax call function. But outside of the ajax call the array is empty. I'm sure it's a scoping issue. Can anyone give me a way to get the data from inside the array? Does the construct $.ajax({url:... , data:... , success: function(){}}); returns callback return value?
$.ajax({ url: './php/bandwidth.php',
data: { prop_id : "1" },
type: 'post',
dataType: 'json',
success: function(output) {
times = [];
for( var i = 0 ; i < output.response.length; i++ ){
times.push (output.response[i].time);
}
},
complete: function(){
if(times.length > 0){ console.log(times); } else { console.log("times empty"); }
}
});

JQuery won't pass data labeled sessid when calling drupal service module

Hey all I am working on a json call that will implement Drupal's services module with json. I am using jquery's ajax function to call the function but I am getting an error stating that no parameters are being passed. When I look at the query string being posted I notice that sessid is not being passed even though its with the parameters. Below is what Im running.
// JavaScript Document
$(document).ready(function() {
function drupalConnect(src) {
$.ajax({
url: src,
type: 'POST',
data: {
method: 'system.connect'
},
success: function(data) {
return data["result"]["sessid"];
}
});
}
function getTimestamp() {
return Math.round((new Date).getTime() / 1000);
}
function randString(length) {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var randomstring = '';
for (var i = 0; i < length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum, rnum + 1);
}
return randomstring;
}
var session_id = drupalConnect('http://localhost/drupal/services/json-rpc');
var nonce = randString(10);
var timestamp = getTimestamp();
var username = "markusgray";
var password = "Markus1990";
var key = '2ae0392e0aebbfeeddefcc962ea1924f';
var domain = 'localhost';
var hashObj = new jsSHA(timestamp + ";" + domain + ";" + nonce + ";user.login", "TEXT");
var hash = hashObj.getHMAC(key, "TEXT", "SHA-256", "HEX");
var parameters = {
hash: hash,
domain_name: domain,
domain_time_stamp: timestamp,
nonce: nonce,
sessid: session_id,
username: username,
password: password
};
var par = JSON.stringify(parameters);
$.ajax({
url: 'http://localhost/drupal/services/json-rpc',
type: 'POST',
dataType: 'json',
data: {
method: 'user.login',
params: par
},
success: function() {
}
});
});​
drupalConnect doesn't return anything, also the return from the success callback is just thrown away. The best way to use the data returned from an ajax call is to use it in thee callback itself.
function drupalConnect(src){
$.ajax({
url: src,
type: 'POST',
data:{method:'system.connect'},
success: function(data){
var session_id = data["result"]["sessid"];
//use session_id here
}
});
}
It is because of the Asynchronous ajax, let me elaborate, to get the session_id you are making an ajax call. At the moment it will send the request, but it wont ensure that the session_id will be assigned at that moment. Hence when you making the second ajax call, the session_id may not be assigned for a value.
There are two workarounds for this,
One is, making the first ajax call with an option async:false and assign the value within the success call, something like
var session_id;
function drupalConnect(src) {
$.ajax({
url: src,
type: 'post',
async : false,
data: {
method: 'system.connect'
},
success: function(data) {
session_id = data["result"]["sessid"];
}
});
};
DEMO
The second one and preferred way is, use of deferred objects, something like
$.when(
// make your first ajax request
).then(function(data) {
session_id = data["result"]["sessid"];
// make your second ajax call
});​
DEMO

Categories