Loop through XML files jQuery - javascript

I am a bit stuck with the following problem.
I have several XML files tagged by an ID (every XML is id'd by a value). I am now trying to loop through these files and output its contents to HTML.
However it starts the loop before it does the call back
Loop0
Loop1
Loop2
Callback0
Callback1
Callback2
I would need
Loop0
Callback0
Loop1
Callback1
As I need to control the results at some point.
var allContent=["xmlfile1","xmlfile2","xmlfile3","xmlfile4"];
var totalSearch = 0;
var countSearch = 0;
function doSearch() {
var oldContentID = contentID;
for (iSearch=0;iSearch<allContent.length;iSearch++) {
totalSearch = totalSearch + countSearch;
contentID = allContent[iSearch];
defineContent();
getXML();
}
}
function getXML() {
$.ajax({
type: "GET",
url: langFile,
dataType: "xml",
beforeSend: function(){
$('#results-list').empty();
$('#results-list').hide();
$('#loading').addClass('loading');
},
success: function(xml) {
var totalElements;
var intSearch = 0;
totalSearch = totalSearch + countSearch;
countSearch = 0;
var searchText = $('#text').val().toLowerCase();
totalElements = $(xml).find('news').length;
while (intSearch < totalElements) {
oFeed = $(xml).find('news:eq('+intSearch+')');
var headline = oFeed.find('headline').text();
var newsText = oFeed.find('detail').text();
var section = oFeed.find('section').text();
var category = oFeed.attr('category');
var stripEnters = newsText.match(/\r?\n|\r/gi);
if (stripEnters != null) {
for (var s = 0; s < stripEnters.length ; s++ ){
newsText = newsText.replace(stripEnters[s],'');
}
}
var newsText2 = $.htmlClean(newsText, {format:true});
var newsText3 = $(newsText2)
var newsText4 = $(newsText3).text();
var newsText5 = newsText4.replace( /\W/gi, "" );
if (section.toLowerCase() == "news" || section.toLowerCase() == "featured") {
if (headline.toLowerCase().indexOf(searchText) >= 0) {
$('<dt></dt>').html(headline).appendTo('#results-list');
$('<dd></dd>').html(newsText).appendTo('#results-list');
countSearch++;
}//end if
else if (newsText5.toLowerCase().indexOf(searchText) >= 0) {
$('<dt></dt>').html(headline).appendTo('#results-list');
$('<dd></dd>').html(newsText).appendTo('#results-list');
countSearch++;
}
}
intSearch++;
}
}
});
}
At the end of the call backs I need to run the following, however it now executes this function before it finishes all call backs.
function displayResults() {
if (totalSearch == 0)
{
alert("No results found");
$('#loading').removeClass('loading');
$('#main').fadeIn(1000);
}
else {
dynamicFaq();
$('<p></p>').html(totalSearch + ' Results found').prependTo('#results-list');
$('#results-list').fadeIn(1000);
$('#loading').removeClass('loading');
}
}

If I understood you correctly, you want to load 1 xml file, loop, and then start to load the next xml file. If so, here is a little pseudo code:
function doSearch(int xmlFileIterator){
if (xmlFileIterator < allContent.length) {
...
contentID = allContent[xmlFileIterator];
...
getXml(xmlFileIterator);
} else {
//no more xml files left
displayResults();
}
}
function getXml(int xmlFileIterator) {
...
success: function() {
...
doSearch(++xmlFileIterator);
}
}
The first call is doSearch(0) which loads the first xml file. After the file is loaded and the loop is done (in success) you can call the doSearch function again with a higher number (iterator).

I see your AJAX call is Asynchronous. Try using
....
type: "GET",
url: langFile,
async: false,
dataType: "xml",
.....

Maintain a ajax queue so thos ajax call will be done one by one. plus maintain a global variable searchedCount which will maintain how main xml are proccessed.
In complete callback of ajax check for the searchedCount and call displayResults function .
var allContent = ["xmlfile1", "xmlfile2", "xmlfile3", "xmlfile4"];
var totalSearch = 0;
var countSearch = 0;
var searchedCount = 0;
var ajaxQueue = $({});
$.ajaxQueue = function (ajaxOpts) {
// Hold the original complete function.
var oldComplete = ajaxOpts.complete;
// Queue our ajax request.
ajaxQueue.queue(function (next) {
// Create a complete callback to fire the next event in the queue.
ajaxOpts.complete = function () {
// Fire the original complete if it was there.
if (oldComplete) {
oldComplete.apply(this, arguments);
}
// Run the next query in the queue.
next();
};
// Run the query.
$.ajax(ajaxOpts);
});
};
function doSearch() {
var oldContentID = contentID;
searchedCount = 0;
for (iSearch = 0; iSearch < allContent.length; iSearch++) {
totalSearch = totalSearch + countSearch;
contentID = allContent[iSearch];
defineContent();
searchedCount++;
getXML();
}
}
function getXML() {
$.ajaxQueue({
type: "GET",
url: langFile,
dataType: "xml",
beforeSend: function () {
$('#results-list').empty();
$('#results-list').hide();
$('#loading').addClass('loading');
},
success: function (xml) {
//your code
},
complete: function () {
if (searchedCount == allContent.length) {
displayResults()
}
}
});
}

Related

AJAX keep showing wrong data from array

I have a loop that calls multiples AJAX to find out if there's any booking in the database or not. JS will pass the data from an array to AJAX and find it out in database through SQL query.
However, the data returned from the AJAX is correct, and if it's there in database, i want to to show the data returned from AJAX and the current value of array in current loop, but still the data that i show from the array is the last index of array.
javascript :
function getButtonInfo() {
var jam = [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
var lap = ['Lapangan A','Lapangan B','Lapangan Batminton'];
var lapId = ['lapA','lapB','lapBat'];
for (var j = 0; j < lap.length; j++){
for (var i = 0;i < jam.length; i++){
var lapIdFix = jam[i]+lapId[j];
var lapId2 = jam[i]+lap[j];
var lap1 = lap[j];
if(jam[i] < 10){
var jamFix = '0'+jam[i]+':00:00';
}else{
var jamFix = jam[i]+':00:00';
}
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
},
error: function () {
$('#output').html('ERROR!');
},
});
}
}
return false;
}
PHP File:
<?php
ob_start();
$error=""; // Variable To Store Error Message
$connection = mysqli_connect(/*credential*/);
$tgl = $_POST['date'];
$time = $_POST['time'];
$lap = $_POST['lapangan'];
//Query
$query = mysqli_query($connection, "SELECT * FROM lapangan_book WHERE tanggal='$tgl' and jam='$time' and lapangan='$lap'");
$rows = mysqli_num_rows($query);
$data = mysqli_fetch_array($query);
if($rows > 0){
echo $data['lapangan'];
}else{
echo "0";
}
?>
The output should be
Lapangan A
22lapA
22Lapangan A
But keep showing
Lapangan A
22lapBat
22Lapangan Batminton
Yes, this is happening because of the Asyncroniouse behavior of ajax. There is two tricks you have to send asynchronous request by async: false or you have to call the recursive function after success response from ajax request.
Trick 1- Pass option aysnc: false in ajax request, but some browser will throws warning in synchronous request of ajax
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
async:false,
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
},
error: function () {
$('#output').html('ERROR!');
},
});
}
Trick 2: Recursive function, this is most accurate way of calling
function getButtonInfo() {
var jam = [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
var lap = ['Lapangan A','Lapangan B','Lapangan Batminton'];
var lapId = ['lapA','lapB','lapBat'];
var i=0;
var j=0;
var ajaxCall= function(){
var lapIdFix = jam[i]+lapId[j];
var lapId2 = jam[i]+lap[j];
var lap1 = lap[j];
if(jam[i] < 10){
var jamFix = '0'+jam[i]+':00:00';
}else{
var jamFix = jam[i]+':00:00';
}
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
async:false,
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
var recursiveCall=true;
i=i+1;
if(i>=jam.length){
j=j+1;
if(j>=lap.length) recursiveCall= false;
else i=0;
}
if(recursiveCall===true)
{
ajaxCall();
}
},
error: function () {
$('#output').html('ERROR!');
},
});
}
ajaxCall();
return false;
}
I have written code for your understanding might be your have to made come modification in this code

