Failure to receive a server response during the AJAX communication

I am facing an issue with my code that is making 3 requests to a server. The code successfully sends the request, but fails when receiving the response. I need help in skipping the first response and only getting the third one.

phone.open("POST", '/', true);
phone.setRequestHeader("Content-type", elmnt.getAttribute('ctype'));
phone.send(reqStr);

Below is the code responsible for handling the response:

phone = new ConstructorXMLHttpRequest();
onreadystatechange = function(){
        if(phone.readyState == 4){
        if(phone.status == 200){
        var val = phone.responseText;
        alert(phone.responseText)
        dataInsert(val);
        break;
        }else{
              alert("Problemas status:"+phone.status+" state:"+phone.readyState);
              break;
        }
            }

};

@Hemlock, here is the code snippet for the constructor function:

function ConstructorXMLHttpRequest()
{
      if(window.XMLHttpRequest) /*XMLHttpRequest(Browsers Mozilla, Safari and Opera). */
      {
        return new XMLHttpRequest(); 
      }
      else if(window.ActiveXObject) /*IE*/
      {
      /*There a several difference between versions of IE, so
       * if the kids of MS release a new please put in this Array.*/
      var versionesObj = new Array(
      'Msxml2.XMLHTTP.5.0',
      'Msxml2.XMLHTTP.4.0',
      'Msxml2.XMLHTTP.3.0',
      'Msxml2.XMLHTTP',
      'Microsoft.XMLHTTP');
        for (var i = 0; i < versionesObj.length; i++)
        {
          try
          {
          return new ActiveXObject(versionesObj[i]);
          }
          catch (errorControlado)
          {
          }
        }
      }
throw new Error("Couldn't make a XMLHttpRequest");
}

Answer №1

Many find humor in this situation because your case statement is rendered ineffective due to the fact that you are not actually intending to execute different actions based on the object's state. Instead, you only want to take action under a specific condition. Additionally, combining your case with an if statement is unnecessary and creates errors in syntax.

It seems like what you're aiming for is:

    if(phone.readyState == 4){
        var val = phone.responseText;
        alert(val);
        dataInsert(val);
    } else {
        alert("Issues with status:"+phone.status+" and state:"+phone.readyState);
    }

You might also benefit from exploring the use of a third-party library such as jQuery for your ajax requests.

http://api.jquery.com/jQuery.ajax/

$.ajax({
    url: 'getData.html',
    success: function(val) {
        alert(val);
        dataInsert(val);
    }
});

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

Improving conditional rendering in Mui <Cards> component by fixing state behavior

I have a situation where I want to display a Floating Action Button inside each Mui card when hovered over. However, I'm running into an issue with the hover state affecting all cards instead of just the one being interacted with. How can I ensure tha ...

Error encountered: `npm ERR! code E503`

While attempting to execute npm install on my project, which was cloned from my GitHub repository, I encountered the following error: npm ERR! code E503 npm ERR! 503 Maximum threads for service reached: fs-extra@https://registry.npmjs.org/fs-extra/-/fs-ex ...

Mapbox is capable of managing several GEOJSON files by utilizing the loadURL function

I am in the process of creating a map that is designed to load multiple layers from various sources based on a configuration file called config.json. Each layer should trigger a popup when clicked, but oddly enough, I am only able to see the popup for the ...

The back button fails to refresh the page on a website utilizing Ajax technology

Recently, I implemented AJAX on a client's website to introduce some smooth animations for page transitions. When navigating from the homepage of firedogcreative.com to the edit page, and then to one of the work pages, we see a history like this: fir ...

Omitted Script within a Node.js JavaScript Code Segment

