DEV Community

KAK
KAK

Posted on • Originally published at railsmine.net on

Native Javascript Ready Function and JSON with AJAX GET Request

I use You Might Not Need jQuery as reference when building something with Native Javascript.

In this post I write about example usage for ready function and JSON with AJAX GET request.For POST request, please see my previous Native Javascript AJAX POST Request with Data or Parameters.

The code below is ready function based on jQuery and Native Javascript.

// jQuery
$(document).ready(function(){
});


// Native JS, IE 9+
function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

And the code below is JSON GET request based on jQuery and Native Javascript.

// jQuery
$.getJSON('/my/url', function(data) {
});


// Native JS, IE 10+
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (this.status >= 200 && this.status < 400) {
    // Success!
    var data = JSON.parse(this.response);
  } else {
    // We reached our target server, but it returned an error
  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

Example Usage

Suppose thereโ€™s HTML like this:

<div id="my-selector">
</div>

And JSON response like this:

{
  "example": {
    "foo": "bar"
  }
}

Here is example code how to insert HTML element from JSON response with Native Javascript.

function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

ready(function() {
  var request = new XMLHttpRequest();
  request.open('GET', 'https://example.com', true);

  request.onload = function() {
    if (this.status >= 200 && this.status < 400) {
      var data = JSON.parse(this.response);
      var element = document.getElementById('my-selector');

      if (data['example'] == null) {
        element.innerHTML = '<p>Empty resultt</p>';
      } else {
        element.innerHTML = '<p>'+ data['example']['foo']+'</p>';
      }
    } else {
      console.log('server error');
    }
  };

  request.onerror = function() {
    console.log('request error');
  };

  request.send();
});

Discussion (0)