How to check URLs in Ajax then fire an event - javascript

I am working on one urlChecker tool where I need to check multiple URLs. If all URLs are UP then image should change to green ,if any of the url is down image should change to red. Below is my code ,don't know what's going wrong in it. It checks all URLs ,but its failed to show red image if any of URL is down.
<html>
<head>
<script src="jquery-3.2.1.js"></script>
<script>
var urlArray = Array();
urlArray[0] = 'http://google.com';
urlArray[1] = 'm';
urlArray[2] = 'http://apple.com';
$(function() {
for (var i = 0; i < urlArray.length; i++) {
urlcheck(i);
}
})
function urlcheck(i) {
var url1 = urlArray[i];
$(document).ready(function() {
var urlExists = function(url, callback) {
$.ajax({
type: 'HEAD',
url: url,
success: function() {
callback(true);
},
error: function() {
callback(false);
}
});
}
urlExists(url1, function(success) {
if (success) {
//alert('Success!');
$("#theImg").attr("src", "images/green.png")
} else {
//alert('Down!');
$("#theImg").attr("src", "images/red.png")
}
});
});
}
</script>
</head>
<body>
<form name=form01>
<td style="height: 60px;; width: 75px"><IMG
ID="theImg" border="0" src="images/wait.png" width="40"
height="40"></IMG></td>
</form>
</body>
</html>
Thanks.

Hi please try this out
$(function () {
var urlArray = Array();
urlArray[0] = 'http://google.com';
urlArray[1] = 'http://m';
urlArray[2] = 'http://apple.com';
var url_flag = 0;
$(function () {
for (var i = 0; i < urlArray.length; i++) {
urlcheck(i);
}
})
function urlcheck(i) {
var url1 = urlArray[i];
$(document).ready(function () {
//Set the green image as default
$("#theImg").attr("src", "images/green.png")
var urlExists = function (url, callback) {
$.ajax({
type: 'HEAD', url: url, success: function () {
callback(true);
},
error: function () {
callback(false);
}
});
}
urlExists(url1, function (success) {
if (!success) {
url_flag = 1;
setImage(url_flag);
}
});
});
}
function setImage(url_flag){
if (url_flag == 1) {
$("#theImg").attr("src", "http://s1.thingpic.com/images/2T/1SL9eAWko9U1ZhnPvMvAzvw2.png")
}
}
});

Should be ok :
var urlArray = Array();
urlArray[0] = 'http://google.com';
urlArray[1] = 'm';
urlArray[2] = 'http://apple.com';
function handler(status){
var img = '';
if(!!status){
img = "images/green.png";
}else{
img = "images/red.png";
}
$("#theImg").attr("src",img);
}
function checkUrls (arr) {
var len = arr.length;
urlArray.map(function (url) {
ping(url)
.done(function(){
if(--len === 0) handler(true);
})
.fail(function(){
handler(false);
})
})
}
function ping (url) {
return $.ajax({
type: "HEAD",
url: url,
cache:false
})
}
checkUrls(urlArray);

Related

html table no longer supported

