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.
Related
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 2 years ago.
I have two functions main function which JQuery , and the other one in Javascript.
jQuery :
$(document).ready(function () {
$('#ProvisionLink').click(function () {
var queryTargetList = [ "Item1","Item2","Item3","Item4"]
var data = ["Data1","Data2","Data3","Data4" ]
event.preventDefault();
var i;
for(i = 0; i < queryTargetList.length; ++i) {
var dataItem = data[i];
var QueryItems = queryTargetList[i];
console.log("Before Launching the Javascript : " +QueryItems)
$.ajax({
url: '/operation',
data: {DataType: dataItem,},
type: 'POST',
success: function (response){ getInventory(response,QueryItems) },
error: function (error) {console.log(error);}
});
}
});
});
Java script :
function getInventory(data,queryTarget){
console.log("In Get Inventory Function in javascript ... " +queryTarget)
var queryTarget = "#"+queryTarget
// get the query id
const SelectBoxQuery = document.querySelector(queryTarget)
console.log(SelectBoxQuery)
// resetting the values to enter all the new one.
SelectBoxQuery.options.length = 0; // reset the values
// making a loop to reach each element item in the list
for (var i = 0; i < data.length; ++i) {
// add new element which is option to the targeted ID
var SelectBoxQuery_Addition = document.createElement('option');
// adding a text to that option
SelectBoxQuery_Addition.text = data[i];
// apply the adding .
SelectBoxQuery.add(SelectBoxQuery_Addition)
}}
The problem is, after i get response from python FLASK to Jquery function. in success part it should launch the javascript function with the same i of the queryTargetList.
for example if i pass data[1], i expect to have queryTargetList[1] also.
but in javascript console.log function. that does not happen. it printing the last item of the queryTargetList list.
Print:
Before Launching the Javascript : Item1
JQueryTests.js:11 Before Launching the Javascript : Item2
JQueryTests.js:11 Before Launching the Javascript : Item3
JQueryTests.js:11 Before Launching the Javascript : Item4
operationJavaScript.js:115 In Get Inventory Function in javascript ... Item4
In Get Inventory Function in javascript ... Item4
In Get Inventory Function in javascript ... Item4
In Get Inventory Function in javascript ... Item4
I do not know what am doing wrong :(
Since the ajax call is an async operation, the loop variable i would have changed by the time the success method gets called. There is no guarantee that the i would have reached the end.
You would need to wrap the variables, in a closure so that it success methods gets the correct item.
Sample code not tested.
$(document).ready(function () {
$('#ProvisionLink').click(function () {
var queryTargetList = [ "Item1","Item2","Item3","Item4"]
var data = ["Data1","Data2","Data3","Data4" ]
event.preventDefault();
var i;
for(i = 0; i < queryTargetList.length; ++i) {
var dataItem = data[i];
var QueryItems = queryTargetList[i];
console.log("Before Launching the Javascript : " +QueryItems)
(data,queryItem)=>{
$.ajax({
url: '/operation',
data: {DataType: data,},
type: 'POST',
success: function (response){ getInventory(response,queryItem) },
error: function (error) {console.log(error);}
});
})(dataItem,QueryItems);
}
});
});
set the async option to false:
$.ajax({
url: '/operation',
data: {DataType: dataItem,},
async: false,
type: 'POST',
success: function (response){ getInventory(response,QueryItems) },
error: function (error) {console.log(error);}
});
Another way: send queryTargetList[i] value to server and response get from server..
You must consider the issue of synchronization and non-synchronization, because you did not set the async attribute, so the default will be true. The easiest way is to set the async attribute to false
Like my example below, for detailed usage, you can refer to here
$.ajax({
url: '/operation',
data: {DataType: dataItem,},
type: 'POST',
async: false,
success: function (response){ getInventory(response,QueryItems) },
error: function (error) {console.log(error);}
});
I'm trying to make a notification system that gets data every 5 secs but I don't know why it doesn't work properly. It outputs the notification endlessly but it should get the data and compare it to the last data it stored and if the data is not the same it should append the notification(s) and when it's the same it should alert "same".
var appliedData;
setInterval(getNotifications, 5000);
function getNotifications(){
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "json",
async: false,
success: function(data) {
if ( appliedData != data ) {
appliedData = data;
for(i=0; i < data.length; i++){
$( ".notification-container" ).append('<div class="notification"><p>' + data[i].user + '</p></div>');
}
}else{
alert("sammee");
}
}
});
}
Objects (any non-primitive: an array is an object) will never be equal to each other unless they reference the same place in memory. When comparing, your appliedData will always be different from your data, so that condition will always fail. If the response strings can be guaranteed to be the same when they represent the same object, you can simply compare the strings, as shown below. If not, you'll have to carry out a deep comparison instead.
let lastDataStr;
setInterval(getNotifications, 5000);
function getNotifications() {
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "text", // change here, then parse into an object in success function
async: false,
success: function(newDataStr) {
if (newDataStr === lastDataStr) {
alert('same');
return;
}
lastDataStr = newDataStr;
const newData = JSON.parse(newDataStr);
newData.forEach(({ user }) => {
$(".notification-container").append('<div class="notification"><p>' + user + '</p></div>');
})
}
});
}
I want to try to display my notification json through ajax, but however when I try first show me undefined, and then show me my json what am I doing wrong?
$(function (doc, win, $) {
var notification = win.Notification || win.mozNotification || win.webkitNotification;
var $badge = $("#notifications-badge");
var $list = $("#notifications-list");
var $button = $("#notifications-button");
URL_GET_NOTIFICATION = BASE_URL + 'notifications/getNotification';
function check_notifications() {
$.ajax({
type: 'GET',
url: URL_GET_NOTIFICATION,
//data: { timestamp : timestamp },
dataType: 'json',
async: true,
success: function (data) {
console.log(data);
}
});
}
$button.click(function (e) {
alert(check_notifications());
});
}(document, window, jQuery));
All functions return undefined by default when called, unless something else is specified.
You'd get the same with just
function go() {};
alert( go() ); // undefined
And that's basically what you're doing, alerting a function that doesn't return anything.
If you return something from the function, it works
function go() { return 'Hello Kitty' };
alert( go() ); // Hello Kitty
But, as you're using ajax inside the function, you can't really return the result from that, as it's asynchronous and executes some time after the result is returned.
You'd have to use a callback or promise to make it work.
function check_notifications() {
return $.ajax({
type: 'GET',
url: URL_GET_NOTIFICATION,
//data: { timestamp : timestamp },
dataType: 'json'
});
}
$button.click(function (e) {
check_notifications().done(function(data) {
alert(data);
});
});
As a sidenote, use the console when debugging, not alerts.
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);
});
I'm trying to work with two XML files. I use the second highlighted answer in this thread [1] as a base script.
This is what I got:
jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'xml',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
});
var party1 = $.getValues('http://data.riksdagen.se/voteringlista/?rm=2010%2F11&bet=&punkt=parti=M&valkrets=&rost=&iid=&sz=500&utformat=xml&gruppering=bet')
var party2 = $.getValues('http://data.riksdagen.se/voteringlista/?rm=2010%2F11&bet=&punkt=&parti=S&valkrets=&rost=&iid=&sz=500&utformat=xml&gruppering=bet')
$(party1).find('votering').each(function(){
var id = $(this).find("forslagspunkt").text()
partyTwo(id)
//-------------------------------------
//HERE I RUN A FEW SIMPLE IF STATEMENTS
//------------------------------------
})
function partyTwo(id) {
$(party2).find('votering').filter(function() {
return $(this).find("forslagspunkt").text() == id;
}).each(function () {
//-------------------------------------
// AGAIN, A FEW SIMPLE IF STATEMENTS
//------------------------------------
return vote
})
}
This leaves me with two problems:
1) partyTwo(id) returns 'undefined', but works fine if I manually insert an id outside.
2) The whole script runs very slow (+5 sec to load).
Any thoughts?
[1] JQuery - Storing ajax response into global variable