I’m trying to write a script to sequentially pull data from printers that have a web interface. There are over 500 on a large local network, hence the reason I’d like to call out to the next one once the previous returns (successful or not). I’m having difficulties wrapping my head around callbacks …if that’s the best solution.
Here’s where I currently stand (be kind, this is my intro to jQuery/Javascript and this is a proof test). Also, is there a way to build an array from the resulting calls? The reason I’ve turned to Javascript is that I could not get PHP to behave with the execution times.
Oh, you’ll see ASYNC: true below only because I tried w/ false and it did not work (return anything).
function pingDevice(prnList) {
prnList = ["www.google.com", "amazon.com", "facebook.com", "as923f.com"];
document.getElementById("myDiv").innerHTML="please wait...";
$(prnList).each( function(index,printer) {
$.ajax({
type: "GET",
dataType: "html",
url: "pingTest.php?ping="+printer,
async: true,
success: function (data) {
$('#myDiv').append( $('<div class="prn"></div>').html(data) );
$prnResults[printer] = data;
},
error: function () {
$prnResults[printer] = data;
}
});
});
$('#myDiv').append( $('<div class="prn"></div>').$prnResults );
}
It looks like there are two things you want your code to do.
Unfortunately, the code you have does neither of these things. 🙁
$.eachis a way to iterate over an array-like thing, but it won’t wait until the request returns before moving on the next item in the list. The ajax requests happen asynchronously, which means you call them and move on to the next operation in your code. When they are done, they will call back either thesuccessorerrorfunctions, but this code will never block while requests are happening.If you want to fire off sequential requests, you can create some kind of helper function that lets you loop through an array, and only calls the function on the next item in the array when you know you are done with the first one. If you want to do some action when they are all finished, then you need one more function that calls back when all the items in the array are done being processed.
Here is a small example of how you can do asynchronous things in sequence.
To apply this pattern to your own code, you just define your own callback function that gets called on each item in the array, like this:
The key is that you are calling the
donefunction in thesuccessanderrorcallbacks. This signals to thedoAsyncStuffSequentiallyfunction that an async operation has finished, and it should either start the next one or call thefinalfunction if we are done or an error occurred.