As others before I used yql to get data from a website. The website is in xml format.
I am doing this to build a web data connector in Tableau to connect to xmldata and I got my code from here: https://github.com/tableau/webdataconnector/blob/v1.1.0/Examples/xmlConnector.html
As recommended on here: YQL: html table is no longer supported I tried htmlstring and added the reference to the community environment.
// try to use yql as a proxy
function _yqlProxyAjaxRequest2(url, successCallback){
var yqlQueryBase = "http://query.yahooapis.com/v1/public/yql?q=";
var query = "select * from htmlstring where url='" + url + "'";
var restOfQueryString = "&format=xml" ;
var yqlUrl = yqlQueryBase + encodeURIComponent(query) + restOfQueryString + "&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
_ajaxRequestHelper(url, successCallback, yqlUrl, _giveUpOnUrl9);
}
function _giveUpOnUrl9(url, successCallback) {
tableau.abortWithError("Could not load url: " + url);
}
However, I still got the message: Html table no longer supported.
As I don't know much about yql, I tried to work with xmlHttpRequestinstead, but Tableau ended up processing the request for ages and nothing happened.
Here my attempt to find another solution and avoid the yql thingy:
function _retrieveXmlData(retrieveDataCallback) {
if (!window.cachedTableData) {
var conData = JSON.parse(tableau.connectionData);
var xmlString = conData.xmlString;
if (conData.xmlUrl) {
var successCallback = function(data) {
window.cachedTableData = _xmlToTable(data);
retrieveDataCallback(window.cachedTableData);
};
//INSTEAD OF THIS:
//_basicAjaxRequest1(conData.xmlUrl, successCallback);
//USE NOT YQL BUT XMLHTTPREQUEST:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open('GET', 'https://www.w3schools.com/xml/cd_catalog.xml', true);
xhttp.send();
return;
}
try {
var xmlDoc = $.parseXML(conData.xmlString);
window.cachedTableData = _xmlToTable(xmlDoc);
}
catch (e) {
tableau.abortWithError("unable to parse xml data");
return;
}
}
retrieveDataCallback(window.cachedTableData);
}
Does anyone have an idea how to get YQL work or comment on my approach trying to avoid it?
Thank you very much!
For reference, if there is any Tableau user that wants to test it on Tableau, here is my full code:
<html>
<head>
<title>XML Connector</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script src="https://connectors.tableau.com/libs/tableauwdc-1.1.1.js" type="text/javascript"></script>
<script type="text/javascript">
(function() {
var myConnector = tableau.makeConnector();
myConnector.init = function () {
tableau.connectionName = 'XML data';
tableau.initCallback();
};
myConnector.getColumnHeaders = function() {
_retrieveXmlData(function (tableData) {
var headers = tableData.headers;
var fieldNames = [];
var fieldTypes = [];
for (var fieldName in headers) {
if (headers.hasOwnProperty(fieldName)) {
fieldNames.push(fieldName);
fieldTypes.push(headers[fieldName]);
}
}
tableau.headersCallback(fieldNames, fieldTypes); // tell tableau about the fields and their types
});
}
myConnector.getTableData = function (lastRecordToken) {
_retrieveXmlData(function (tableData) {
var rowData = tableData.rowData;
tableau.dataCallback(rowData, rowData.length.toString(), false);
});
};
tableau.registerConnector(myConnector);
})();
function _retrieveXmlData(retrieveDataCallback) {
if (!window.cachedTableData) {
var conData = JSON.parse(tableau.connectionData);
var xmlString = conData.xmlString;
if (conData.xmlUrl) {
var successCallback = function(data) {
window.cachedTableData = _xmlToTable(data);
retrieveDataCallback(window.cachedTableData);
};
//_basicAjaxRequest1(conData.xmlUrl, successCallback);
//here try another approach not using yql but xmlHttpRequest?
//try xml dom to get url (xml http request)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open('GET', 'https://www.w3schools.com/xml/cd_catalog.xml', true);
xhttp.send();
return;
}
try {
var xmlDoc = $.parseXML(conData.xmlString);
window.cachedTableData = _xmlToTable(xmlDoc);
}
catch (e) {
tableau.abortWithError("unable to parse xml data");
return;
}
}
retrieveDataCallback(window.cachedTableData);
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
window.cachedTableData = _xmlToTable(xmlDoc);
}
// There are a lot of ways to handle URLS. Sometimes we'll need workarounds for CORS. These
// methods chain together a series of attempts to get the data at the given url
function _ajaxRequestHelper(url, successCallback, conUrl, nextFunction,
specialSuccessCallback){
specialSuccessCallback = specialSuccessCallback || successCallback;
var xhr = $.ajax({
url: conUrl,
dataType: 'xml',
success: specialSuccessCallback,
error: function()
{
nextFunction(url, successCallback);
}
});
}
// try the straightforward request
function _basicAjaxRequest1(url, successCallback){
_ajaxRequestHelper(url, successCallback, url, _yqlProxyAjaxRequest2);
}
// try to use yql as a proxy
function _yqlProxyAjaxRequest2(url, successCallback){
var yqlQueryBase = "http://query.yahooapis.com/v1/public/yql?q=";
var query = "select * from htmlstring where url='" + url + "'";
var restOfQueryString = "&format=xml" ;
var yqlUrl = yqlQueryBase + encodeURIComponent(query) + restOfQueryString + "&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
_ajaxRequestHelper(url, successCallback, yqlUrl, _giveUpOnUrl9);
}
function _giveUpOnUrl9(url, successCallback) {
tableau.abortWithError("Could not load url: " + url);
}
// Takes a hierarchical xml document and tries to turn it into a table
// Returns an object with headers and the row level data
function _xmlToTable(xmlDocument) {
var rowData = _flattenData(xmlDocument);
var headers = _extractHeaders(rowData);
return {"headers":headers, "rowData":rowData};
}
// Given an object:
// - finds the longest array in the xml
// - flattens each element in that array so it is a single element with many properties
// If there is no array that is a descendent of the original object, this wraps
function _flattenData(xmlDocument) {
// first find the longest array
var longestArray = _findLongestArray(xmlDocument, xmlDocument);
if (!longestArray || longestArray.length == 0) {
// if no array found, just wrap the entire object blob in an array
longestArray = [objectBlob];
}
toRet = [];
for (var ii = 0; ii < longestArray.childNodes.length; ++ii) {
toRet[ii] = _flattenObject(longestArray.childNodes[ii]);
}
return toRet;
}
// Given an element with hierarchical properties, flattens it so all the properties
// sit on the base element.
function _flattenObject(xmlElt) {
var toRet = {};
if (xmlElt.attributes) {
for (var attributeNum = 0; attributeNum < xmlElt.attributes.length; ++attributeNum) {
var attribute = xmlElt.attributes[attributeNum];
toRet[attribute.nodeName] = attribute.nodeValue;
}
}
var children = xmlElt.childNodes;
if (!children || !children.length) {
if (xmlElt.textContent) {
toRet.text = xmlElt.textContent.trim();
}
} else {
for (var childNum = 0; childNum < children.length; ++childNum) {
var child = xmlElt.childNodes[childNum];
var childName = child.nodeName;
var subObj = _flattenObject(child);
for (var k in subObj) {
if (subObj.hasOwnProperty(k)) {
toRet[childName + '_' + k] = subObj[k];
}
}
}
}
return toRet;
}
// Finds the longest array that is a descendent of the given object
function _findLongestArray(xmlElement, bestSoFar) {
var children = xmlElement.childNodes;
if (children && children.length) {
if (children.length > bestSoFar.childNodes.length) {
bestSoFar = xmlElement;
}
for (var childNum in children) {
var subBest = _findLongestArray(children[childNum], bestSoFar);
if (subBest.childNodes.length > bestSoFar.childNodes.length) {
bestSoFar = subBest;
}
}
}
return bestSoFar;
}
// Given an array of js objects, returns a map from data column name to data type
function _extractHeaders(rowData) {
var toRet = {};
for (var row = 0; row < rowData.length; ++row) {
var rowLine = rowData[row];
for (var key in rowLine) {
if (rowLine.hasOwnProperty(key)) {
if (!(key in toRet)) {
toRet[key] = _determineType(rowLine[key]);
}
}
}
}
return toRet;
}
// Given a primitive, tries to make a guess at the data type of the input
function _determineType(primitive) {
// possible types: 'float', 'date', 'datetime', 'bool', 'string', 'int'
if (parseInt(primitive) == primitive) return 'int';
if (parseFloat(primitive) == primitive) return 'float';
if (isFinite(new Date(primitive).getTime())) return 'datetime';
return 'string';
}
function _submitXMLToTableau(xmlString, xmlUrl) {
var conData = {"xmlString" : xmlString, "xmlUrl": xmlUrl};
tableau.connectionData = JSON.stringify(conData);
tableau.submit();
}
function _buildConnectionUrl(url) {
// var yqlQueryBase = "http://query.yahooapis.com/v1/public/yql?q=";
// var query = "select * from html where url='" + url + "'";
// var restOfQueryString = "&format=xml";
// var yqlUrl = yqlQueryBase + encodeURIComponent(query) + restOfQueryString;
// return yqlUrl;
return url;
}
$(document).ready(function(){
var cancel = function (e) {
e.stopPropagation();
e.preventDefault();
}
$("#inputForm").submit(function(e) { // This event fires when a button is clicked
// Since we use a form for input, make sure to stop the default form behavior
cancel(e);
var xmlString = $('textarea[name=xmlText]')[0].value.trim();
var xmlUrl = $('input[name=xmlUrl]')[0].value.trim();
_submitXMLToTableau(xmlString, xmlUrl);
});
var ddHandler = $("#dragandrophandler");
ddHandler.on('dragenter', function (e)
{
cancel(e);
$(this).css('border', '2px solid #0B85A1');
}).on('dragover', cancel)
.on('drop', function (e)
{
$(this).css('border', '2px dashed #0B85A1');
e.preventDefault();
var files = e.originalEvent.dataTransfer.files;
var file = files[0];
var reader = new FileReader();
reader.onload = function(e) { _submitXMLToTableau(reader.result); };
reader.readAsText(file);
});
$(document).on('dragenter', cancel)
.on('drop', cancel)
.on('dragover', function (e)
{
cancel(e);
ddHandler.css('border', '2px dashed #0B85A1');
});
});
</script>
<style>
#dragandrophandler {
border:1px dashed #999;
width:300px;
color:#333;
text-align:left;vertical-align:middle;
padding:10px 10px 10 10px;
margin:10px;
font-size:150%;
}
</style>
</head>
<body>
<form id="inputForm" action="">
Enter a URL for XML data:
<input type="text" name="xmlUrl" size="50" />
<br>
<div id="dragandrophandler">Or Drag & Drop Files Here</div>
<br>
Or paste XML data below
<br>
<textarea name="xmlText" rows="10" cols="70"/></textarea>
<input type="submit" value="Submit">
</form>

