AJAX calls inside a loop - javascript

So, I have a list of data that I am out putting onto my view, and each list item has an id.
Each of these list items is a bar and I have a document created for each bar that at least one user is going to. For those bars where no users are going, there is no document created.
I need to make an AJAX call for each list item to the database to check
i) If a document exists for that list item
ii) If a document exists, how many users are going according to the document.
I attempted a solution using a while loop, where the update for the while loop was contained in the callback for the AJAX call. Here is the code
function updateAllGoingButtons(){
var i = 0;
var dataToPass = {};
var numButtons = global_data_object.listData.businesses.length;
while(i < numButtons){
dataToPass.button = global_data_object.listData.businesses[i].id;
dataToPass = JSON.stringify(dataToPass);
ajaxFunctions.ready(ajaxFunctions.ajaxRequest('POST', '/update-buttons', dataToPass, function(data){
console.log(i);
i++;
}));
}
}
When I attempted to run the function, I got the error,
Request entity too large
So, is there a better way to go about doing what I am trying to do? Should I use promises? Or is there simply an error in the way I am trying to make the AJAX call from within a while loop?
For reference, here is the ajaxRequest function
'use strict';
var appUrl = window.location.origin;
var ajaxFunctions = {
ready: function ready (fn) {
if (typeof fn !== 'function') {
return;
}
if (document.readyState === 'complete') {
return fn();
}
document.addEventListener('DOMContentLoaded', fn, false);
},
ajaxRequest: function ajaxRequest (method, url, data, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
callback(xmlhttp.response);
}
};
xmlhttp.open(method, url, true);
xmlhttp.setRequestHeader('Content-type', 'application/json');
xmlhttp.send(data);
}
};

You should check out the npm library called async, it has an each method that you can do asynchronous calls within. If you use promises, the Promise.all method in Bluebird could be very useful for you.

So, here's how I did the multiple AJAX calls from within a loop. I used this resource https://medium.com/coding-design/writing-better-ajax-8ee4a7fb95f#.d7ymg99mp (Great resource!)
Here's the code
$('.btn-group').find('button').each(function() {
console.log($(this).attr('id'));
dataToPass.button = $(this).attr('id');
var ajax = $.ajax({
url: '/update-buttons',
method: 'post',
data: dataToPass,
dataType: 'json',
}).success(function(data){
console.log(data);
});
});
Essentially, what this does is selects a div with the class 'btn-group' and then iterates over each button within that div using the jQuery each operator. Then simply make an AJAX request and use the success chain callback to access the returned data.

Related

AJAX call finishes after rest of the script

I Have an AJAX call to get entry's of a list from a database. So I recieve the Data from my Ajax call, but they are a little bit to "late" so the rest of the actions start before the neccessary data is fully loaded (see screenshot). Is there a way to pause the script until the ajax data is fully loaded to use all of the information? Does this happen because of the "asynchronus = true" ?
Would be nice to get some answers, Thanks!
Console shows this:
I tried to re-order the script, but nothing really changed the problem.
var data_array = [];
var data = [];
var output = document.getElementById('entry-list');
/*Static Data Variables for Data Call*/
var name;
var priority;
var category;
var expiry;
/*Call AJAX*/
var ajax = new XMLHttpRequest();
var method = "GET";
var url = "getdata.php";
var asynchronous = true;
ajax.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200) {
/*getting return --> putting/convert json into array*/data.push(JSON.parse(this.responseText));
console.log(data.length);
for(var a = 0; a<data.length; a++){
name = data[a].name;
priority = data[a].priority;
category = data[a].category;
expiry = data[a].expiry;
data_array.push("<li class='' id='list-item"+a+"' onclick='itemClick(this)'>"+name+" #"+a+", "+priority+"</li>");
console.log("Array-entry added");
}
}
}
ajax.open(method, url, asynchronous);
//sending
ajax.send();
//recieving asnwer from getdata.php
console.log(data_array);
output.innerHTML = data_array;
Is there a way to pause the script
You're thinking about this the wrong way. Instead of trying to force operations to be blocking, instead re-structure your code to use the data in response to the asynchronous operation. Basically, the lines after //recieving asnwer from getdata.php should be in the callback function, not after it.
So instead of something like this:
ajax.onreadystatechange = function()
{
// the rest of your code
}
ajax.open(method, url, asynchronous);
ajax.send();
console.log(data_array);
output.innerHTML = data_array;
You would do something like this:
ajax.onreadystatechange = function()
{
// the rest of your code
console.log(data_array);
output.innerHTML = data_array;
}
ajax.open(method, url, asynchronous);
ajax.send();
Naturally, your code could get larger and more complex than just those two lines. How you structure the more complex operations is up to you. But the point is that those operations should be invoked by the response handler for the AJAX function.
You can do it this way with jquery AJAX.
$.ajax({
method:"POST",
url:"URL",
data: {name:value},
success: function (responseText) {
//CODE HERE RUN AFTER DATA FULLY LOADED
}
});

