jQuery Ajax Column Sort

by Vincy. Last modified on July 13th, 2022.

Sorting MySQL column via an AJAX call will prevent us from sending the column name and column order in URL. So, it makes page URL simple. In the last article, we have seen about how to sort MySQL column using PHP with a page refresh.

HTML Header with AJAX Call

This HTML code contains database results with column name in the table header. On clicking this header the AJAX call is sent to the server to get new results with the given sort order. The code is,

<?php 
	if(!empty($result))	 { ?>
	<table class="table-content">
		<thead>
			<tr>
			  <th width="30%" onClick="orderColumn('post_title','<?php echo $postTitleNextOrder; ?>')"><span>Post Title</span></th>
			  <th width="50%" onClick="orderColumn('description','<?php echo $descriptionNextOrder; ?>')"><span>Description</span></th>          
			  <th width="20%" onClick="orderColumn('post_at','<?php echo $postAtNextOrder; ?>')"><span>Post Date</span></th>	  
			</tr>
		</thead>
		<tbody>
		<?php
			while($row = mysqli_fetch_array($result)) {
		?>
			<tr>
				<td><?php echo $row["post_title"]; ?></td>
				<td><?php echo $row["description"]; ?></td>
				<td><?php echo $row["post_at"]; ?></td>
			</tr>
		<?php
			}
		?>
		<tbody>
	</table>
<?php } ?>

jQuery AJAX Order Column Function

This jQuery script is sending an AJAX request to order_column.php by passing column_name and order. PHP code will read these AJAX request and use the post parameters to get database results in new order. This results will be sent as an AJAX response.

jquery-ajax-column-sort

<script>
	function orderColumn(column_name,column_order) {
		$.ajax({
			url: "order-column.php",
			data:'orderby='+column_name+'&order='+column_order,
			type: "POST",
			success: function(data){	
				$('#demo-order-list').html(data);
			}
		});
	}
</script> 

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page