Access to XMLHttpRequest response denied due to different origin

JSON response handling issues


Edge Browser: The response property value is sometimes briefly inserted into the DOM and then removed. Occasionally, an error message "SCRIPT5: access denied" is logged (indicating CORS). The response is fully accessible from the Debugger, but the request is not shown in the network tab.

Chrome Browser: The response is an empty string, the request is not displayed in the network tab, and there are no console messages.

Firefox Browser: A console error 'response "malformed JSON"' occurs on a breakpoint line when using `response` in `JSON.parse()`, even before its usage. Similar to Chrome, the request is not shown in the network tab.


JS Code (for modern browsers only):


var session = "";
var request;

function checkLogin()
{
    if(request.readyState > 3)
    {
        var response = JSON.parse(request.response);
        if(verify(response))
        {
            // do something
        }
    }
}

function login()
{
    request = new XMLHttpRequest();
    request.onreadystatechange = checkLogin;
    request.open("GET", "authenticateUser.php?user=" + document.getElementById("user").value + "&credential="+md5(document.getElementById("password").value));
    request.send();
}

Request detail for Edge from the network tab:


Request URL: http://*MYDOMAIN*/authenticateUser.php?user=df&credential=d41d8cd98f00b204e9800998ecf8427e
Request Method: GET
Status Code: 200 / OK

[...]

Response sample:

{"success":false,"error":"authentication failed or unauthorised"}

How can I make my PHP response usable in JavaScript code in both Chrome and Firefox, ensuring that its properties' values can be inserted into the DOM?

Answer №1

login() is responsible for handling the onsubmit event. I forgot to include a return false, causing the form containing the username and password fields to submit to its own page, resulting in the browser reloading the page - effectively canceling the request in Chrome and Firefox. Surprisingly, Edge allowed the previous request's JavaScript code to handle the response until it needed to be inserted into the page.

After spending 6 hours trying various methods including JSONP and observing network traffic using Charles in Chrome, it became apparent that the page was essentially "reloading." It finally clicked when I remembered that the onsubmit handler prevents submission with return false, otherwise submitting it normally and loading the action (or the same page if no action specified), which is what occurred in this scenario.

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

Assistance with JavaScript regular expressions for dividing a string into days, hours, and minutes (accounting for plural or singular forms)

My challenge is with handling different variations in a string var str = "2 Days, 2 Hours 10 Minutes"; When I use : str.split(/Days/); The result is: ["2 ", ", 2 Hours 10 Minutes"] This method seems useful to extract values like "days", "hours" and " ...

What is the best way to change the value of a boolean array in React?

In my component, I maintain an array of boolean values as a state. When the value is false, I need to change it to true. this.state = { checkedPos: [] } handleChange(index, reaction) { if (!this.state.checkedPos[index]) { this.state.ch ...

React Checkbox Value Display Issue

I'm currently working on developing a basic to-do list application. However, I've encountered an issue where the checkbox does not automatically check itself based on the value provided; instead, it always remains checked. I have attempted to mod ...

Check to see if a variable has been assigned a value in the form of a jquery

Scenario: <div> <div class="application-section active"></div> <div class="application-section"></div> </div> I need to define the following variables var $activeSection = $("div.application-section.active") ...

Converting a JSON array into a table using AngularJS

Here is the structure of my JSON data: [{"Name":["A","B","C","D","E","F"], "Age":["20","30","40","50","55","60"], "Gender":["M","M","F","M","Unknown","Unknown"]}] I am looking to create an AngularJS table that resembles the following format: Name Age ...

kotlin NullPointerException occurs when parsing gson

I've recently started learning programming and am working on retrieving sunrise/sunset times from the Yahoo Weather API to display it on a UI. Currently, I'm using the Gson and Anko libraries. Here is my MainActivity code: class MainActivity : ...

I am encountering an issue when attempting to retrieve information from a JSON file

package com.joshbradley.pokemonapp.activities; import android.annotation.SuppressLint; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclervie ...

Mastering the Implementation of Timetable.js in Angular with TypeScript

I am currently working on integrating an amazing JavaScript plugin called Timetable.js into my Angular6 project. You can find the plugin here and its repository on Github here. While searching for a way to implement this plugin, I stumbled upon a helpful ...

What is the reason Vue Router makes API calls from different routes when I am not currently within that route?

I am currently developing a Vue application where each route contains a table that pulls information from an API. The table is housed in a separate component and waits for an event from an eventBus to trigger a data refresh. DataTable.vue this.$bus.$on(&a ...

Can one access non-static methods within React Navigation's navigationOptions?

Within my form, I am trying to position a submit button to the right of the header that triggers the same method as the submit button located at the bottom of the form. React Navigation necessitates the declaration of a static method named navigationOptio ...

Feature allowing simultaneous playback of several audio files when activated within Aframe webVR

I have been experimenting with ways to make all the sound files in my A-frame VR project autoplay when the scene loads, but also include an on-window-click function for browsers that do not support autoplay or require user interaction. Although I believe ...

Error in Material UI when using the select component

CustomComponent.js:98 UI Error: The value undefined provided for the selection is out of range. Please make sure to select a value that matches one of the available options or ''. The available options are: `All`, `Software Development`, `Qualit ...

What is the best way to choose a date and time in a custom format within my React application?

I'm currently developing the front-end of my application using React. I am looking for a way to capture the date and time in the specific format shown in this image. Any suggestions or solutions would be greatly appreciated! ...

Refresh the custom JavaScript dropdown list without having to reload the page

I implemented this code to customize a drop-down list Selector. Is there a way to reset this code without reloading the page, maybe by triggering a function with a button click? <button onclick="reset();">Reset</button> For example, if "Jagu ...

Ways to address the issue of no-param-reassign error within a function

While working on a Node/JS function, I encountered an ESLint error no-param-reassign while trying to update a candidate as shown below: update(candidate) { const { id } = candidate; if (!id) { throw new UserInputError('id is mandatory&ap ...

Using Javascript within HTML: A guide on when to utilize semi-colons and when to implement the return false statement

Exploring the use of JavaScript attributes within HTML elements: <input type="button" onclick="somceFunc()" /> <input type="button" onclick="somceFunc();" /> <input type="button" onclick="somceFunc(); return false;" /> Debating whether ...

Is there a way to programmatically prevent the back button from functioning if the previous route pathname in React was 'Login'?

When it comes to navigating back on previous pages, the traditional back button is typically used instead of relying solely on the navigation bar. However, I am currently looking to disable this feature specifically when the next previous route in line is ...

How to match Slick Slider slide width with Bootstrap container width

Utilizing the slick slider from http://kenwheeler.github.io/slick/ to showcase 3 slides side by side with the center slide displayed in the middle. This website is built on Bootstrap 4 framework and I want the slides to have the same width as the Bootstra ...

Maximizing CSS opacity for optimal performance in image fading

I'm working on creating a smooth fade in-out effect for the images in my photo gallery by adjusting the CSS opacity value using JavaScript. However, I've noticed that this process is quite sluggish on certain computers, such as my relatively new ...

When attempting to convert a dictionary to a JSON string in Swift, you may encounter an error stating that protocol type 'Any' cannot conform to 'Encodable' because only tangible types can adhere to protocols

Is there a way to convert a dictionary to a JSON string? I am encountering an error that says "Protocol type 'Any' cannot conform to 'Encodable' because only concrete types can conform to protocols." Can someone please help me fix this ...