Parsing arguments to functions involving ajax

I am having an issue trying to improve the functionality of my ajax functions by adding arguments to define what to do with the returned result.
So what i am trying to implement is a way to tell the function to append the result to a given element by its id. But i am having difficulty understanding how to add this functionality.
This is my current code:
var ajax = new function(){
var self = this;
self.x = function() {
if (typeof XMLHttpRequest !== 'undefined') {
return new XMLHttpRequest();
}
};
self.send = function(url, callback, method, data, sync) {
var x = self.x();
x.open(method, url, sync);
x.onreadystatechange = function() {
if (x.readyState == 4) {
callback(x.responseText)
}
};
if (method == 'POST') {
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
x.send(data)
};
self.get = function(url, data, callback, sync) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
self.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, sync)
};
};
I then make an ajax request like so:
//get the html file, and then call a function
ajax.get(dir.layout+'login.html',false,
function(){
elements.addTemplate(data,'parent',true);
});
In Chrome the xhr shows the correct data and contents, so i know that part works. In my elements.loadTemplate function i have these three lines with their actual values:
elements.addtemplate(data,div_id,append){
console.log(data); //shows:
console.log(div_id); //shows string: parent
console.log(append); //shows: true
}
Now the issue is data is blank, when i want it to contain the contents of the HTML file that I just requested (in this case login.html). I am wondering why it would show up as blank and how i can fix it?
your data is undefined because your callback doesn't accept a parameter
try this:
ajax.get(dir.layout+'login.html',false,
function(data){ // <=== data
elements.addTemplate(data,'parent',true);
});

multiple calls to ajax simultaneously

I'm trying to make multiple calls to Ajax, i have fields like time intervals and no of calls to ajax under that time period. Now the problem is, while making multiple calls to same Ajax, there may be chances of merging of data with the other data that were send to Ajax earlier. I am not sure that it will happen.
Here my Ajax call.
callAjax = function () {
var dataIn = inObj.data || {};
var successFunc = inObj.success || function () {};
var passOn = inObj.passOn || {};
var myParams = {drape:1,type:'GET'};
myParams.url = this.homeComingUrl;
$.extend(myParams,params);
var data = this.fillAction(action,dataIn);
if (myParams.drape) { vidteq.utils.drapeSheer(action); }
var that = this;
var magicCall = $.ajax({
url:myParams.url,
type:myParams.type,
data:data,
success: function (response) {
// TBD we need better error handling
if (myParams.drape) { vidteq.utils.undrapeCurtain(action); }
successFunc(response,passOn);
},
error:function(response) {
if (myParams.drape) { vidteq.utils.undrapeCurtain(action); }
that.gui.io.handleError(response);
}
});
}
saveEvents = function () {
this.commitEditingEvent();
var dataEvents = this.collectEventsToSave();
//$('#calendar').fullCalendar('removeEvents');
var that = this;
if (vidteq.eTrainer==1) {
dataEvents = arguments[0];
}
if (!dataEvents.length) { alert("Nothing to save");return; }
this.callAjax('updateEvents',{
data : { events : JSON.stringify(dataEvents) },
success : function (response,passOn) {
that.handleGetEvent(response,passOn);
}
},{type:'POST'});
}
This may not be required for understanding the problem.
If any body can explain how Ajax handles multiple calls, then it'll really helpful.
First line, your anonymous function isn't saved and isn't ran. Then. In each function, what does this refer to ? What is this context ? Is this window or do you call your function like saveEvents.apply( jQuery ) ?
JavaScript is powerful, when your want to run XMLHttpRequest (Ajax uses it), scripts are called when an event happen, like "server is found", "request is send", "file is reading", "file loaded"... for each state of your request. Ajax by jQuery help you to request asynchronous. You can request as many Ajax request as you would like in the same time. The important is to create a function happen in success case.
In this success function, you receive data, you compute it, then this function may call another Ajax request, and so on. When you chain requests like this to get the same file, we call it Ressource.
Ressource uses Ajax which uses XMLHttpRequest.
you need to do asynic :false in your ajax method
function isLoggedIn() {
var isLoggedIn;
$.ajax({
async: false,
// ...
success: function(jsonData) {
isLoggedIn = jsonData.LoggedIn
}
});
return isLoggedIn
}

