-
-
Save madiele/a5995db081bc68e0040959fe8d163386 to your computer and use it in GitHub Desktop.
XMLHttpRequest example
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
var request = new XMLHttpRequest(); | |
request.onreadystatechange = function() { | |
if (request.readyState === 4) { | |
var data = JSON.parse(request.responseText); | |
console.log(data); | |
} | |
}; | |
request.open('GET', 'https://databaseurl/todos'); | |
request.send(); | |
/**************** | |
* POST REQUEST * | |
****************/ | |
var postRequest = new XMLHttpRequest(); | |
postRequest.open('POST', 'https://databaseurl/todos'); | |
postRequest.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); | |
postRequest.send(JSON.stringify({ text: 'Buy House', complete: false })); | |
postRequest.onreadystatechange = function() { | |
if (postRequest.readyState === 4) { | |
var data = JSON.parse(postRequest.responseText); | |
console.log(data); | |
} | |
}; | |
/***************** | |
* PATCH REQUEST * | |
*****************/ | |
/* | |
* When we want to edit a resource we need to specify which | |
* todo we want to change, this is done in the URL. We specify that we want to change | |
* the resource with the ID of 1 and use the verb 'PATCH'. | |
* We don't want to change every value (just toggle the completed) so we send along just | |
* that property with the new value (`true`). Every other property of the object will remain | |
* the same if we use `PATCH`. | |
*/ | |
var editRequest = new XMLHttpRequest(); | |
editRequest.open('PATCH', 'https://databaseurl/todos/1'); | |
editRequest.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); | |
editRequest.send(JSON.stringify({ complete: true })); | |
/****************** | |
* DELETE REQUEST * | |
******************/ | |
/* | |
* Delete requests doesn't need to send any data inside of the `send()`-method. We are | |
* removing data so we just need to specify WHAT we want to remove. What we want to remove | |
* is specified in the URL. So we are sending a DELETE-request to the URL: | |
* "https://fed17.herokuapp.com/todos/1", this means that we want to remove the todo with an ID | |
* of 1. It is important to specify the method 'DELETE' inside of `open()` | |
*/ | |
var deleteRequest = new XMLHttpRequest(); | |
deleteRequest.open('DELETE', 'https://databaseurl/todos/1'); | |
deleteRequest.setRequestHeader( | |
'Content-Type', | |
'application/json;charset=UTF-8' | |
); | |
deleteRequest.send(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment