jeth318
jeth318

Reputation: 65

How to get data from local JSON using Ajax?

Hello brilliant people!

I've been sitting hours trying to figure out why I cant load a local JSON file using Ajax. I bet it's some silly typo, of that I totally misunderstand something. I'm using Node.js Express.

The location of the two files:

"trollytrains/views/trips.ejs" (Doing the ajax-request)

"trollytrains/json/allstops.json"

$.ajax(
    {
      type: "GET",
      url: "../json/allstops.json",
      contentType: "application/json; charset=utf-8",
      dataType: "json",     
      success: function (data) {

        alert('success');

      },

      error: function (msg) {
        alert("error");
        alert(msg.responseText);
      }
    });

I have tried altering the URL in all kinds of variations:

./allstops.json

allstops.json

json/allstops

/json/allstops

/json.allstops.json

No matter what I type I get a 404 error.

GET http://localhost:1337/json/allstops.json 404 (Not Found) jquery.min.js:4

Am I entering the wrong URL, or is there some other problem in my code that I haven't detected? I'm very new to JSON and Javascript so I wouln't be surprised.

I'd really appreciate some tips!

Best / J

Upvotes: 0

Views: 3506

Answers (2)

rsp
rsp

Reputation: 111336

Am I entering the wrong URL, or is there some other problem in my code that I haven't detected?

It depends on whether you can access the URL in the request in your example:

GET http://localhost:1337/json/allstops.json 404 (Not Found) jquery.min.js:4

See if you see the correct JSON when you go to http://localhost:1337/json/allstops.json with the browser. If you get 404 then this JSON is not served at this PATH and the problem can be either your backend failing to serve the JSON or you using the wrong URL.

It's impossible to tell you if you backend code is fine if you didn't include even a single line of the code that actually attempts to serve the JSON in question.

My assumption would be that you're not serving the JSON files.

I assume that you entire app is located in trollytrains directory and you have a json directory inside. To serve what's there you need to use something like this if you're using Express:

app.use('/json', express.static(path.join(__dirname, 'json')));

For more options to serve static files with and without Express, see this answer:

Upvotes: 1

Wintergreen
Wintergreen

Reputation: 234

Try this.

  $.ajax({
  url: '../json/allstops.json',
  dataType: 'json',
  data: 
  async: false,
  success:function()
{}
});

Upvotes: 0

Related Questions