ajax url directs me to .php?userid=undefined

When I click on the button, it redirects me to removeadmin.php?userid=undefined . My intended result was eg removeadmin.php?userid=0001 depending on which button the person has pressed. I have tried to change to window.location = "removeadmin.php?userid=" + arr[i].userid However, nothing seems to work.
(function () {
$(document).ready(function () {
showadmin();
});
function showadmin() {
var url = serverURL() + "/showadmin.php";
var userid = "userid";
var employeename = "employeename";
var role ="role";
var JSONObject = {
"userid": userid,
"employeename": employeename,
"role": role
};
var myJSON = JSON.stringify(JSONObject);
$.ajax({
url: url,
type: 'POST',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getAdminResult(arr);
},
error: function () {
alert("fail");
}
});
}
function _getAdminResult(arr) {
var gridcontainers = [];
for (var i = 0; i < arr.length; i++) {
var gridcontainer = $("<div />").addClass("grid-container");
gridcontainer.append($("<div />").text(arr[i].userid));
gridcontainer.append($("<div />").text(arr[i].employeename));
gridcontainer.append($("<div />").text(arr[i].role));
gridcontainer.append($("<div />").append(
$("<button />")
.on("click", BtnRemoveAdmin)
.text("Remove")
));
gridcontainers.push(gridcontainer);
}
$("#name").append(gridcontainers);
}
function BtnRemoveAdmin(event) {
var data = event.data;
removeadmin(event.data);
}
function removeadmin(userid) {
window.location = "removeadmin.php?userid=" + userid;
}
})();
simply event.data is undefined. Change _getAdminResult and BtnRemoveAdmin functions with this
function _getAdminResult(arr) {
var gridcontainers = [];
for (var i = 0; i < arr.length; i++) {
var gridcontainer = $("<div />").addClass("grid-container");
gridcontainer.append($("<div />").text(arr[i].userid));
gridcontainer.append($("<div />").text(arr[i].employeename));
gridcontainer.append($("<div />").text(arr[i].role));
gridcontainer.append($("<div />").append(
$("<button />")
.on("click", BtnRemoveAdmin)
.attr("data-userid", arr[i].userid)
.text("Remove")
));
gridcontainers.push(gridcontainer);
}
$("#name").append(gridcontainers);
}
function BtnRemoveAdmin() {
var data = $(this).attr("data-userid");
removeadmin(data);
}

