Below is a function I created and frequently use for handling ajax requests, posts, and more
function ajax(url, callback, type, data, uploadProgress, progress){
// url,callback,type(get),FormData(null),uploadProgress,progress
let xhr = new XMLHttpRequest;
!uploadProgress||(xhr.upload.onprogress=uploadProgress);
!progress||(xhr.onprogress=progress);
xhr.onload = callback;
xhr.open(type || 'get', url);
xhr.send(data || null);
}
It seems that only Chrome supports the responseType='json';
. If you remove it, you can retrieve the JSON response using
JSON.parse()
For example:
JSON.parse(xhr.response)
To access the response from this ajax call, there are 3 options to choose from
1. In your case or mine:
xhr.response
//or yours
xhr.response
2. Using this:
this.response
3. Event target:
event.target.response
Description of the ajax function:
This ajax function takes in 6 parameters: url, callback, type (get or post), FormData (or null), uploadProgress, progress.
Only url and callback are required for a simple GET request.
ajax('url',function(){console.log(this.response)})
// It's better to use a function reference to avoid memory leaks
// like
function cb(){console.log(this.response)};
ajax('url',cb)
In the case of a POST request, you need 4 parameters:
url, callback, type(post in your case), and formdata.
So:
ajax('url', callbackFunction, 'post', fd);
Where fd can be constructed in 2 ways:
var fd = new FormData();
fd.append('key', 'value');
ajax('url', callbackFunction, 'post', fd);
Alternatively, you can also submit the entire form
var fd = new FormData(document.getElementsByTagName('form')[0]);
ajax('url', callbackFunction, 'post', fd);
You can also add a progress event function if needed
function progress(e){
console.log(e.loaded/e.total*100)
}
Same goes for the upload progress
The callback function can look like this
function callbackFunction(e){
console.log(e.target.response);
console.log(this.response);
console.log(xhr.response);
// Without responseType
console.log(JSON.parse(e.target.response));
console.log(JSON.parse(this.response));
console.log(JSON.parse(xhr.response))
}
If you have any questions feel free to ask.