ajax-utility
v1.2.1
Published
This jQuery plugin provides utility functions for making AJAX requests, initializing DataTables, and dynamically populating `<select>` elements. It simplifies the process of fetching data from APIs and displaying it in a user-friendly format.
Readme
ajax-utility
#Author: Khujrat Sultan Shaikh
#Date: MARCH 2025
- This jQuery plugin provides utility functions for making AJAX requests, initializing DataTables, and dynamically populating
<select>elements. It simplifies the process of fetching data from APIs and displaying it in a user-friendly format.
Table of Contents
Installation
To use this plugin, include jQuery and the plugin script in your HTML file:
usage
GetData Function
- The GetData function is a common AJAX utility to fetch data from a specified URL.
#Syntax
GetData(url, type, postData, callback);
- url: The URL to send the request to.
- type: The HTTP method (e.g., "GET", "POST").
- postData: The data to send with the request (as an object).
- callback: A function to call with the response or error.
- const type = "POST";
- const url = "https://api.example.com/data";
- const postData = { key: "value" };
GetData(url, type, postData, function (error, response) {
if (error) {
console.error("Error:", error);
} else {
console.log("Success:", response);
}
});
##ajaxdatatable-function
2) ajaxDataTable Function
- The ajaxDataTable function initializes a DataTable with data fetched via AJAX.
#Syntax
# $(selector).ajaxDataTable(options);
- options: An object containing the following properties:
- url: The URL to fetch data from.
- method: The HTTP method (default is "POST").
- data: The data to send with the request (default is an empty object).
- columns: An array of column definitions for the DataTable.
- tableId: The ID of the table element.
- tableClass: dataTable Class
- BindTableElementID: The ID where DataTable is binded
- loaderSelector: The selector for the loader element.
- noDataMessage: Message to display when no data is available.
- successCallback: A callback function for successful data retrieval.
- errorCallback: A callback function for handling errors.
#javascript
$(document).ready(function () {
$('#TableHistory').ajaxDataTable({
url: "/UrlHistory/GetUrlHistory",
data: { searchdate: $("#txtdate").val(), UType: "someType" },
columns: [
{ title: "Sr.No", data: null },
{ title: "URL", data: "url" },
{ title: "Indate", data: "Indate" },
{ title: "BitDefender", data: "BitDefender" },
{ title: "Kaspersky", data: "Kaspersky" },
{ title: "IP Quality Score", data: "IPQualityScore" },
{ title: "URL Void", data: "URLVoid" },
{ title: "Result", data: "Result" }
],
successCallback: function (data) {
console.log("Data loaded successfully:", data);
},
errorCallback: function (error) {
console.error("An error occurred:", error);
}
});
});
#populateselect-function
3) populateSelect Function
- The populateSelect function dynamically populates a <select> element with options fetched via AJAX.
# $(selector).populateSelect(options);
- options: An object containing the following properties:
- url: The URL to fetch data from.
- method: The HTTP method (default is "GET").
- data: The data to send with the request (default is an empty object).
- placeholder: The placeholder text for the select element.
- selectId: The ID of the select element to populate.
- valueField: The field for the option value (default is "value").
- textField: The field for the option text (default is "text").
- onSuccess: A callback function for successful data retrieval.
- onError: A callback function for handling errors.
#javascript
function GetMachineList() {
var GrpIdData = 1; // Example group ID, replace with your actual data
$('#ddlMachine').populateSelect({
url: '/EpsReport/GetMachineList?groupid=' + GrpIdData,
method: 'GET',
selectId: 'ddlMachine',
valueField: 'LicNo',
textField: 'Machine',
onSuccess: function (data) {
console.log("Machine list populated successfully:", data);
},
onError: function (error) {
console.error("Error fetching machine list:", error);
}
});
}
// Call the function to populate the select
GetMachineList();
#examples
4) Examples
#Example 1: Using GetData
#This example demonstrates how to use the GetData function to fetch data from an API and handle the response.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GetData Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="path/to/your/jquery-ajax-utility.js"></script>
</head>
<body>
<h1>GetData Example</h1>
<button id="fetchData">Fetch Data</button>
<div id="result"></div>
```javascript
<script>
$(document).ready(function () {
$('#fetchData').on('click', function () {
const url = "https://api.example.com/data"; // Replace with your API endpoint
const postData = { key: "value" }; // Replace with your actual data
const type = "POST"; // HTTP method
GetData(url, type, postData, function (error, response) {
if (error) {
$('#result').html("Error: " + error);
} else {
$('#result').html("Success: " + JSON.stringify(response));
}
});
});
});
</script>
</body>
</html>
================================
#Example 2: Using ajaxDataTable
#This example shows how to initialize a DataTable with data fetched via AJAX.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ajaxDataTable Example</title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="path/to/your/jquery-ajax-utility.js"></script>
</head>
<body>
<h1>DataTable Example</h1>
<div id="TableHistory"></div>
```javascript
<script>
$(document).ready(function () {
$('#TableHistory').ajaxDataTable({
url: "/UrlHistory/GetUrlHistory", // Replace with your API endpoint
data: { searchdate: "2023-10-01", UType: "someType" }, // Replace with your actual data
const type = "POST"; // HTTP method
columns: [
{ title: "Sr.No", data: null }, // Placeholder for serial number
{ title: "URL", data: "url" },
{ title: "Indate", data: "Indate" },
{ title: "BitDefender", data: "BitDefender" },
{ title: "Kaspersky", data: "Kaspersky" },
{ title: "IP Quality Score", data: "IPQualityScore" },
{ title: "URL Void", data: "URLVoid" },
{ title: "Result", data: "Result" }
],
tableId: "dataTable", // ID of the table element
loaderSelector: ".loader", // Loader element selector
noDataMessage: "No data available", // Message when no data is returned
BindTableElementID: "BindTableElementID", // Message when no data is returned
tableClass: "table table-bordered table-striped display nowrap blue dataTable", // Message when no data is returned
successCallback: function (data) {
console.log("Data loaded successfully:", data);
},
errorCallback: function (error) {
console.error("An error occurred:", error);
}
});
});
</script>
</body>
</html>
===============================================
#Example 3: Using populateSelect
#This example demonstrates how to populate a <select> element with options fetched via AJAX.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>populateSelect Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="path/to/your/jquery-ajax-utility.js"></script>
</head>
<body>
<h1>Populate Select Example</h1>
<select id="ddlMachine" class="form-control">
<option value="0" selected>--- Select ---</option>
</select>
<button id="loadMachines">Load Machines</button>
```javascript
<script>
$(document).ready(function () {
$('#loadMachines').on('click', function () {
var GrpIdData = 1; // Example group ID, replace with your actual data
$('#ddlMachine').populateSelect({
url: '/EpsReport/GetMachineList?groupid=' + GrpIdData, // Replace with your API endpoint
method: 'GET',
selectId: 'ddlMachine',
valueField: 'LicNo', // Field for option value
textField: 'Machine', // Field for option text
onSuccess: function (data) {
console.log("Machine list populated successfully:", data);
},
onError: function (error) {
console.error("Error fetching machine list:", error);
}
});
});
});
</script>
</body>
</html>
=================================
#License
This project is licensed under the MIT License - see the LICENSE file for details.
