Native Javascript Ready Function and JSON with AJAX GET Request
- Categories:
- javascript
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();
});
- Tags:
- #javascript
- #ajax
- #json
Recent Posts
How to Defend Against Brute-Force and DoS Attacks with Fail2ban, Nginx limit_req, and iptables
In this tutorial, I’ll explain how to protect your public-facing Linux server and Nginx web server from common threats, including brute-force and DoS attacks.
Is Getting AWS Solutions Architect Associate Certification Worth It?
If you are a full-time Software Engineer, there's no strong need to pursue this certification.
DevSecOps
My Notes about DevSecOps
AWS Secrets Manager
Explanation about AWS Secrets Manager with example code.
Envelope Encryption
Envelope encryption is the practice of encrypting plaintext data with a data key, and then encrypting the data key under another key.