3

I am reading one Json file using getJSON() function.

$.getJSON('sample.json', function (data) {
    /* but file does not exist in few cases*/

}

How can i check wether file exists or not before processing?

regards

CoderPi
  • 12,985
  • 4
  • 34
  • 62
logicstar
  • 197
  • 4
  • 16

1 Answers1

5

Do nothing (aside from having a properly configured HTTP server). The function you pass to getJSON will only get called (and thus only process the data) if you get a successful response.

If the file does not exist on the server you will get a 404 (or 410) which isn't a successful response, so it won't try to process the data.

getJSON returns a jqXHR object, so you can also handle the fail condition with different code:

$.getJSON('url')
    .done(function (data, textStatus, jqXHR) { /* success */ })
    .fail(function (jqXHR, textStatus, errorThrown) { /* error */ });
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • i used $.getJSON( 'sample.json' ) .done(function( data ) { options.series = data; chart = new Highcharts.Chart(options); }) .fail(function( jqxhr, textStatus, error ) { var err = textStatus + ", " + error; console.log( "Request Failed: " + err ); }); but it does not seem to be working. – logicstar Dec 02 '15 at 15:46
  • Define "not working". Use the developer tools in your browser. Check the Console for errors and the output from your log message. Add a `console.log` to your done function so that you can tell if it is running even if Highcharts silently fails. Look at the Network tab to see if the request is made at all and what the response you are getting. In short: Do some actual debugging. – Quentin Dec 02 '15 at 15:48