Click here to Skip to main content
14,872,052 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Below is the Javascript for a page I am working as a demo of how to do AJAX style background tasks. The onchange event of a select control calls the AjaxRequest function.

If the code being executed at the address in the url variable returns a 500 status, it ends up executing the line after catch(err). I thought it would have executed the alert and not called AjaxResults at all. In Chrome with the console showing, it shows that the send results in a 500.

The code works great when there isn't an error. I need to know why the error handling isn't working.

What I have tried:

function removeOptions(selectbox)
   var i;
   for(i = selectbox.options.length - 1 ; i >= 0 ; i--) {

function AjaxResults(xhr, funct) {
   var xmldoc = xhr.responseXML;
   // process the returned data
   switch (funct) {
      case 1:
         try {
            ddlbProducts = document.getElementById("products");
            var products = xmldoc.getElementsByTagName("d_products_row");
            for (var i = 0; i < products.length; i++) {   
               var prodname  = xmldoc.getElementsByTagName('productname').item(i);
               var productid = xmldoc.getElementsByTagName('productid').item(i);
               var option = document.createElement("option");
               option.innerHTML = prodname;
               option.value = productid;
         catch(err) {
            document.documentElement.innerHTML = xhr.responseText;
         alert('Unsupported function: ' + funct);

function AjaxRequest(url, funct) {
   xhr = new XMLHttpRequest();

   xhr.onload = function () {
      if (xhr.status = 200) {
         AjaxResults(xhr, funct);
      } else {
         alert('Error: ' + xhr.statusText);
   };'GET', url, true);
Updated 30-Dec-19 13:25pm

Best thing to do would be to define some event-listeners for your xhr and attach them to your AJAX requests.

Mozilla has some good documentation on this, under the Monitoring Progress subheading:
Using XMLHttpRequest - Web APIs | MDN[^]
if (xhr.status = 200) {
This line always true... try == or === as fits...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900