-
Notifications
You must be signed in to change notification settings - Fork 39
Ajax
#BunnyJS Ajax documentation
BunnyJS Ajax is a Native lightweight JavaScript component for making HTTP (AJAX) requests. Source file is a simple wrapper around native XMLHttpRequest supporting submitting forms and URL encoded data, and source file is only 50 lines big.
import { Ajax } from 'bunnyjs/src/bunny.ajax';To get data from the server via simple GET response use Ajax.get(str urn, onSuccess, onError)
Ajax.get('/api/v1/users/1', function(data) {
var user = JSON.parse(data);
console.log('Welcome ' + user.name);
});GET method automatically adds header X-Requested-With: XMLHttpRequest so backend application could detect that request is ajax.
To make a POST request and submit a form via AJAX use Ajax.sendForm(formElement, onSuccess, onError)
Ajax.sendForm(document.getElementById('my_form'), function(data) {
var response = JSON.parse(data);
if (response.status === 'OK') {
console.log('Form data successfully saved');
} else {
console.log('Error: ' + response.message);
}
});sendForm() method will make a POST request to URL from form action="" attribute. Request will contain data from all form inputs including hidden inputs. All inputs must have name="" attribute.
To make a custom request 3 methods should be used: Ajax.create(method, urn, data, onSuccess, onError, doSend = false) which returns a new instance of Ajax object.
If last argument is true there is no need to use rest two methods open() and send(). Second method is Ajax.open(); which should be called on created instance and the last Ajax.send();
var t = Ajax.create('HEAD', '/api/v1/check-headers', {}, function(data) {
var response = JSON.parse(data);
...
});
t.open();
t.send();If you wan't to add or modify headers, use t.request.setRequestHeader('Header', 'Content'); between t.open() and t.send();