Can someone help me understand why this AJAX script is returning a status code of 404?

After getting involved with AJAX and utilizing the MAMP web server, I decided to work on a simple script to test its functionality. My attempt led me to investigate using the status property of XMLHttpRequest(); As it turns out, the issue I encountered was a 404 error (Page not found), which surprised me since I'm leveraging a JSON file that resides in the same directory as my AJAX script.

Below is the code snippet for the AJAX script:

var xhr = new XMLHttpRequest();
xhr.onload = function() {

if (xhr.status === 200) {

    alert("Good");
}

else if(xhr.status === 304)
{
    alert("304");

}


else if(xhr.status === 404)
{
    alert("404");
} 

else
{
    alert("500");
}
xhr.open("GET", 'json.json', true);
xhr.send(null);

Additionally, here is the content of my json.json file:

{
"events" :
[
    {
        "location" : "San Francisco, CA"
    }

]
}

Encountering this challenge has been quite frustrating. Any insights or solutions would be greatly appreciated.

Raul Rao

Answer №1

My approach involves utilizing a JSON file to manage the script within the same directory as my ajax script

The location of the JSON file is independent of the location of any JavaScript file. The server does not have knowledge nor interest in where the JS file on the front-end was fetched from, and lacks the capability to find anything relative to that. Instead, the Ajax URL is interpreted relative to the page being served (if specified as relative; it can also be specified as absolute, in which case it's relative to the web document root).

Here are examples that demonstrate successful retrieval of json.json from html.html:

webroot
    html.html
    json.json       <== located at the same level as html.html
    js
        js.js       <== placement of this file doesn't matter

webroot
    html
        html.html
        json.json   <== located at the same level as html.html
    js
        js.js

Examples that will not function properly:

webroot
    html.html
    js
        js.js       <== placement of this file doesn't matter
        json.json   <== not at the same level as html.html

Scenarios that work successfully when retrieving /json.json (note the leading slash):

webroot
    html
        html.html
    json.json       <== located at the web root
    js
        js.js

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 am having trouble getting my Ajax script to function properly when the datatype is

When working on my codes, I encountered an issue where I could successfully post data without any errors. However, I faced a problem when attempting to retrieve data from a PHP file to display in an HTML tag. If I remove 'dataType: 'json'&ap ...

What is the best way to attach an attribute to a element created dynamically in Angular2+?

After reviewing resources like this and this, I've run into issues trying to set attributes on dynamically generated elements within a custom component (<c-tabs>). Relevant Elements https://i.stack.imgur.com/9HoC2.png HTML <c-tabs #mainCom ...

Fetching data from MySQL using Ajax technology

I need assistance with my form that is supposed to input a name and phone number, fetch data from a MySQL database based on the input values, and display the results. However, when I execute the query using an onclick function, instead of retrieving data f ...

Using async/await keywords in React Native while iterating through an array and calling an API does not result in successful resolution

When attempting to request data from my API in this manner: export default ({ navigation }) => { // Call getMovieImages with the id of the likedMovies from the state.likedMovies const { getMovieImages, state:{ likedMovies }} = useContext(MovieContext); ...

Having trouble with updating PHP MySQL data using serializeArray?

My HTML page includes a display of temperature with two buttons - one for updating MySQL with the temperature setting and the other for toggling on/off data. Previously, everything was functioning correctly with the initial code: function myFunction() { ...

Navigating between routes with React-router v4: A beginner's guide

There seems to be an issue with the routing functionality in my project. Currently, only the first component, Cloud, is being rendered on the / route. However, when I try to add other routes, they don't seem to work as expected. import React from &a ...

Fixing the mobile display issue with react-responsive-carousel

I am relatively new to ReactJS and I am looking to develop a responsive Carousel. Here is the code snippet that I have currently: To achieve a responsive Carousel for both desktop and mobile devices, I utilized the react-responsive-carousel library. The ...

Is there a way to modify the package version with yarn, either upgrading or downgrading?

Is there a way to downgrade the version of a package using yarn's "dependencies" feature? ...

Interference in the output of .innerHTML leads to disruption

I have been working on a feature to display a calculated price based on the selected quantity for each individual product. I attempted to duplicate the code and modify variable names, but encountered issues with the increase/decrease buttons triggering mul ...

When converting a double value to a long type in GWT, an incorrect number may

I'm not sure if I've encountered a bug, reached a limitation of GWT, or simply made an error by creating a double with such a high number. When performing the following code on the client side: Double d = 10152826455075087d; GWT.log("Value is n ...

When utilizing AJAX requests, parameters specified in f:param are not transmitted when the form enctype is set to multipart/form-data

Currently utilizing Wildfly 8.2 and the bundled JSF version 2.2.8-jbossorg-1. This is the facelet in question: <h:form enctype="multipart/form-data"> <h:commandButton value="Submit"> <f:param name="myparam" value="true"/> ...

Creating dynamic JSON structures in Swift

I'm currently working on generating JSON data in Swift. While I've come across some examples of converting a Dictionary or a class into JSON, my main goal is to dynamically create JSON from raw data. Additionally, most examples I've found fo ...

Extracting array elements from JSON using PHP

In this project, I am analyzing the JSON data available at this link: My main goal is to extract the information from the tags[{"name":""}] section. Specifically, I am interested in retrieving the 'container' value from '"name":"Container"& ...

In PhantomJS, where is the location of the "exports" definition?

Consider the following code snippet from fs.js: exports.write = function (path, content, modeOrOpts) { var opts = modeOrOptsToOpts(modeOrOpts); // ensure we open for writing if ( typeof opts.mode !== 'string' ) { opts.mode = ...

Utilizing Selenium to add a JavaScript event listener will automatically activate it

After conducting thorough research, I've discovered that there is no direct way to capture user input using Selenium. In an attempt to work around this limitation, I have implemented a JavaScript event listener. Unfortunately, upon executing the code ...

Having trouble with setting up the next image configuration for graphcms' images

I've been using graphcms solely for my image assets and trying to integrate them into my Next JS (v12.0.1) frontend. However, I keep getting the error message hostname not configured in next.config.js, even though I have already specified it in my nex ...

Tips for creating a link that utilizes ajax to retrieve data initially and then switches to enable the data to be concealed

Currently, I am working with asp mvc 2 and have a page that contains some data. In addition, there is a link that triggers an ajax request to fetch more data and display it in a specific div on the same page. I am looking for a way to make something visib ...

Setting attributes to a DOM element using String in jQuery

I am currently facing a challenge where I have a list of attributes saved as a string variable, and I need to add that variable to a <div>. Unfortunately, I am stuck and uncertain about the best approach. Here is what I have so far: HTML: <div&g ...

Leveraging the callback function to display information from a JSON file

Attempting to retrieve JSON data from a PHP file and display it. Managed to successfully request the data via AJAX and log it to the console. (At least one part is working). Tried implementing a callback to ensure that the script waits for the data befor ...

Implementing a Basic jQuery Animation: How to Easily Display or Conceal DIV Elements Using fadeIn and fadeOut

SCENARIO: Include 2 links, MY INFO and LOG IN, within a list of ul, li elements. Hovering over one link should display a box with a form inside using the fadeIn animation. The other link should show a button in a box with a fadeIn animation when hovered o ...