Code for ajax request completed function

I am facing an issue with the following code:

function loadRegions()
{
    var xmlhttp;

    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
         xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
         xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
           alert("Ready:"+xmlhttp.status);
           xmlDoc=xmlhttp.responseXML;
           x=xmlDoc.getElementsByTagName("region");
           alert(x[0]);
           alert(x[1]);
       }
   }

   var ctrcode = frm.elements['countrycode'];
   xmlhttp.open("GET","http://mydomain.gr/regionslist.php?countrycode="+ctrcode.value,true);
   xmlhttp.send();
}

In my HTML, I have a select element that triggers this function to retrieve regions based on the country selected. Despite seeing the request being made in the console, I do not receive any response. The onreadystatechange function never gets called. However, when I remove xmlhttp.status==200, the function is invoked but the xmlDoc object remains as null and xmlhttp.status==0. Interestingly, the URL used works fine when accessed independently. Can someone explain why my onreadystatechange function fails to work and does not return a status of 200?

Answer №1

Make sure to include this line of code before using the send() function:

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Additionally, remember to set the onReadyStateChange function after calling open()

Here are a couple of reasons why this is important:
1) The responseXML property is only populated with XML data when the server response is fully received and the Content-Type header indicates it is XML. If not, responseXML will be null.
2) After the initial response, all event listeners will be removed. It's crucial to call open() before adding an onreadystatechange listener.
For further information, check out the reference links provided for the first and the second reason.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guidelines on populating a Vue array with data fetched from an Axios request

The v-breadcrumbs component is used to display data from the breadcrumbs array, which works seamlessly with static data. <v-row> <!-- Breadcrumbs --> <v-col class="d-flex"> <v-breadcrumbs :items="breadcrumbs"></v ...

What are the steps to kick off my React App once I've cloned it?

Currently grappling with deploying my app using Netlify, I encountered an issue after cloning the app onto my new computer. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8afee5eee5e6e3f9fefcb8cabba4baa4ba">[email  ...

Why is my React app opening in Google Chrome instead of the API?

I have a link in my React app that is supposed to open a PDF in another page, but for some reason Google Chrome is redirecting me to the React application instead of opening the API endpoint that renders the PDF. The URL for the PDF is /api/file/:_id and m ...

"JIRA post functionality not functioning correctly on Internet Explorer and Firefox due to jQuery compatibility

I am facing an issue while trying to submit data to JIRA. It seems to be working fine in Chrome but not in IE/FF. I suspect there is something wrong with the ajax call setup, but I'm not entirely sure what needs to be done to fix it. $(&apos ...

A step-by-step guide on utilizing the v-for index loop to showcase a nested JSON array

My JSON Array has the following structure: items: [ { ID: 11, UserID: "test.com", UserRole: "user", timeStamp: "2021-03-23T15:54:02.125578", dialogs: [ { "Bot" ...

Properly accessing values in a set object: a practical guide

Within my ng-controller, I am currently utilizing a small snippet of code that looks something like this: <select ng-model="character" ng-options="ch.name for ch in characters"></select> {{character}} <-- Works well, even {{character.attr} ...

Guide to extracting a key from a specific index within JSON using Google Apps Script

Is there a way to extract values key11-key44? Just managed to retrieve values key1-key4: const data = JSON.parse(UrlFetchApp.fetch(url, options); const keys = Object.keys(data.paths); for (let a in keys) {return keys[a]} { "id": &q ...

What causes jquery-ui resizable to set the width of the div with the "alsoResize" property?

I have created a series of divs structured like this: <div id="body_container"> <div id="top_body"> </div> <div id="bottom_body"> </div> </div> Additionally, I have implemented the following funct ...

When Typescript compiles to JavaScript, it may result in code that appears to be a function

In the following typescript code snippet: export enum UID { FACTORY, ROBOT } we see how it compiles to javascript: (function (UID) { UID._map = []; UID._map[0] = "FACTORY"; UID.FACTORY = 0; UID._map[1] = "ROBOT" ...

Utilize AJAX to send a file within an HTTP request

In my attempt to send a form using an Ajax request, I encountered a challenge with uploading files. Here is a snippet of my form: <form> {{csrf_field()}} <div class="form-group"> <label for="company-name">Co ...

Using the attribute data-ng-repeat along with the <option> tag allows for dynamic iteration and

Hello there, I am a beginner with AngularJS and I am struggling to understand how to create my <option> list. I would like my output to resemble the example in this fiddle: http://jsfiddle.net/XdpJv/ This is what my current code looks like: <se ...

What is the proper way to write an xpath expression in Selenium with C# to retrieve a date from a text node?

<dd> ::before <strong>Test Date:</strong> " 7/6/20 - Monday" ::after </dd> Here is a sample snippet of HTML code. I am looking to find the date that comes after the text "Test Date:". As there are multiple dates on the p ...

When attempting to submit an input, a 404 error is thrown in MVC due to the

I have deployed an MVC application to the server directory '/iapps/ebiz'. The application functions flawlessly on localhost. The @Ajax.Action link is operational for the 'Get' operation, however, it cannot find the Post method for the c ...

Call getElementById upon the successful completion of an AJAX request

In the process of constructing a mini quiz, I am utilizing a variable quizScore to store the score. Each question in the quiz is displayed using AJAX. An individual AJAX call captures the ID of the button pressed (for example, on question 2, the button ID ...

Update the background color when a selectable option is chosen and not disabled

I am searching for a solution to modify the color of a select box if one of the disabled options is not chosen. Here is an example of the dropdown: <select class="selectoption" name="desc[]"> <option disabled="disabled" selected="sel ...

Updating dependencies of dependencies in npm: A step-by-step guide

I'm puzzled by the fact that I can't seem to find a solution to this seemingly easy question. It's surprising that even running npm update doesn't resolve the issue. While I can't post my entire dependency tree here, I'll do ...

Creating a 3D trajectory around the Earth using a Two-Line Element Set (TLE)

I am currently working on a project to develop a 3D scene in JS/React that will visualize the orbit of the ISS around Earth. I have forked a repository from https://github.com/dsuarezv/satellite-tracker. However, I have observed that the current implement ...

AJAX method denied due to server restrictions

Pathway Route::put('path/update',['as'=>'test.update', 'uses'=>'TestController@update']); Ajax Request $.ajax({ url: 'path/update', type: 'PUT', dataType: 'json& ...

Press the button located within the canvas element

How can I click on the verify button embedded inside a canvas element using either jQuery or Selenium? https://i.sstatic.net/F2CAY.png Please advise me on how to successfully click inside the canvas. ...

Escape sequences do not seem to be functioning properly when using innerHTML

I am facing an issue where a string containing HTML escape characters (such as < and >) needs to be rendered inside a div using innerHTML. The intention is for the escaped characters to appear as text rather than as actual HTML, but they still render ...