3

I have a json file with some data to append into a div in the html document when a button is clicked:

html:

<div class="json"></div> <button id="one"></button> 

here the javascript:

function one(){ $("#one").click(function(){ $.getJSON('one.json',function(data){ alert("success"); }) .done(function() { alert('getJSON request succeeded!'); }) .fail(function() { alert('getJSON request failed! '); }) .always(function() { alert('getJSON request ended!'); }); }); } $(document).ready(function() { one(); }); 

the one.json file is in the same directory of js file. When I click the button the alert is "getJSON request failed"...where is the mistake?

4
  • 1
    Is the html file also in the same directory? Try to make a root-relative call like "/folder/one.json" instead Commented Jan 13, 2014 at 9:33
  • what is the path to the html & js file? are they in different directories Commented Jan 13, 2014 at 9:33
  • This is impossible to answer, could be anything! Wrong filename, wrong path, not running a webserver, something else entirely Commented Jan 13, 2014 at 9:35
  • 1
    or malformed JSON: stackoverflow.com/questions/6186770/… Commented Jan 13, 2014 at 9:51

5 Answers 5

2

See if below code works :-

 $.getJSON('/YourDirectory/one.json',function(data){ alert("success"); }) 
Sign up to request clarification or add additional context in comments.

Comments

1

If you html is opening from url

localhost:80/project/test.html 

then the json path will be

localhost:80/project/one.json 

So make sure html and json in same folder.

Comments

1

well, either remove the success callback inside the getJSON method , and use .done .fail.. or use success callback only

 function one(){ $("#one").click(function(){ $.getJSON('path/to/one.json') .done(function() { alert('getJSON request succeeded!'); }) .fail(function() { alert('getJSON request failed! '); }) .always(function() { alert('getJSON request ended!'); }); }); } $(document).ready(function() { one(); }); 

Comments

1

Your Ajax request will look in the url of your current page, so if you are in :

  • mysite.com/index.html, it will look on mysite.com/one.json

and

  • mysite.com/category/index.html, it will look on mysite.com/category/one.json

If you have a modern browser, you can open the developer console to see what is the exact request made.

Comments

1

$.getJSON() takes a url as the parameter for where to get the JSON, not a file path.

$.getJSON('/one.json', function (data) { ... });

or

$.getJSON('http://localhost:1234/one.json', function (data) { ... });

Take the url for the one.json file and paste into a browser address bar. If the browser returns the JSON content, then you know you can use that url in the $.getJSON()` call.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.