


Pass form data for dynamic data filtering using jQuery and DataTables
Oct 12, 2025 am 05:36 AMThis article aims to solve how to pass data to DataTables through HTML
Front-end implementation: jQuery and DataTables integration
First, we need to create a form containing a
HTML structure (index.php):
PLACE # | PLACE NAME | TOTAL VISITORS |
---|---|---|
PLACE # | PLACE NAME | TOTAL VISITORS |
jQuery code:
The following is the key code to use jQuery to listen to the form submission event and reload the AJAX data of DataTables.
$(document).ready(function() { var table = $('#place-table').DataTable({ "ajax": { url: "json.php", "dataSrc": "", "data": function(d) { var frm_data = $('#frm').serializeArray(); // Use ID selector $.each(frm_data, function(key, val) { d[val.name] = val.value; }); } }, columns: [{ data: 'place_id' }, { data: 'place_name' }, { data: 'total_visitor' }] }); $("#frm").submit(function(e) { // Use ID selector e.preventDefault(); table.ajax.reload(); }); });
Code explanation:
- var table = $('#place-table').DataTable({...}) : Initialize DataTables and assign the DataTables object to the variable table for subsequent operations.
- "data": function(d) {...} : In the AJAX request, define the data function to dynamically construct the data to be sent to the server. $('#frm').serializeArray() serializes the form data into an array, then loops through the array, adding the value of each field to the DataTables' AJAX request parameters. Note that you need to use #frm to select the form through the ID selector.
- $("#frm").submit(function(e) {...}) : Listen to the form submission event. e.preventDefault() prevents the form's default submission behavior, and table.ajax.reload() reloads the AJAX data of DataTables to update the table content. Note that you need to use #frm to select the form through the ID selector.
Backend implementation: PHP data filtering (json.php)
On the server side, we need to receive AJAX requests from DataTables and query the database using the form data as the WHERE clause.
<?php $servername = "localhost"; $username = "your_username"; $password = "your_password"; $dbname = "your_database"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $selectedplace = $_POST['selectplace']; // Get the value of selectplace $sql = "SELECT * FROM placestable WHERE place_name = '$selectedplace'"; // Use prepared statements to prevent SQL injection $result = $conn->query($sql); $data = array(); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $data[] = array( "place_id"=>$row['id'], "place_name"=> $row['place_name'], "total_visitor"=> $row['total_visitor'] ); } } echo json_encode($data); $conn->close(); ?>
Code explanation:
- $selectedplace = $_POST['selectplace']; : Get the value of selectplace sent through POST request.
- * `$sql = "SELECT FROM placestable WHERE place_name = '$selectedplace'";**: Construct a SQL query statement and use the value of $selectedplace as the condition of the WHERE` clause. Important: To protect against SQL injection attacks, you should use prepared statements to build SQL queries. For example:
$stmt = $conn->prepare("SELECT * FROM placestable WHERE place_name = ?"); $stmt->bind_param("s", $selectedplace); $stmt->execute(); $result = $stmt->get_result();
- echo json_encode($data); : Encode the query results into JSON format and send it back to the client.
Notes and Summary
- Security: Always use prepared statements to prevent SQL injection attacks, especially when using user-supplied input to build SQL queries.
- Error handling: Add an error handling mechanism on the server side so that when an error occurs, it can correctly handle and return error information to the client.
- Performance optimization: If the amount of data is large, consider using server-side paging to improve performance.
- Form validation: Form validation is performed on both the client and server sides to ensure data validity and integrity.
- ID selector : Make sure to use the ID selector #frm when selecting the form in jQuery. This will select the target form element more accurately.
Through this article, you learned how to integrate HTML forms with DataTables to implement dynamic data filtering. Mastering these technologies will enable you to build more flexible and interactive Web applications.
The above is the detailed content of Pass form data for dynamic data filtering using jQuery and DataTables. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Usefilter_var()tovalidateemailsyntaxandcheckdnsrr()toverifydomainMXrecords.Example:$email="user@example.com";if(filter_var($email,FILTER_VALIDATE_EMAIL)&&checkdnsrr(explode('@',$email)[1],'MX')){echo"Validanddeliverableemail&qu

This article discusses in depth how to use CASE statements to perform conditional aggregation in MySQL to achieve conditional summation and counting of specific fields. Through a practical subscription system case, it demonstrates how to dynamically calculate the total duration and number of events based on record status (such as "end" and "cancel"), thereby overcoming the limitations of traditional SUM functions that cannot meet the needs of complex conditional aggregation. The tutorial analyzes the application of CASE statements in SUM functions in detail and emphasizes the importance of COALESCE when dealing with the possible NULL values ??of LEFT JOIN.

Useunserialize(serialize($obj))fordeepcopyingwhenalldataisserializable;otherwise,implement__clone()tomanuallyduplicatenestedobjectsandavoidsharedreferences.

Usearray_merge()tocombinearrays,overwritingduplicatestringkeysandreindexingnumerickeys;forsimplerconcatenation,especiallyinPHP5.6 ,usethesplatoperator[...$array1,...$array2].

NamespacesinPHPorganizecodeandpreventnamingconflictsbygroupingclasses,interfaces,functions,andconstantsunderaspecificname.2.Defineanamespaceusingthenamespacekeywordatthetopofafile,followedbythenamespacename,suchasApp\Controllers.3.Usetheusekeywordtoi

ToupdateadatabaserecordinPHP,firstconnectusingPDOorMySQLi,thenusepreparedstatementstoexecuteasecureSQLUPDATEquery.Example:$pdo=newPDO("mysql:host=localhost;dbname=your_database",$username,$password);$sql="UPDATEusersSETemail=:emailWHER

The__call()methodistriggeredwhenaninaccessibleorundefinedmethodiscalledonanobject,allowingcustomhandlingbyacceptingthemethodnameandarguments,asshownwhencallingundefinedmethodslikesayHello().2.The__get()methodisinvokedwhenaccessinginaccessibleornon-ex

Usepathinfo($filename,PATHINFO_EXTENSION)togetthefileextension;itreliablyhandlesmultipledotsandedgecases,returningtheextension(e.g.,"pdf")oranemptystringifnoneexists.