Making functions wait until AJAX call is complete with jQuery

Im trying to develop a class in JavaScript I can use to access a load of data that is gathered by an AJAX request easily. The only problem is I need to make the members of the class accessible only once the AJAX call is complete. Ideally what I would like to end up is something where by I can call this in a script:
courses.getCourse('xyz').complete = function () {
// do something with the code
}
And this will only fire after the AJAX call has been complete and the data structures in the "class" are ready to be used. Ideally I dont want to have to create a .complete member for every function in the class
Here is the "class" I am trying to make so far:
var model_courses = (function() {
var cls = function () {
var _storage = {}; // Used for storing course related info
_storage.courses = {}; // Used for accessing courses directly
_storage.references = new Array(); // Stores all available course IDs
var _ready = 0;
$.ajax({
type: "GET",
url: "data/courses.xml",
dataType: "xml",
success: function(xml) {
$(xml).find("course").each(function() {
_storage.courses[$(this).attr('id')] = {
title : $(this).find('title').text(),
description : $(this).find('description').text(),
points : $(this).find('points').text()
}
_storage.references.push($(this).attr('id'))
})
}
})
console.log(_storage.courses)
}
cls.prototype = {
getCourse: function (courseID) {
console.log(cls._storage)
},
getCourses: function () {
return _storage.courses
},
getReferences: function (),
return _storage.references
}
}
return cls
})()
At the moment getCourse will be fired before the AJAX request is complete and obviously it will have no data to access.
Any ideas will be greatly appreciated, im stuck on this one!
jQuery already handles this for you using deferred objects, unless i'm misunderstanding what you are looking for.
var courses = {
getCourse: function (id) {
return $.ajax({url:"getCourse.php",data:{id:id});
}
};
courses.getCourse("history").done(function(data){
console.log(data);
});
I know this isn't exactly what you are looking for, I'm hoping it's enough to push you in the right direction. Deferred objects are awesome.
The following changes allow you to make the AJAX request just once and you can call your function like
courses.getCourse('xyz', function(course){
// Use course here
});
Here are the changes
var model_courses = (function() {
// This is what gets returned by the $.ajax call
var xhr;
var _storage = {}; // Used for storing course related info
_storage.courses = {}; // Used for accessing courses directly
_storage.references = []; // Stores all available course IDs
var cls = function () {
xhr = $.ajax({
type: "GET",
url: "data/courses.xml",
dataType: "xml",
success: function(xml) {
$(xml).find("course").each(function() {
_storage.courses[$(this).attr('id')] = {
title : $(this).find('title').text(),
description : $(this).find('description').text(),
points : $(this).find('points').text()
}
_storage.references.push($(this).attr('id'))
});
}
});
}
cls.prototype = {
// Made changes here, you'd have to make the same
// changes to getCourses and getReferences
getCourse: function (courseID, callback) {
if (xhr.readyState == 4) {
callback(_storage.courses[courseID]);
}
else {
xhr.done(function(){
callback(_storage.courses[courseID]);
})
}
},
getCourses: function () {
return _storage.courses
},
getReferences: function (),
return _storage.references
}
}
return cls
})()
As a side note, your module pattern will not work very well if you need to instantiate two of these model_courses objects, since the storage objects are all shared in your self calling function's closure. You usually don't mix the module pattern with prototypes (returning a constructor from a module), unless you really know what you are doing, that is, the shared closure variables work as static properties of your class.
This is what I would do if I were you (since you really want private variables)
function ModelCourses() {
var storage = {
courses: {},
references: []
};
var xhr = $.ajax({
type: "GET",
url: "data/courses.xml",
dataType: "xml",
success: function(xml) {
$(xml).find("course").each(function() {
storage.courses[$(this).attr('id')] = {
title : $(this).find('title').text(),
description : $(this).find('description').text(),
points : $(this).find('points').text()
}
storage.references.push($(this).attr('id'))
})
}
});
this.getCourse = function(courseId, callback) {
function getCourse() {
callback(storage.courses[courseID])
}
if (xhr.readyState == 4) {
getCourse();
}
else {
xhr.done(getCourse);
}
};
}
in getStorage either add a check to see if there is any data to pilfer (preferred), or make the "actual" method private than publicize it when it has items it can access. (I would recommend the first though otherwise you'll get exceptions about calling a method that doesn't exists on an object).
You can define a function getData that would perform the ajax request and that would take the getCourse as a callback.
The getData could possibly store locally the result of the Ajax call and test the local storage before performing the ajax call.
You could also specify a private member to allow the ajax call to be run only once.
You might want to check underscore.js for some handy tool
Here is a short example code :
cls.prototype.getData = function(callback) {
/*perform ajax call or retrieve data from cache*/
callback()
}
cls.prototype.getCourse = function(id) {
this.getData(function() {
/*do something with the data and the id you passed*/
}
}

Use jQuery to replace XMLHttpRequest

I am quite new to JavaScript libraries. I wanted to replace my current code with jQuery. My current code looks like this:
var req;
function createRequest() {
var key = document.getElementById("key");
var keypressed = document.getElementById("keypressed");
keypressed.value = key.value;
var url = "/My_Servlet/response?key=" + escape(key.value);
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("Get", url, true);
req.onreadystatechange = callback;
req.send(null);
}
function callback() {
if (req.readyState == 4) {
if (req.status == 200) {
var decimal = document.getElementById('decimal');
decimal.value = req.responseText;
}
}
clear();
}
I wanted to replace my code with something a little friendlier like jQuery's
$.get(url, callback);
However it doesn't call my callback function.
Also I would like to call a function called createRequest continuously. Does jQuery have a nice way of doing that?
­­­­­­­­­­­­­­­­­­­­­­­
$.get(url, {}, callback);
should do the trick. Your callback could be simplified like this:
function callback(content){
$('#decimal').val(content);
}
Or even shorter:
$.get(url, {}, function(content){
$('#decimal').val(content);
});
And all in all I think this should work:
function createRequest() {
var keyValue = $('#key').val();
$('#keypressed').val(keyValue);
var url = "/My_Servlet/response";
$.get(url, {key: keyValue}, function(content){
$('#decimal').val(content);
});
}
Take out the readyState and status checks. jQuery only calls your callback upon success. Your callback is supplied the arguments (data, textStatus), so you should use data instead of req.responseText.
window.setTimeout() as suggested by another answer won't do what you want - that only waits and then calls your function once. You need to use window.setInterval() instead, which will call your function periodically until you cancel it.
So, in summary:
var interval = 500; /* Milliseconds between requests. */
window.setInterval(function() {
var val = $("#key").val();
$("#keypressed").val(val);
$.get("/My_Servlet/response", { "key": val }, function(data, textStatus) {
$("#decimal").val(data);
});
}), interval);
I don't think jQuery implements a timeout function, but plain old javascript does it rather nicely :)
According to the docs, jQuery.get's arguments are url, data, callback, not url, callback.
A call to JavaScript's setTimeout function at the end of your callback function should suffice to get this to continually execute.
There's no need to set the GET parameters on the URL, jQuery will set them automatically. Try this code:
var key = document.getElementById("key");
[...]
var url = "/My_Servlet/response";
$.get (url, {'key': key}, function (responseText)
{
var decimal = document.getElementById ('decimal');
decimal.value = responseText;
});
In the end I guess it was added the type. This seems to work for me.
function convertToDecimal(){
var key = document.getElementById("key");
var keypressed = document.getElementById("keypressed");
keypressed.value = key.value;
var url = "/My_Servlet/response?key="+ escape(key.value);
jQuery.get(url, {}, function(data){
callback(data);}
, "text" );
}
function callback(data){
var decimal = document.getElementById('decimal');
decimal.value = data;
clear();
}
Thanks Everyone for the help. I'll vote you up.

Categories

Resources