In this article, I will introduce a small JavaScript library that I have built for making AJAX calls in various projects.
The library has three main functions: LiinAjax, LiinAjax_Endpoint, and LiinAjax_SerializeFormData.
You can find the complete code here and soon on GitHub.
AJAX stands for Asynchronous JavaScript and XML, which is a technique used in web development to create fast and dynamic web pages. It allows web pages to update content asynchronously without having to reload the entire page.
The library uses XMLHttpRequest. The XMLHttpRequest (XHR) object is a built-in object in web browsers that provides a way to make HTTP requests to a server from client-side JavaScript code.
Here’s an example of how you can structure your AJAX ‘GET’ calls using objects.
LiinAjax({
endpoint : 'https://jsonplaceholder.typicode.com/todos/1',
method : 'GET',
response : 'JSON',
success : function(response) {
console.log(response);
},
error : function() {
console.log('Error');
}
});
Here’s an example of how you can structure your AJAX ‘POST’ calls using objects.
LiinAjax({
endpoint: 'https://jsonplaceholder.typicode.com/posts',
method: 'POST',
response: 'JSON',
body: JSON.stringify({
title: 'Test',
body: 'Body',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8'
},
success: function(jsonRepsonse) {
console.log(jsonRepsonse);
},
error: function(reponse) {
console.log('Error');
}
});
The LiinAjax function is the main function for making HTTP requests. It takes an object as an argument, which can include properties such as method, response, body, endpoint, headers, success, and error.
The method property specifies the HTTP method to use for the request, with a default value of ‘GET’.
The endpoint property specifies the URL to send the request to, either as a string or as an object that can be processed by the LiinAjax_Endpoint function. The headers property specifies any custom headers to send with the request. The success property is a callback function that is called when the request is successful, and the error property is a callback function that is called when the request fails or returns an error status code.
The LiinAjax_Endpoint function is a utility function that processes an object representing an endpoint URL and query string parameters into a string that can be used as the endpoint property in the LiinAjax function. The function takes an object as an argument, which has two properties: url (the base URL for the endpoint) and query (an object containing key-value pairs for the query string parameters).
The LiinAjax_SerializeFormData function is a utility function that takes a HTML form element as an argument and returns a new FormData object containing the data from the form. This is useful for sending form data in an HTTP POST request using the LiinAjax function.
Here the code:
function LiinAjax_Endpoint(endpointObject) {
var endpoint = endpointObject.url + '?';
var isFirstProperty = true;
for (property in endpointObject.query) {
if (isFirstProperty) {
endpoint += property + '=' + endpointObject.query[property];
isFirstProperty = false;
} else {
endpoint += '&' + property + '=' + endpointObject.query[property];
}
}
return endpoint;
}
function LiinAjax(object) {
/* AJAX Method 'GET', 'POST', 'PUT'; Default: 'GET' */
var method = 'GET';
if ( object.method !== undefined ) {
method = object.method;
}
/* AJAX Response */
var JSONResponse = false;
if ( object.response === 'JSON' ) {
JSONResponse = true;
}
/* AJAX Body */
var body = null;
if ( object.body !== undefined ) {
body = object.body;
}
/* AJAX endpoint, string or LiinAjax_Endpoint object */
var endpoint = false;
if (typeof object.endpoint === 'string' || object.endpoint instanceof String) {
endpoint = object.endpoint;
} else {
endpoint = LiinAjax_Endpoint(object.endpoint);
}
/* AJAX XMLHttpRequest */
var xhr = new XMLHttpRequest();
xhr.open(method, endpoint, true);
/* AJAX Request Headers */
if ( object.headers !== undefined ) {
for (header in object.headers) {
xhr.setRequestHeader(header, object.headers[header]);
}
}
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status < 300 && this.status >= 200 ) {
var response = this.responseText;
if ( JSONResponse ) {
response = JSON.parse(response);
}
object.success(response);
} else {
object.error();
}
}
}
if (method == 'POST') {
xhr.send(body);
} else {
xhr.send();
}
}
function LiinAjax_SerializeFormData(form) {
return new FormData(form);
}
If you have suggestions for improving the code, please send an email. It should be noted that the code's functionality is provided without any guarantee or responsibility.
WordPress nonces provide essential security measures against CSRF attacks.
In WordPress, user roles determine the level of access and capabilities that each user has within a website.
This website uses cookies to ensure you get the best experience on our website.