My code snippet is: function write_to_orchestrate(data_to_write) { console.log('more testing'); db.put('musician', '1', '{"test":"test1"}') .then(function (result) { res.send(result); ...

Unable to retrieve scope variable within AJAX call

I am currently in the process of running a loop function that contains an AJAX request within it. However, I am facing difficulties with the success function on the AJAX not being able to access a counter variable outside of the loop function. var upda ...

load a page using ajax

Hello, I am trying to submit the page using the code below but I am unable to retrieve the post data in ajax.php. Can anyone please guide me on where I might be making a mistake? new Ajax(wgScriptPath + '/' + 'ajax.php', { ...

Easily conceal and reveal elements using Svelte in a straightforward manner

I'm looking for a straightforward method to hide and show an element using a button in Svelte. Can someone guide me on how to achieve this? Additionally, I'm curious if it's easier to accomplish this task with vanilla JavaScript. ...

Increase in JQuery .ajax timeout not effective

My website has a process where JavaScript sends a POST request to a PHP server using the .ajax() function. The PHP server then communicates with a third-party API to perform text analysis tasks. After submitting the job, the PHP server waits for a minute b ...

Is it possible to track unsuccessful email deliveries using MailApp?

In my Google Script program, I incorporate MailApp in the following manner: MailApp.sendEmail(AddressStringGlobal,EMailSubjectProperLanguageGlobal,"",{htmlBody: EMailBody}); The issue arises when I encounter a bad email address in my data set, causing my ...

Creating an animated background slide presentation

After creating a button group, I wanted the background of the previous or next button to move/slide to the selected one when the user clicks on it. I achieved this effect using pure CSS and simply adding or removing the 'active' class with jQuery ...

transfer the value of a method to a different component

In my Component called IncomeList, there is a method named sumValue. This method simply adds different numbers together to produce one value, for example 3+5 = 8. Similarly, in another Component named OutputList, the same logic is applied but with a method ...

Automated scrolling within a div when an li element overflows

Looking to implement automatic scrolling in a div. I have a list of elements within a fixed height div, and now I want the div to scroll automatically when I press the down key after highlighting the 3rd li element (i.e Compt0005). Can anyone help me solve ...

Automatic line breaks within a JavaScript code can be achieved by using

I need help formatting this text: hello everyone. My name is PETER. hahahah ahahah .... If I have a fixed width, how can I automatically line break the text to look like this: hello everyone. My name is PETER. hahahah ahahah ...

Tips for effectively transmitting and managing a JSON object within an ASP.NET MVC controller

I am currently working on a project using ASP.NET MVC 4 and I'm facing an issue with sending a JSON object to a controller that is supposed to accept it. Here is the snippet of javascript and jQuery code I am using: var jsonObject = { "PlantShip ...

What is the reason behind FieldSelect returning a string instead of an object like FieldCheckbox?

FieldSelect component from Sharetribe documents is giving me a string, while FieldCheckbox is returning a JSON object. In a specific scenario, I want FieldSelect to store a JSON object. How can I achieve this? Below is the code snippet for reference: I& ...

Duplicate user scrolling input within a specified div container

I am attempting to recreate a horizontal scrolling effect on a div element that mirrors the input scroll. When the user scrolls along the input, I want the div element to scroll in sync. The issue I am encountering is specific to Chrome, where the input b ...

The jQuery included does not function properly in production mode and results in an error stating that it is not a function

After placing the jquery.placeholder.js file in the assets/javascripts folder, I successfully applied the function in my coffeescript file and it worked perfectly. $(document).ready -> $('input, textarea').placeholder(); However, when swit ...

Tips for sending multiple variables using XMLHttpRequest

I want to pass two variables through an Ajax request to my ajax.php: var xhrRequest = new XMLHttpRequest(); xhrRequest.open ( "GET", "ajax.php", false ); xhrRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); x ...

Unable to retrieve JSON data from converting TXT using JavaScript, resulting in undefined output

After converting txt to JSON, I encountered an issue. const txt = JSON.stringify(`{ ErrorList: [{ 80: 'Prepared' }], Reference: [ { 'Rule Name': 'Missing 3', 'Rule ID': 1, 'Rule Des& ...