19

I am using JSON to transfer data.

What do I need in my HTML page to read a file with Ajax that only includes one JSON object into my script?

Do I need jQuery too, or is it possible to load that JSON file with Ajax?

Is it different on different browsers?

RyanS
  • 627
  • 1
  • 10
  • 26
rubo77
  • 19,527
  • 31
  • 134
  • 226

4 Answers4

61

You don't need any library, everything is available in vanilla javascript to fetch a json file and parse it :

function fetchJSONFile(path, callback) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                var data = JSON.parse(httpRequest.responseText);
                if (callback) callback(data);
            }
        }
    };
    httpRequest.open('GET', path);
    httpRequest.send(); 
}

// this requests the file and executes a callback with the parsed result once
//   it is available
fetchJSONFile('pathToFile.json', function(data){
    // do something with your data
    console.log(data);
});
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • As long as you don't need to support IE 5 and 6 – Ruan Mendes Jan 17 '13 at 21:35
  • 3
    You might want to add `|| httpRequest.status === 0` (for local connections). That really tripped me up when I was starting to learn `xmlhttprequest` – Jeffrey Sweeney Jan 17 '13 at 21:36
  • 2
    @JuanMendes The only thing this code would need to support older versions of IE is `var httpRequest = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");` But, who cares about older versions of IE? ;) – Jeffrey Sweeney Jan 17 '13 at 21:37
  • Thank you, this did what I needed as a Javascript beginner, and is simpler than other solutions I've seen. I like having the anonymous function there instead of a third, separate function. – Samuel Bradshaw Jan 25 '16 at 19:27
  • I wouldn't parse the json if I knew the callback wasn't a function. – Tomáš Zato Jun 11 '17 at 20:20
  • Make sure the path to json file is with respect to the HTML file and not the js file. Was stuck on this for a long time. – Rishabh Gupta Jun 21 '17 at 11:07
3

The most efficient way is to use plain JavaScript:

var a = new XMLHttpRequest();
a.open("GET","your_json_file",true);
a.onreadystatechange = function() {
  if( this.readyState == 4) {
    if( this.status == 200) {
      var json = window.JSON ? JSON.parse(this.reponseText) : eval("("+this.responseText+")");
      // do something with json
    }
    else alert("HTTP error "+this.status+" "+this.statusText);
  }
}
a.send();
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • This code works, but beware a wrong path will result in "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied" making it look like the code doesn't work. – shao.lo Mar 21 '16 at 18:30
1

In the past, Ajax was different in different browsers (and still is if you need to support older browsers which a good number of users are unfortunately still using). For older browsers, you would need a library like JQuery (or your own equivalent code) to handle the browser differences. In any case, for a beginner, I might recommend jQuery for good docs, a simple API, and getting started quickly, though MDN is helpful for JavaScript itself too (and you really should increasingly get to understand JavaScript/DOM APIs even if you primarily rely on jQuery).

Brett Zamir
  • 14,034
  • 6
  • 54
  • 77
1

I prefer to use ajax jquery. Jquery makes live a lot easier.

What you for example can do on the server side is, i assume you're using php:

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){
    // if it's an ajax request

    $json['success'] = 1;
    $json['html'] = '<div id="test">..[more html code here].. </div>';
    echo json_encode($json);
}else{
    // if it's an non ajax request


}

At the client side you can do the following using jquery ajax:

    $.ajax({
          type: "POST",
          url: "[your request url here]",
          data: { name: "JOKOOOOW OOWNOOO" },
          complete: function(e, xhr, settings){
              switch(e.status){
                  case 500:
                     alert('500 internal server error!');
                     break;
                  case 404:
                      alert('404 Page not found!');
                     break;
                  case 401:
                      alert('401 unauthorized access');     
                     break;       
              }
          }           
        }).done(function( data ) {
            var obj = jQuery.parseJSON(data)

            if (obj.success == 1){

                  $('div#insert_html_div').html(obj.html);

            }else if (obj.error == 1){


                            }


            // etc

        });
user1881928
  • 606
  • 6
  • 8