The XMLHttpRequest() function throws NS_ERROR_FAILURE when sending requests to localhost using either an absolute or relative path

Encountering an error in Firefox 31 ESR:

Error: NS_ERROR_FAILURE:

Source file:

http://localhost/Example/scripts/index.js Line: 18

Similar issue observed on Internet Explorer 11:

SCRIPT5022: InvalidStateError

The script used for AJAX function call is as follows:

ajax('post','standard/','part='+p+'&price='+q,'sequel_sub_object_key');

Below is the code snippet for the AJAX function:

function ajax(method,url,param_id_container_pos,id_container,id_focus,sequel)
{
 var methods = Array('get','head','post');

 if (window.XMLHttpRequest && in_array(method,methods))
 {
  xhr = new XMLHttpRequest();
  xhr.open(method,url,true);//Error triggers here for localhost.

  if (method=='post')
  {
   xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
   xhr.send(param_id_container_pos);
  }

  xhr.send(null);

  xhr.onreadystatechange = function()
  {console.log('xhr.readyState = '+xhr.readyState);
   if (xhr.readyState=='4')
   {
    alert('xhr.responseText = '+xhr.responseText);
   }
  }
 }

Seems like Firefox and IE suspect cross-site scripting issues even with localhost involved?

Tried both absolute and relative paths for the URL :

  1. document.getElementsByTagName('base')[0].href+'standard/'

  2. window.location.href

  3. 'standard'

After going through several pages including Stack, no solution seems to fit.

  1. No intention of implementing cross-site scripting.

  2. Not altering the method.

  3. Solely using HTTP, not HTTPS.

  4. No involvement of subdomains.

  5. Avoiding frameworks entirely.

  6. Just need the URL to work, regardless of being absolute or relative.

  7. Intranet website scenario.

  8. Server and client are the same computer.

  9. Originating URL format -

    http://localhost/Client/standard/?http-query

  10. Target URL -

    http://localhost/Client/standard/
    .

  11. Apache Access log indicates request completion with HTTP 200 response.

  12. An alert() post open doesn't show all parameters.

  13. onreadystatechange states don't get logged in console.

  14. Optional parameters when calling the ajax function.

What aspect am I overlooking?

Answer №1

You're making a mistake by calling send() twice for the same XHR object, causing an InvalidStateError due to attempting to send data when the object is already in the process of sending.

function ajax(method, url, param_id_container_pos, id_container, id_focus, sequel) {
    ....

        if (method == 'post') {
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            xhr.send(param_id_container_pos); // sending here
        }

        xhr.send(null); // then sending again triggers an error

        ..........

Additionally, it's recommended to URL encode the data before sending it.

var data = 'part=' + encodeURIComponent(p) +'&price=' + encodeURIComponent(q);
ajax('post', 'standard/', data, 'sequel_sub_object_key');

All together

var data = 'part=' + encodeURIComponent(p) +'&price=' + encodeURIComponent(q);

ajax('post', 'standard/', data, 'sequel_sub_object_key');

function ajax(method, url, param_id_container_pos, id_container, id_focus, sequel) {
    var methods = ['get', 'head', 'post'];

    if (window.XMLHttpRequest && methods.indexOf(method) != -1) {
        var xhr = new XMLHttpRequest();

        xhr.open(method, url, true);

        if (method == 'post') {
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            xhr.send(param_id_container_pos);
        } else {
            xhr.send(null);
        }

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                alert('xhr.responseText = ' + xhr.responseText);
            }
        }
    }
}

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

I'm wondering why my .focus() function is causing the cursor to move to the start of my contenteditable div?

I am currently developing a website for writing books, primarily using php. I have implemented a jQuery function that, upon clicking the "New Chapter" button, triggers an AJAX function along with various other JS/jQuery events. One of these events is inten ...

Retrieval is effective in specific situations but ineffective in others

I have encountered an issue with fetching data only when using the async behavior. I am currently in the process of re-building a property booking website that was originally developed using Laravel and a self-built API. The new version is being created wi ...

What is the relationship between $.when, apply(), and $.done() within the scope of this function?

I recently received this function from a helpful SO user that allows for returning a variable number of jQuery $.get() requests. The initial part seems pretty straightforward, but I am struggling to understand how $.when(), apply(), and $.done() are inte ...

Two ways to make a call, whether it be from the same URL or from

