Last active
May 17, 2024 12:37
-
-
Save audacus/d2c753edeaaa1275e1f855607782c02b to your computer and use it in GitHub Desktop.
Template for making a AJAX request with vanilla JavaScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// create request object | |
var xhttp = new XMLHttpRequest(); | |
// set params | |
var method = 'GET' || 'DELETE' || 'POST' || 'PUT' || 'PATCH'; | |
var url = 'controller/action'; | |
var asynchronous = true; | |
// open request | |
xhttp.open(method, url, asynchronous); | |
// set ajax headers | |
xhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); | |
// set request listener | |
xhttp.onreadystatechange = function() { | |
// when answer received | |
if (this.readyState === XMLHttpRequest.DONE) { | |
var response = this.responseText; | |
// try parse json response | |
try { | |
response = JSON.parse(this.responseText); | |
} catch (e) { | |
// not json | |
} | |
// switch http status code | |
switch (this.status) { | |
case 200: | |
console.log(response); | |
break; | |
case 400: | |
console.log(response); | |
break; | |
case 404: | |
console.log(response); | |
break; | |
case 500: | |
console.log(response); | |
break; | |
default: | |
// do nothing | |
break; | |
} | |
} | |
}; | |
// send request | |
// when data has to be sent | |
if (['POST','PUT','PATCH'].indexOf(method) !== -1) { | |
// set json headers | |
xhttp.setRequestHeader('Content-Type', 'application/json; charset=utf-8'); | |
// format data into json and send request | |
xhttp.send(JSON.stringify(data)); | |
} else { | |
// set url encoded headers | |
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8'); | |
// send no data | |
xhttp.send(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment