Fetch data in custom wordpress theme using ajax

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:

my-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"></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,
     // data : {name : name, mobile: phone},
     success: function(data) {   
           $('#loaddata').html(data);
        }
}); 

}

ajaxload();

// ajax end

});

</script>
all-events.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%'><a href='admin.php?page=event-edit&id=<?php echo $print->id; ?>'>
<button class='btn btn-success btn-sm' type='button'>Edit</button></a>

<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 
}

?>

 

 

Leave a Reply