AJAX is a combination of HTML, CSS and JavaScript code that enables you to send data to a script and then receive and process the script’s response without needing to reload the page. Basically, AJAX is not a programming language, but if you want to use AJAX, you have to familiar with JavaScript/JQuery, HTML, CSS, and PHP. We can use ajax with wordpress by using this way:
all-events.php
<div class="container" style="margin-top:30px">
<h4>All Events</h4><hr/>
<table class="table table-striped" style="background:#f7f7f7">
<tr>
<td>S.No</td>
<td>Title</td>
<td>Date</td>
<td>Cost</td>
<td>Action</td>
</tr>
<!-- loop start -->
<tbody id="loaddata">
<tr>
<td>Loading..</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
<!-- loop end -->
</table>
</div>
<script>
jQuery(document).ready( function($) {
let ajax_url = "all-events";
// ajax start
function ajaxload(){
$.ajax({
type : "get",
url: ajax_url,
success: function(data) {
$('#loaddata').html(data);
}
});
}
ajaxload();
// ajax end
});
</script>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Update Event</h4>
</div>
<!-- popop body start -->
<div class="modal-body loadform">
<!-- load data here -->
</div>
<!-- popop body end -->
</div>
</div>
</div>
all-event.php (template)
<?php
// Template Name: All Events
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM wp_events");
foreach ($result as $key => $print) {
?>
<tr>
<td width='25%'><?php echo $key+1; ?></td>
<td width='25%'><?php echo $print->title; ?></td>
<td width='25%'><?php echo $print->edate; ?></td>
<td width='25%'><?php echo $print->cost; ?></td>
<td width='25%'>
<button type="button" class='btn btn-success btn-sm editbtn' data-toggle="modal" data-target="#myModal" id="editbtn" evId="<?php echo $print->id; ?>">Edit</button>
<a href='admin.php?page=delete-event&del=<?php echo $print->id; ?>'>
<button class='btn btn-danger btn-sm' type='button'>DELETE</button></a>
</td>
</tr>
<?php
}
?>
<script>
jQuery(document).ready( function($) {
$('.editbtn').click(function(){
let editBtnId = $(this).attr('evId');
let ajax_url = "all-events-where";
// ajax start
function ajaxload(){
$('.loadform').hide();
$.ajax({
type : "get",
url: ajax_url,
data:{id:editBtnId},
success: function(data) {
$('.loadform').show();
$('.loadform').html(data);
}
});
}
ajaxload();
// ajax end
});
});
</script>