'fetch' is a feature added since ES6
GET
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
POST
Old Version
var url = 'YOUR URL HERE'
var xhr = new XMLHttpRequest()
const form = document.getElementById("form-id");
var formData = new FormData(form);// it could be new FormData() also
xhr.open('POST', url, true);
xhr.addEventListener('readystatechange', function(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
// Done. Inform the user
}
else if (xhr.readyState == 4 && xhr.status != 200) {
// Error. Inform the user
}
})
//formData.append('file', file); //if file uploads are facilitated via js drag & drop
xhr.send(formData)
// for JSON Post
/*
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify({ "email": "hello@user.com", "response": { "name": "Tester" } }));
// this is handled in php with
//$data = json_decode(file_get_contents('php://input'), true);print_r($data);echo $data["response"];
*/
With 'fetch'
Ref
In addition to ural and `init' object with various options need to be supplied
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header, here it is json. if it is POST, data should be of type 'FormData' and should not be stringified
});
return response.json(); // parses JSON response into native JavaScript objects
}
// and call the function
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});
Sending a request with credentials included
fetch('https://example.com', {
credentials: 'include'
});
Uploading a file
const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');
formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);
fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: formData
})
.then(response => response.json())
.then(result => {
console.log('Success:', result);
})
.catch(error => {
console.error('Error:', error);
});
References
|
|