jQuery bind not working on click

I have a strange problem, from the ones below only the first one works, i need to mention that both of them are in jQuery(document).ready(function(){});
There are no errors in the console.
This one works
jQuery('.delete_product_line').click(function(){
console.log('xxxxx2');
});
This one doesn't work
jQuery('body').on('click', '.delete_product_line', function(){ console.log('ccccc');});
This is the full example, i know it does not make any sense, also the #submitAddProduct works as it should.
jQuery(document).ready(function(){
jQuery('body').on('click', '#submitAddProduct', function(){
var interval;
var product_id = jQuery('#add_product_product_id').val();
var price_tax_excl = jQuery('#add_product_product_price_tax_excl').val();
var price_tax_incl = jQuery('#add_product_product_price_tax_incl').val();
var qty = jQuery('#add_product_product_quantity').val();
var id_combination = 0;
var initial_rows = jQuery('#orderProducts tbody tr').length;
var i = 0;
var rows = 0;
console.log(initial_rows);
if(jQuery('#add_product_product_attribute_id').length > 0)
id_combination = jQuery('#add_product_product_attribute_id').val();
interval = setInterval(function(){
if(i >= 5000)
{
clearInterval(interval);
interval = 0;
}
else
{
rows = jQuery('#orderProducts tbody tr').length;
if(rows > initial_rows)
{
i = 10000;
var response_z = $.ajax({ type: "POST",
url: aem_ajax,
cache: false,
data: { action: 'add_product_to_order', id_product: product_id, price_tax_excl: price_tax_excl, price_tax_incl:price_tax_incl, qty:qty, id_combination: id_combination, id_order: aem_id_order, id_employee: aem_id_employee, token: aem_token },
async: true,
success: function(data) {
}
}).responseText;
}
}
i = i + 100;
}, 100);
return false;
});
jQuery('.delete_product_line').click(function(){
console.log('xxxxx2');
});
jQuery(document).on('click', '.delete_product_line', function(){
console.log('xxxxx');
var parent = jQuery(this).closest('tr');
var id_order_detail = parent.find('.edit_product_id_order_detail').val();
var price_tax_excl = parent.find('.edit_product_price_tax_excl').val();
var price_tax_incl = parent.find('.edit_product_price_tax_incl').val();
var qty = parent.find('.edit_product_quantity').val();
var id_combination = 0;
var link = 'https://mytestsite.com/'+parent.find('a:eq(0)').attr('href');
var url = new URL(link);
var id_product = url.searchParams.get("id_product");
var response_z = $.ajax({ type: "POST",
url: aem_ajax,
cache: false,
data: { action: 'remove_product_from_order', id_order_detail: id_order_detail, id_order: aem_id_order, id_product: id_product, id_employee: aem_id_employee,qty: qty, price_tax_excl:price_tax_excl, price_tax_incl:price_tax_incl, token: aem_token },
async: true,
success: function(data) {
}
}).responseText;
return false;
});
});
Use document instead of 'body' in this case.
jQuery(document).ready(function() {
jQuery(document).on('click', '.delete_product_line', function(){
console.log('ccccc');
});
})

