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:
add-event.php
<div class="container card" style="margin-top:30px; background:wheat">
<h3><b>Add Events Form</b></h3>
<hr/>
<div class="form-group">
<label for="name">Event Title:</label>
<input type="name" class="form-control" id="ename" name="etitle">
</div>
<div class="form-group">
<label for="edate">Event date:</label>
<input type="date" class="form-control" id="edate" name="edate">
</div>
<div class="form-group">
<label for="number">Cost:</label>
<input type="number" class="form-control" id="ecost" name="ecost">
</div>
<button type="button" class="btn btn-default" id="submit">Submit</button>
</div>
<script>
jQuery(document).ready( function($) {
let site_url = "<?php echo site_url(); ?>"
let ajax_url = site_url+"/add-events";
// ajax start
$('#submit').click(function(){
let ename = $('#ename').val();
let edate = $('#edate').val();
let ecost = $('#ecost').val();
$.ajax({
type : "post",
url: ajax_url,
data : {ename : ename, edate: edate, ecost:ecost},
success: function(data) {
alert(data);
}
});
});
// ajax end
});
</script>
submit-event.php (template)
<?php
// Template Name: Add event
global $wpdb;
$etitle = $_POST['ename'];
$edate = $_POST['edate'];
$ecost = $_POST['ecost'];
$table_name = 'wp_events';
$q = $wpdb->insert(
$table_name,
array(
'title' => $etitle,
'edate' => $edate,
'cost' => $ecost,
)
);
if($q){
echo "Data Saved Successfully !";
}
else{
echo "Something went wrong !";
}
?>