I have implemented two methods, namely method1() and method2(). These methods are part of two separate web APIs which are published on different URLs. I am able to call these methods using the following URLs: www.aaa.com/api/firstcontroller/method1 www.b ...

The button in my form, created using React, continuously causes the page to refresh

I tried to create a chat application using node.js and react.js. However, I'm facing an issue where clicking the button on my page refreshes the entire page. As a beginner in web development, please forgive me if this is an obvious problem. You can fi ...

Run custom JavaScript code dynamically within a webpage

What is the most effective way to use Java to automatically open a web page, run some JavaScript to complete and submit a form, and analyze the outcome? ...

Sending AJAX Responses as Properties to Child Component

Currently, I am working on building a blog using React. In my main ReactBlog Component, I am making an AJAX call to a node server to get back an array of posts. My goal is to pass this post data as props to different components. One specific component I h ...

Tips for concealing the final click (add) tab after it has been clicked and revealing the hidden (add) button when the user clicks on the remove button

I have created a form where users can add tests. Everything is working smoothly but I want the previous "Add Another Test" field to be removed when the user clicks on it and a new field to be shown. Everything is running well, but the issue is that when t ...

Utilize load-grunt-configs and run bower.install() with grunt

I have been attempting to break down my current Gruntfile into smaller parts for better clarity. However, I have encountered a hurdle while using bower.install to manage project dependencies. My directory structure appears as follows: package.json bower.j ...

Validate a JSON object key

There are two ways in which we receive JSON strings: "{"phoneNumber":[{"remove":["0099887769"]},{"add":["0099887765"]}]}" Or "{"phoneNumber":["0099887765"]}" We need to convert the JSON string from the first format to the second format. Is there a way ...

A guide on displaying information in a dropdown menu using JQuery, Ajax, and Backbone.Marionette

Currently, I am utilizing backbone and marionette for a web application. My objective is to populate a drop-down menu with JSON data once an option has been selected. The process involves the user selecting their account type, triggering an AJAX request, ...

Closing the Material UI dialog from an inner component

In my application, I have implemented a sign-in dialog using Material UI. However, I have separated the login button into its own component. I am trying to figure out how to close the dialog when the submit button in the SigninForm component is clicked. I ...

Employing Ajax.Updater to retrieve a javascript file (prototype.js)

My ajax request is set up as follows: new Ajax.Updater({ success: 'footer' }, '/dyn/actions/checkSystemMessage', { insertion: 'after', evalScripts: true }); The content found at /dyn/actions/checkSystemMessag ...

Issue with PHP functionality not functioning properly

I've been working on implementing an AJAX Form to allow users to upload their profile picture on my website. However, I've encountered some difficulties with the process. I have created a PHP page where the form is supposed to be posted using AJA ...

What is preventing me from successfully sending form data using axios?

I've encountered an issue while consuming an API that requires a filter series to be sent within a formData. When I test it with Postman, everything works smoothly. I also tried using other libraries and had no problems. However, when attempting to do ...

Discover the secrets to dynamically swapping out all columns in a Data Table with Angular2+

Whenever changes or events occur outside of the Data Table, my requirement is to replace all the columns. When the data table is displayed for the first time, it shows selected columns based on an event. However, if I select another option, the new column ...

The AJAX modal in Ruby on Rails is not displaying as expected

I'm having an issue with an AJAX modal window. The grey background shows up, but the view doesn't appear. Here is the link to the modal window: <%= link_to "Create Message", messages_path, remote: true, data: { toggle: "modal", target: "#aj ...

How can Angular JS detect the names of the CSS files being used in an HTML page?

I am in the process of developing a brand new widget where we are incorporating a unique feature that displays the number of CSS files included within an HTML page. Our team requires the count and names of all CSS files utilized on the webpage. While I a ...

What is the best way to align a TabPanel component at the center using React Material UI

As I attempt to compile a list of articles while switching to a list of other entities in React + material UI, I have encountered some difficulties. Specifically, I am struggling to center the Card displaying an article in alignment with the centered Tabs. ...

The callback for the Ajax request failing before entering the webmethod function

Below is the Ajax request I am using: $.ajax({ type: "POST", url: "ProductDetail.aspx/AddCart", data: '{productId:' + 4 + ',productTypeId:' + 0 + ',quantity:' + 1 + '}', ...