jQuery Promise each loop

I am creating a UserScript that will generate a list of URLs to a users photo gallery. A user gallery may have multiple pages, each page has multiple thumbnails that have a link to a page which contains the full-sized image url.
I am using jQuery to request the pages though I'm not getting the desired results when a user gallery only contains 1 page. I get some results when a user gallery contains multiple pages but I only get 1 page worth of results.
var userID = 0;
function getUserID() {
var query = window.location.search;
var regex = /UserID=(\d+)/;
var regexResult = query.match(regex);
if (regexResult !== null) {
return regexResult[0].replace('UserID=', '');
} else {
return 0;
}
}
function getGallery(userID) {
function getGalleryPage(userID, page, gallery) {
var data = {};
if(page > 0) {
data = { btnNext: ">", PageNo: page };
}
var url = 'http://www.domain.com/' + userID;
return $.ajax({
method: 'POST',
url: url,
data: data,
dataType: 'html'
}).then(function(result){
$result = $(result);
$result.find('form[name="frmGallery"]').find('img').each(function() {
var url = ''
// Do stuff to get url
getGalleryImage(url).done(function(imageLink) {
gallery.push(imageLink);
});
});
$btnNext = $result.find('input[name="btnNext"]');
if($btnNext.length > 0) {
page += 1;
return getGalleryPage(userID, page, gallery);
} else {
return(gallery);
}
});
}
return getGalleryPage(userID, 0, []);
}
function getGalleryImage(url) {
return $.ajax({
method: 'GET',
url: url,
dataType: 'html'
}).then(function(result){
var imageUrl = '';
// Do stuff to get full sized image url
return imageUrl;
});
}
jQuery(document).ready(function($) {
userID = getUserID();
if(userID === 0)
return;
getGallery(userID).done(function(gallery) {
$.each(gallery, function(index, value) {
console.log(value);
});
});
});
I think this part of my script is not correct:
$result.find('form[name="frmGallery"]').find('img').each(function() {
var url = ''
// Do stuff to get url
getGalleryImage(url).done(function(imageLink) {
gallery.push(imageLink);
});
});
As written, there's no attempt to aggregate the inner promises returned by getGalleryImage().
You need to map the delivered img elements to an array of promises and aggregate them with jQuery.when().
I would write it something like this :
jQuery(function($) {
var userID;
function getUserID() {
var query = window.location.search;
var regex = /UserID=(\d+)/;
var regexResult = query.match(regex);
if (regexResult !== null) {
return regexResult[0].replace('UserID=', '');
} else {
return 0;
}
}
function getGallery(userID) {
var gallery = [];
var page = 0;
var url = 'http://www.domain.com/' + userID;
function getGalleryPage() {
var data = (page > 0) ? { btnNext: ">", PageNo: page } : {};
return $.ajax({
method: 'POST',
url: url,
data: data,
dataType: 'html'
}).then(function(result) {
$result = $(result);
//map jQuery collection of img elements to Array of promises
var promises = $result.find('form[name="frmGallery"]').find('img').map(function(imgElement, i) {
var url = ''
// Do stuff to get url
return getGalleryImage(url);
}).get();// .get() is necessary to unwrap jQuery and return Array
//aggregate promises
return $.when.apply(null, promises).then(function() {
//accumulate results
gallery = gallery.concat(Array.prototype.slice.call(arguments));
// recurse/terminate
if($result.find('input[name="btnNext"]').length > 0) {
page += 1;
return getGalleryPage();
} else {
return gallery;
}
});
});
}
return getGalleryPage();
}
function getGalleryImage(url) {
return $.ajax({
method: 'GET',
url: url,
dataType: 'html'
}).then(function(result) {
var imageUrl = '';
// Do stuff to get full sized image url
return imageUrl;
});
}
userID = getUserID();
if(userID !== 0) {
getGallery(userID).then(function(gallery) {
$.each(gallery, function(index, value) {
console.log(value);
});
});
}
});
You should also impose a limit on the number of recursions, just in case one day some userID yields thousands of pages.

Loop through XML files jQuery

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()
}
}
});
}

Categories

Resources