Updating varibles and running functions using setTimeout

I'm trying to send a drone a new set of coordinates every 1/2 of a second. Right now, it's not working the way I planned on it working (aka it's not working at all). I have 90 different Lat, Long, and Alt coordinates all predetermined inside my .js file. They are listed like this-
setTimeout(function () {long_in=-74.61122515230907;lat_in=41.05861743700108;alt_in=10}, 5000);
setTimeout(function () {long_in=-74.61124258212661;lat_in=41.05864962647036;alt_in=10}, 10000);
setTimeout(function () {long_in=-74.61125021662482;lat_in=41.05867214783328;alt_in=10}, 15000);
and so on...
Then they will need to pass thru this function -
if (coordinate == "GPS") {
console.log("GPS go");
lat_out = lat_in;
long_out = long_in;
alt_out = alt_in;
console.log(lat_out, long_out, alt_out)
}
And finally it will send this command to the drone-
var msgdata = {};
msgdata["twist"] = {};
msgdata.twist["twist"] = {};
msgdata.twist.twist["linear"] = {};
msgdata.twist.twist.linear["x"] = lat_out;
msgdata.twist.twist.linear["y"] = long_out;
msgdata.twist.twist.linear["z"] = alt_out;
msgdata.twist.twist["angular"] = {};
msgdata.twist.twist.angular["z"] = 1.00;
msgdata["tolerance"] = 2.00;
msgdata["async"] = true;
msgdata["relative"] = false;
msgdata["yaw_valid"] = true;
msgdata["body_frame"] = false;
$.ajax({
type: "POST",
dataType: "json",
data: JSON.stringify(msgdata),
url: "http://" + ip + "/ros/" + namespace + "/navigation/position_set",
success: function (data) {
console.log(data, "Coordinates sent", lat_out,long_out,alt_out);
}
});
I have defined all of my variables prior to this code globally. All of the commands work perfectly fine, I just can't get them to all refresh every 1/2 of a second. Do I need to have all of these commands inside every setTimeout or something? Thanks for the help.
Yes you need to make the call again and again. You could wrap it in a function and make the call happen again and again from the setTimeout.
I have created a callback chain to guarantee order of execution based on #Liam's recommendation and the comments discussion.
setTimeout(function() {
long_in = -74.61122515230907;
lat_in = 41.05861743700108;
alt_in = 10;
prepSignal(long_in, lat_in, alt_in, function() {
setTimeout(function() {
long_in = -74.61124258212661;
lat_in = 41.05864962647036;
alt_in = 10;
prepSignal(long_in, lat_in, alt_in, function() {
setTimeout(function() {
long_in = -74.61125021662482;
lat_in = 41.05867214783328;
alt_in = 10;
prepSignal(long_in, lat_in, alt_in);
}, 5000);
});
}, 5000);
});
}, 5000);
var coordinate = "GPS";
function prepSignal(long_in, lat_in, alt_in, callback) {
if (coordinate == "GPS") {
console.log("GPS go");
lat_out = lat_in;
long_out = long_in;
alt_out = alt_in;
console.log(lat_out, long_out, alt_out, callback);
sendSignal(long_in, lat_in, alt_in, callback);
}
function sendSignal(long_in, lat_in, alt_in, cb) {
var msgdata = {};
msgdata["twist"] = {};
msgdata.twist["twist"] = {};
msgdata.twist.twist["linear"] = {};
msgdata.twist.twist.linear["x"] = lat_out;
msgdata.twist.twist.linear["y"] = long_out;
msgdata.twist.twist.linear["z"] = alt_out;
msgdata.twist.twist["angular"] = {};
msgdata.twist.twist.angular["z"] = 1.00;
msgdata["tolerance"] = 2.00;
msgdata["async"] = true;
msgdata["relative"] = false;
msgdata["yaw_valid"] = true;
msgdata["body_frame"] = false;
$.ajax({
type: "POST",
dataType: "json",
data: JSON.stringify(msgdata),
url: "http://" + ip + "/ros/" + namespace + "/navigation/position_set",
success: function(data) {
console.log(data, "Coordinates sent", lat_out, long_out, alt_out);
if(cb && typeof cb == "function") {
cb();
}
}
});
}
}
You have to run recalculation inside setTimeout after you set a value.

How to abort ajax request

In my below code if input search vale is empty and as well as search keyword is same means if entered 'abc' got the result again clicked need to abort the ajax request, I had written in beforesend method but browser throwing error "Cannot read property 'abort' of undefined"
Ajax code:
function makeRequest()
{
var searchText='';
var popupRequest = $.ajax({
url:"cnc/cncstorelocator",
type:'GET',
cache:false,
data: {searchCriteria : $('#cnc-searchcriteria').val()},
dataType: 'json',
beforeSend: function(){
if(searchText == '' && searchText == searchData) {
popupRequest.abort();
}
},
success : function(cncStoreLocatorData)
{
var store=null;
for (var i = 0; i < cncStoreLocatorData.length; i++) {
var loc = cncStoreLocatorData[i];
store = $('<div/>').addClass('pane');
var store_hours = loc.hrsOfOperation;
var str1 = $('<p/>').addClass('stores-timing');
var store_timings=null;
for (var j = 0; j < store_hours.length; j++) {
var storetime = store_hours[j];
store_timings = str1.append($('<span/>').html('<strong>' + storetime.days_short));
store_timings.appendTo(store);
}
$("#cncstorepane").append(store);
searchText=searchData;
}
},
error: function(cncStoreLocatorData) {
alert("can't make req");
}
});
}
var xhr = $.ajax({
type: "POST",
url: "XXX.php",
data: "name=marry&location=London",
success: function(msg){
alert( "The Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
var xhr = null;
function makeRequest()
{
if( xhr != null ) {
xhr.abort();
xhr = null;
}
var searchText='';
xhr = $.ajax({
url:"cnc/cncstorelocator",
type:'GET',
cache:false,
data: {searchCriteria : $('#cnc-searchcriteria').val()},
dataType: 'json',
beforeSend: function(){
if(searchText == '' && searchText == searchData) {
xhr.abort();
}
},
success : function(cncStoreLocatorData)
{
var store=null;
for (var i = 0; i < cncStoreLocatorData.length; i++) {
var loc = cncStoreLocatorData[i];
store = $('<div/>').addClass('pane');
var store_hours = loc.hrsOfOperation;
var str1 = $('<p/>').addClass('stores-timing');
var store_timings=null;
for (var j = 0; j < store_hours.length; j++) {
var storetime = store_hours[j];
store_timings = str1.append($('<span/>').html('<strong>' + storetime.days_short));
store_timings.appendTo(store);
}
$("#cncstorepane").append(store);
searchText=searchData;
}
},
error: function(cncStoreLocatorData) {
alert("can't make req");
}
});
Define a variable and give your ajax the same alias. Then, everytime the function is being made, you check if (in this example XHR) is null or not. If it is not, you abort() it and give it null value again.

javascript wait for several callback finished

I have a following javascript program:
function jQueryFunction(url, callback)
{
$.ajax
({
type: "GET",
async: true,
url: url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
return callback(json);
}
});
}
var jsonArray = new Array();
for(var i = 0; i < 10; i++)
{
jQueryFunction(url[i], function(json){
jsonArray[i] = json;
});
}
//process jsonArray
However, when I check jsonArray after the for loop, it is null. So my question is that how to store the return value from jQueryFunction to jsonArray in for loop and then process it?
I have tried $.when.apply($,jsonArray).done(function) but still the same, it is null.
A simple way:
function doTheAjax(url, callback) {
return $.ajax({
type: "GET",
async: true,
url: url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler"
});
};
var reqs = [];
for(var i = 0; i < 10; i++) {
reqs.push(doTheAjax(url[i]));
}
// send the array of requests to when, which will fire `done`
// when it's, well, done
$.when.apply($.when, reqs).done(function() {
$.each(arguments, function(data) {
// process the data
});
});
alternatively, make a bunch of requests and put them into jsonArray, but keep
track of how many you're making. When they all complete, you have the array. Create your
own deferred, resolve it yourself when the counter is up, and return the promise.
var getJSON = function(url) {
var dfd = $.Deferred();
var count = 0;
var total = 10;
var jsonArray = [];
for(var i = 0; i < total; i++) {
doTheAjax(url[i]).done(function(json) {
jsonArray.push(json);
count++;
if ( count >= total ) {
dfd.resolve(jsonArray);
}
});
}
return dfd.promise();
};
getJSON().done(function(theCreatedJsonArray) {
// do stuff
});
I'm not sure why the answer to your previous question (using deferreds) didn't work. But the cause of your problem is that you are checking the array before any of the ajax responses arrived. You also have a problem with i referencing the same value on all callbacks.
One simple workaround, if you know how many responses you're expecting:
var arr = [];
for(var i = 0; i < 10; i++){
jQueryFunction(url[i], function(json){
arr.push(json);
if(arr.length == 10) {
// All 10 responses arrived!
// DO STUFF FROM HERE
// e.g., call another function
console.log(arr);
}
});
}

Javascript Function Returns Undefined JSON Object (But It's Not Undefined!)

I am trying to return a JSON object from a function using the JSON jQuery plugin (http://code.google.com/p/jquery-json/) but after returning the object from the function, it becomes undefined.
$(document).ready(function() {
var $calendar = $('#calendar');
$calendar.weekCalendar({
...
data : function(start, end, callback) {
var datas = getEventData();
alert(datas); // Undefined???
}
});
If I inspect the object before returning it, it is defined.
function getEventData() {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
//alert(dataString);return false;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
alert($.toJSON(jsonArray)); // Defined!
return ($.toJSON(jsonArray));
} else {
}
}
});
}
Any idea what I'm missing here?
function getEventData() {
function local() {
console.log(42);
return 42;
}
local();
}
Your missing the fact that the outer function returns undefined. And that's why your answer is undefined.
Your also doing asynchronous programming wrong. You want to use callbacks. There are probably 100s of duplicate questions about this exact problem.
Your getEventData() function returns nothing.
You are returning the JSON object from a callback function that's called asynchronously. Your call to $.ajax doesn't return anything, it just begins a background XMLHttpRequest and then immediately returns. When the request completes, it will call the success function if the HTTP request was successful. The success function returns to code internal in $.ajax, not to your function which originally called $.ajax.
I resolved this by using callbacks since AJAX is, after all. Once the data is retrieved it is assigned to a global variable in the callback and the calendar is refreshed using the global variable (datas).
$(document).ready(function() {
// Declare variables
var $calendar = $('#calendar');
datas = "";
set = 0;
// Retrieves event data
var events = {
getEvents : function(callback) {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
//alert($.toJSON(jsonArray));
callback.call(this,jsonArray);
} else {
}
}
});
}
}
$calendar.weekCalendar({
data : function(start, end, callback) {
if(set == 1) {
callback(datas);
//alert(datas.events);
}
}
});
// Go get the event data
events.getEvents(function(evented) {
displayMessage("Retrieving the Lineup.");
datas = {
options : {},
events : evented
};
set = 1;
$calendar.weekCalendar("refresh");
});
});

Categories

Resources