I am trying to learn how to use AJAX to streamline an error-check process.
The webpage that will use this process asks a user to select a month and year from two separate drop-down (<select><option>) lists to view the newsletter published for that month-and-year. The YEARS list will include only and all years in which a newsletter was published, and the MONTHS list will include all twelve months. The error to be detected is the selection of a future month in the current year (e.g.: December 2018, selected in August of 2018).
Newsletters are uploaded to year-specific subdirectories and each issue is a PDF file named for the year and month of publication. For example, the April 2017 issue will saved as .../2017/2017-04.pdf. These year-directories are all subdirectories of the calling program's directory.
I had originally written a purely PHP error-checker, which works but it's inelegant and poses risk of trapping inexperienced users on a page they cannot use. I learned that AJAX could check for the existence of a URL without having to load a new webpage. The resource I found led me to develop the following code:
Code:
<script>
var xhrObj = false;
xhrObj = new XMLHttpRequest();
function postErrChk() {
// Establish some variables.
var monthVal = $("#postMonth").val();
var yearVal = $("#postYear").val();
// Check to see if the issue that has been uploaded.
var issueToCheck = "./" + yearVal + "/";
issueToCheck += yearVal + "-" + monthVal + ".pdf";
xhrObj.open("HEAD", issueToCheck);
alert("You've requested " + issueToCheck);
xhrObj.onreadystatechange = function() {
alert("The readyState is " + xhrObj.readyState);
if (xhrObj.readyState == 4) {
if (xhrObj.status == 200) {
alert("The file has been found!");
} else {
alert("The file cannot be found.");
} // Close the if-else-statement testing status==200.
} // Close the if-statement testing readyState==4.
} // Close the anonymous function responding to onreadystatechange
}
</script>
When I put this in the webpage that also holds the <input> fields for the user's month-and-year selection, it works up to the point of
Code:
alert("You've requested " + issueToCheck);
It accurately identifies the user's selection. However, none of the alerts following the
Quote:
xhrObj.onreadystatechange = function()
|
line pop up.
I have the impression that anonymous function() should reiterate until it reaches a (readyState == 4) condition, but this does not appear to be happening. In fact, it does not appear that the anonymous function() is firing at all.
I'm new to AJAX, and I've been trying everything I can think of to debug this, and I'm getting nowhere. Any clues?