I am running match() to loop through an array or stop ID's. For each stop ID I am calling a function which loops through another array of route ID's and through the response of the AJAX call to find a match.
If it finds a match between the routeID and the RouteID in the array then it adds the result to another array in each loop.
My problem is that I can't find a way to determine when the functions called by the match() loop are complete.
The reason I need to do this, is that I need to make sure that the jpFromStops array is complete and ready to be processed by another function.
What is the best way to do this?
function match() {
// Array length is 5
for(i=0; i < fromStopsAr.length; i++) {
getFromRoutesStopId(fromStopsAr[i]);
}
console.log("Match Array Output: " + jpFromStops.toString());
}
function getFromRoutesStopId(id) {
jpFromStops=[];
tempAr = [];
jQuery.ajax({
type: "GET",
url: 'http://apu-url.com/v1/gtfs/routes/stopid/'+id+'?api_key=API_KEY',
dataType: "jsonp",
cache: false,
crossDomain: true,
processData: true,
success: function (data) {
$.each( matchRoutes, function(index, value) {
$.each(data.response, function(key, data) {
if(data.route_short_name.toString() == value) {
jpFromStops[jpFromStops.length] = id + ":" + value;
}
});
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("There is a problem");
}
});
}
Console log Output:
Match Array Output:
jp-main.js (line 177)
2
115
jp-main.js (line 199)
2
113
jp-main.js (line 199)
2
087
You can use a counter...sort of like:
var count = 0;
function getFromRoutesStopId(id) {
jpFromStops=[];
tempAr = [];
jQuery.ajax({
type: "GET",
url: 'http://apu-url.com/v1/gtfs/routes/stopid/'+id+'?api_key=API_KEY',
dataType: "jsonp",
cache: false,
crossDomain: true,
processData: true,
success: function (data) {
count++;
if(count == fromStopsAr.length){your code or function call}
$.each( matchRoutes, function(index, value) {
$.each(data.response, function(key, data) {
if(data.route_short_name.toString() == value) {
jpFromStops[jpFromStops.length] = id + ":" + value;
}
});
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
count++;
if(count == fromStopsAr.length){your code or function call}
alert("There is a problem");
}
});
}
You can return promise and use $.when
function match() {
var promises = [];
// Array length is 5
for(i=0; i < fromStopsAr.length; i++) {
promises.push(getFromRoutesStopId(fromStopsAr[i]));
}
$.when.apply($, promises).then(function() {
console.log("Match Array Output: " + jpFromStops.toString());
});
}
function getFromRoutesStopId(id) {
jpFromStops=[];
tempAr = [];
return jQuery.ajax({
type: "GET",
url: 'http://apu-url.com/v1/gtfs/routes/stopid/'+id+'?api_key=API_KEY',
dataType: "jsonp",
cache: false,
crossDomain: true,
processData: true,
success: function (data) {
$.each( matchRoutes, function(index, value) {
$.each(data.response, function(key, data) {
if(data.route_short_name.toString() == value) {
jpFromStops[jpFromStops.length] = id + ":" + value;
}
});
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("There is a problem");
}
});
}
When dealing with ajax calls, you need wait until each of them has finished the execution.
Follow this pattern:
var jobs = [11, 12, 14, 15];
function doTheJob() {
if (jobs.length === 0) {
alert('All jobs are done now.');
complete();
return;
}
var job_Id = jobs.pop();
$.ajax({
url: "/DoTheJob",
complete: function () {
doTheJob();
}
});
};
Related
Ok, so I've got a loop like so:
underscore.each(dom.paramArray, function(value, i) {
fetchDataFromServerWithParams(value, i);
});
In my current example it loops 3 times, idealy like: 0,1,2
However, when I log the index of the function called, it logs: 1,0,2, why ?
And how can I get it to call the function recursively, so first it will process the function with index:0, then index:1, and lastly, index:2
I think it has something to do with the functions I am calling (buildResult and buildSubResult), but Im really not sure?
The function that is called by the loop looks like:
function fetchDataFromServerWithParams(param, index) {
//Create promise
let getData = $.ajax({
headers: {
Accept : "text/plain; charset=utf-8",
"Content-Type": "text/plain; charset=utf-8"
},
type: "GET",
url: configuration.apiEndpoint,
data: { id: param},
dataType: "json"
});
//When done processing promise, build result
getData.then(function (data) {
let generatedData;
console.log(index);
if(index === 0) {
generatedData = buildResult(data);
} else {
$.each($("ul.material a"), function( index, value ) {
var target = $(this).parent();
if($(this).data("id") == param) { //Refactor later to ===
target.parent().addClass("open-folder");
target.parent().parent().find("ul").addClass("open-folder");
generatedData = buildSubResult(data, target);
}
});
}
}), function(xhr, status, error) {
// Handle errors for any of the actions
handleError(error);
};
}
you can use async library or any other library for this purpose
also you can change the line
getData.then(function (data) {
to
return getData.then(function (data) {
and use this code instead of your underscore loop
(function sequenceCall(index){
fetchDataFromServerWithParams(dom.paramArray[index], index).then(function(){
sequenceCall(index+1);
});
})(0);
I am attempting to do an AJAX call with the Select2 jquery plugin. The query seems to be working, but the issue occurs when .results() is called on the options object:
Uncaught TypeError: options.results is not a function
Here is my HTML:
<input class="form-control" type="number" value="2125" name="topic_relation[source_topic_id]" id="topic_relation_source_topic_id" />
Here is my JS:
$(document).ready(function() {
$('#topic_relation_source_topic_id').select2({
minimumInputLength: 3,
ajax: {
url: "<%= grab_topics_path %>",
dataType: 'json',
delay: 250,
data: function (term, page) {
return {
q: term, //search term
page_limit: 30, // page size
page: page, // page number
};
},
processResults: function (data, page) {
var more = (page * 30) < data.total;
return {results: data.topics, more: more};
}
},
formatResult: topicFormatResult,
formatSelection: formatRepoSelection,
escapeMarkup: function (m) { return m; }
});
function topicFormatResult(topic) {
return topic.name
}
function formatRepoSelection(topic) {
return '<option value="'+ topic.id +'">' + topic.name + '</option>'
}
});
Here is the returned JSON:
{"total":2, "topics":[{"id":305,"name":"Educational Assessment, Testing, And Measurement"},{"id":3080,"name":"Inspectors, Testers, Sorters, Samplers, And Weighers"}]}
Here is the code which is failing:
function ajax(options) {
var timeout, // current scheduled but not yet executed request
handler = null,
quietMillis = options.quietMillis || 100,
ajaxUrl = options.url,
self = this;
return function (query) {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
var data = options.data, // ajax data function
url = ajaxUrl, // ajax url string or function
transport = options.transport || $.fn.select2.ajaxDefaults.transport,
// deprecated - to be removed in 4.0 - use params instead
deprecated = {
type: options.type || 'GET', // set type of request (GET or POST)
cache: options.cache || false,
jsonpCallback: options.jsonpCallback||undefined,
dataType: options.dataType||"json"
},
params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated);
data = data ? data.call(self, query.term, query.page, query.context) : null;
url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
if (handler && typeof handler.abort === "function") { handler.abort(); }
if (options.params) {
if ($.isFunction(options.params)) {
$.extend(params, options.params.call(self));
} else {
$.extend(params, options.params);
}
}
$.extend(params, {
url: url,
dataType: options.dataType,
data: data,
success: function (data) {
========> var results = options.results(data, query.page, query); <==========
query.callback(results);
},
error: function(jqXHR, textStatus, errorThrown){
var results = {
hasError: true,
jqXHR: jqXHR,
textStatus: textStatus,
errorThrown: errorThrown
};
query.callback(results);
}
});
handler = transport.call(self, params);
}, quietMillis);
};
}
Since the plugin calls results(), you should also declare results: function (data, page) instead of processResults: function (data, page).
I have two javascript function which populate some data using jquery json. Both working fine but problem is that second function getting called before first one execute. My code is :
$(document).ready(function () {
loadSubject();
getTopic();
});
function loadSubject() {
var CourseId = document.getElementById('CourseId').value;
alert('22222');
jQuery.support.cors = true;
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
dataType: 'json',
success: function (data) {
var subjectDivs = "";
var divs = "";
var i = 1;
$.each(data, function (index, value) {
divs = "";
// Some code here
i = i + 1;
});
subjectDivs = subjectDivs + divs;
alert('11111');
$('#cCount').val(i);
document.getElementById('accordion').innerHTML = subjectDivs;
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
function getTopic() {
var c = $('#cCount').val();
alert(c);
for (var i = 1; i <= c; i++) {
var subId = $('#hdn_' + i).val();
jQuery.support.cors = true;
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Topic', UserRecId: 0, ParentId: subId },
dataType: 'json',
success: function (data) {
var topicDivs = "";
var divs = "";
tDivs = '';
$.each(data, function (index, value) {
divs = '';
divs = '<div class="row">';
divs = divs + '<div class="subject">' + value.Name + '</div>';
divs = divs + "</div>";
topicDivs = topicDivs + divs;
});
$('#sDiv_' + i).html(topicDivs);
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
}
This is not the way how ajax get executes. If you put two jquery ajax requests one by one then they will execute in sequence by it is not necessary that second request will be executed after first request completes or response of first request is received.
If you want this to happen then there are two ways
1. Use async:'false'
This makes a request to wait until response is recieved before executing next statement in javascript.
What does "async: false" do in jQuery.ajax()?
2. Use callbacks
Write the second function which you want to execute in success or complete callback of your first ajax request.
jQuery ajax success callback function definition
Try adding return statement before $.ajax({}) within both loadSubject and getTopic , to return jQuery promise object , which can be handled at deferred.then
function loadSubject() {
return $.ajax()
}
function getTopic() {
return $.ajax()
}
loadSubject().then(getTopic);
function a() {
return new $.Deferred(function(dfd) {
setTimeout(function() {
dfd.resolve(1)
}, 2000)
}).promise().then(function(data) {
console.log(data)
})
}
function b() {
return new $.Deferred(function(dfd) {
setTimeout(function() {
dfd.resolve(2)
}, 2000)
}).promise().then(function(data) {
console.log(data)
})
}
a().then(b)
You have to add async:false in your first ajax request, it stop next execution till first ajax request will complete its execution.
So your first function like this
function loadSubject() {
var CourseId = document.getElementById('CourseId').value;
jQuery.support.cors = true;
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
dataType: 'json',
async:false,
success: function (data) {
var subjectDivs = "";
var divs = "";
var i = 1;
$.each(data, function (index, value) {
divs = "";
// Some code here
i = i + 1;
});
subjectDivs = subjectDivs + divs;
alert('11111');
$('#cCount').val(i);
document.getElementById('accordion').innerHTML = subjectDivs;
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
Call second function from first ajax success function
$(document).ready(function () {
loadSubject();
});
function loadSubject() {
// code here
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
dataType: 'json',
success: function (data) {
//code here
getTopic(); // Second function calling
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
Now when first function is executed successfully then second function will be called.
I have these ajax calls that need to get called when the previous one is success, meaning once the first ajax is OK, call the 2nd ajax, once the 2nd ajax is OK call the 3rd one, etc so on. I started with a few ajax calls so it was fine to chain them up like this below but now I have about 20 of them and it'd be a mess to chain them up like this.
$.ajax({
url: 'urlThatWorks1',
success: function (data) {
//call someMethod1 with data;
$.ajax({
url: 'urlThatWorks2',
success: function (data) {
//call method2 with data;
//another ajax call ... so on
}
}.... 19 level deep
So I need to make it bit easier to read and maintain so I'm thinking something like
var ajaxArray = [];
var function1 = $.ajax('urlThatWorks1', data I get back from the 'urlThatWorks1' call);
myArray.push(function1);
var function2 = $.ajax('urlThatWorks2', data I get back from the 'urlThatWorks2' call);
myArray.push(function2);
//etc 19 others
myArray.each(index, func){
//Something like $.when(myArray[index].call()).done(... now what?
}
Hope this makes sense, I'm looking for a way of ajax call array from which I can call an ajax call on whose success I call the next ajax in the array. Thanks.
Create a recursive function to be called in sequence as the ajax requests return data.
var urls = [ "url.1", "url.2", ... ];
var funcs = [];
function BeginAjaxCalls()
{
RecursiveAjaxCall(0, {});
}
function RecursiveAjaxCall(url_index)
{
if (url_index >= urls.length)
return;
$.ajax(
{
url: urls[url_index],
success: function(data)
{
funcs[url_index](data);
// or funcs[urls[url_index]](data);
RecursiveAjaxCall(url_index + 1);
}
});
}
funcs[0] = function(data)
// or funcs["url.1"] = function(data)
{
// Do something with data
}
funcs[1] = function(data)
// or funcs["url.2"] = function(data)
{
// Do something else with data
}
Try
$(function () {
// requests settings , `url` , `data` (if any)
var _requests = [{
"url": "/echo/json/",
"data": JSON.stringify([1])
}, {
"url": "/echo/json/",
"data": JSON.stringify([2])
}, {
"url": "/echo/json/",
"data": JSON.stringify([3])
}];
// collect responses
var responses = [];
// requests object ,
// `deferred` object , `queue` object
var requests = new $.Deferred() || $(requests);
// do stuff when all requests "done" , completed
requests.done(function (data) {
console.log(data);
alert(data.length + " requests completed");
$.each(data, function (k, v) {
$("#results").append(v + "\n")
})
});
// make request
var request = function (url, data) {
return $.post(url, {
json: data
}, "json")
};
// handle responses
var response = function (data, textStatus, jqxhr) {
// if request `textStatus` === `success` ,
// do stuff
if (textStatus === "success") {
// do stuff
// at each completed request , response
console.log(data, textStatus);
responses.push([textStatus, data, $.now()]);
// if more requests in queue , dequeue requests
if ($.queue(requests, "ajax").length) {
$.dequeue(requests, "ajax")
} else {
// if no requests in queue , resolve responses array
requests.resolve(responses)
}
};
};
// create queue of request functions
$.each(_requests, function (k, v) {
$.queue(requests, "ajax", function () {
return request(v.url, v.data)
.then(response /* , error */ )
})
})
$.dequeue(requests, "ajax")
});
jsfiddle http://jsfiddle.net/guest271314/6knraLyn/
See jQuery.queue() , jQuery.dequeue()
How about using the Deferred approach. Something like:
var arrayOfAjaxCalls = [ { url: 'https://api.github.com/', success: function() { $("#results").append("<p>1 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>2 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>3 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>4 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>5 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>6 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>7 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>8 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>9 done</p>"); } }
];
loopThrough = $.Deferred().resolve();
$.each(arrayOfAjaxCalls, function(i, ajaxParameters) {
loopThrough = loopThrough.then(function() {
return $.ajax(ajaxParameters);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="results"></div>
You could use the async library, which has a bunch of functions like waterfall or series which could solve your problem.
https://github.com/caolan/async#series
https://github.com/caolan/async#waterfall
I am looking for advice to ensure that I am using callbacks and javascript coding using generally accepted js guidelines. What is listed below is two functions which are chained together. Basically its a list of checks which need to be completed prior to creating the entity. I don't expect the final version to use a ajax POST but it is a good way to test all of the error handling.
Advice or recommendations would be appreciated!! I will give credit to the best explained and critiqued answer.
function relationship_check(app_label, model, company_id, params, form, callback_function){
// This will check to see if a relationship exists. This works even on new objects.
kwargs = $.extend({}, params);
kwargs['app_label'] = app_label;
kwargs['model'] = model;
kwargs['relationship__company'] = company_id;
kwargs['error_on_objects_exists_and_no_relation'] = true;
ajax_req = $.ajax({
url: "{% url 'api_get_discover' api_name='v1' resource_name='relationship' %}",
type: "GET",
data: kwargs,
success: function(data, textStatus, jqXHR) {
callback_function(form, params)
},
error: function(data, textStatus, jqXHR) {
results = $.parseJSON(data.responseText)
if (results['object_exists'] && ! results['relationships_exists']){
django_message(results['create_string'], "info");
} else {
django_message(results['error'], "error");
}
return false
}
})
return false
};
function create_community(form, data){
var self = $(this),
ajax_req = $.ajax({
url: self.attr("action"),
type: "POST",
data: data,
success: function(data, textStatus, jqXHR) {
django_message("Saved successfully.", "success");
},
error: function(data, textStatus, jqXHR) {
var errors = $.parseJSON(data.responseText);
$.each(errors, function(index, value) {
if (index === "__all__") {
console.log(index + " : " + value )
django_message(value[0], "error");
} else {
console.log(index + " : " + value )
apply_form_field_error(index, value);
}
});
}
});
}
$(document).on("submit", "#community_form", function(e) {
e.preventDefault();
clear_form_field_errors("#community_form");
var data = {
name: $(this).find("#id_name").val(),
city: $(this).find("#id_city").val(),
cross_roads: $(this).find("#id_cross_roads").val(),
website: $(this).find("#id_website").val(),
latitude: $(this).find("#id_latitude").val(),
longitude: $(this).find("#id_longitude").val(),
confirmed_address: $(this).find("#id_confirmed_address").val()
};
console.log(data)
relationship_check(
'community', 'community', '{{ request.user.company.id }}',
data, "#community_form", create_community);
});