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

Node.js making an API request

I am encountering an issue with the following code snippet: const req = require("request"); const apiReq = req("http://example.com/car/items.json", (err, res, body) => { if (!err && res.statusCode === 200) { return JSON.parse(body); } } ...

What does the main attribute in npm stand for?

The command npm init generates a file called package.json. The contents typically look like this: { "name": "webpack-tut", "version": "1.0.0", "description": "", "main": "index.js", .... } I came across this information in the official documen ...

Having trouble with the parent folder functionality in JavaScript?

I am facing a challenge with my website's structure as I have an old setup that needs to be updated. http://localhost/enc/pdfs/ : This directory contains some html files that are uploaded via ajax to be displayed on a tabbed div using: var Tabs ...

Closing tag in jQuery

In my script, I am using a div tag within the jquery code. However, whenever the div tag appears in the jquery code, it automatically closes the script tag and breaks the jquery code. For example, consider the following code: <script>var b = 25;var ...

A guide on dynamically altering text upon hovering over an element using Vue.js

On my website, I have the following HTML code: <div class="greetings"> <img @mouseover="hover='A'" @mouseleave="hover=''" src="a.png" alt="A" /> <img @mouseover="hover='B'" @mouseleave="hover=''" ...

A guide on combining two parameters using jQuery in a link for CodeIgniter

I am attempting to pass two parameters through jQuery in the href attribute of an a link, which I will then use in CodeIgniter. Here is my current code: $("#user_comment_show").append("<li>"+...+'<a id="remove_link&qu ...

What is the best way to retrieve data from this array?

Some of the code I have extracted from serialized data appears to not be in an array format. When attempting to use a foreach loop, it results in an error. array ( 'last_submit' => '1', 'feeds_changed' => '1', ...

Harnessing the power of express middleware to seamlessly transfer res.local data to various routes

I am in the process of implementing a security check middleware that will be executed on the specific routes where I include it. Custom Middleware Implementation function SecurityCheckHelper(req, res, next){ apiKey = req.query.apiKey; security.securi ...

Webpack is failing to load the logo PNG image file

Is there a way to make the logo png file visible on the webpage? I have been encountering issues with loading the image while other elements like HTML, css, and fonts are loading properly when the web pack is started. List of Error Messages: Refused to a ...

Struggling to implement a Rock Paper Scissors game using HTML, CSS Bootstrap4, and JavaScript, specifically facing challenges in getting the function to select a new image

Recently, in my coding class, we were tasked with creating a program that would display images of dice and generate random numbers when the refresh button was clicked. To practice using querySelector and setAttribute, I decided to expand on the lesson by i ...

Selecting the checkbox will activate the POST endpoint

I am working on a nodejs/express app and looking for a way to update my database using a POST route when a checkbox is clicked. The challenge I am facing is that I want to avoid using a submit button or jQuery. I am currently using a Bootstrap4 checkbox ...

Unanticipated commitments fulfilled on the spot

While troubleshooting a setup for managing promise concurrency in handling CPU-intensive asynchronous tasks, I encountered perplexing behavior that has left me puzzled. To regulate the flow, my approach was to initially create an array of Promises and the ...

The response detail error code 2 indicates that the post method API body check has failed within the Agora REST API, resulting in

const Authorization = `Basic ${Buffer.from(`${config.CUSTOMERID}:${config.CUSTOMER_SECRET}`).toString("base64")}`; const acquire = await axios.post(`https://api.agora.io/v1/apps/${config.agoraAppId}/cloud_recording/acquire`,{ ...

Strange behavior observed with Nuxt Js asyncData method returning values

Currently, I am engaged in a project using nuxt js/vue js. The project requires me to interact with multiple REST APIs. To accomplish this task, I am utilizing the asyncData() function provided by nuxt js to make the API calls within the page component. i ...

Customize the border style for the span element

I attempted to use the code below in JavaScript/jQuery to adjust the border thickness. Unfortunately, it seems to be ineffective. Can someone please assist me? //$("span").css({"border":"4px solid green"}); document.getElementById("192.168.42.151:8984_ ...

Unable to trigger onClick event

The button I have with the id "jump-button" is not functioning at all. When clicked, nothing happens. I have added an alert(); to the onclick attribute to test if the button is working. However, the other two buttons (next and prev) are working perfectly ...

Mapping Services API for Postal Code Borders by Google

After hitting a dead end with Google Maps Marker, I am seeking help to replicate the functionality for users on my website. Specifically, I want to take a user's postal code and outline their boundaries using Google Maps API. If anyone has knowledge o ...

Enhancing image clips using jQuery techniques

Could someone help me figure out why the image clip value isn't changing when I move the range slider in the code below? $('#myRange').on('input', function() { var nn = $(this).val(); $("img").css({ 'clip': ...

Improvement in Select2 Change Event: Update the subsequent select2 box options based on the value change in the preceding select2 box

I need assistance with two select boxes, namely Category and Sub-category. My objective is to dynamically alter the available options in the subcategory box based upon the value selected in the category box. Additionally, I would like to load data for the ...

A Guide to Listing Private JavaScript Class Properties

What is the best approach to iterate through private class fields? class Person { #isFoo = true; #isBar = false; constructor(first, last) { this.firstName = first; this.lastName = last; } enumerateSelf() { console.log(this); ...