Insert data in wordpress custom plugin using ajax

Friends, you must know one thing that in any website, whether it is WordPress or HP, there is one thing which is very important, that is our operation, which means inserting any data in the database, fetching data from it, updating it, deleting it, are called operations.

Ajax (Asynchronous JavaScript And XML) contain a special functionality that allows you to update the content of a web page dynamically without reloading it.

create url

add_submenu_page('all-customerspk', 'Submit Customers', 'Submit Customers', 
'manage_options', 'submit-customers', 
'my_sub_menu_admin_page_submit');
form.php

<div class="container">
<div class="card" style="padding:10px; background:white">

<div class="mb-3 mt-3">
<label for="uname" class="form-label">Name:</label>
<input type="text" class="form-control" id="unames" placeholder="Enter name" name="name" required>
</div>
<div class="mb-3">
<label for="pwd" class="form-label">Mobile No:</label>
<input type="number" class="form-control" id="number" placeholder="Enter your number" name="mobile" required>
</div>

<button class="btn btn-primary" id="submit">Submit</button>

</div>
</div>
script.js

<script>

jQuery(document).ready( function($) {
   let ajax_url = "admin.php?page=submit-customers";
   $("#submit").click( function(e) {
      let name = $('#name').val();
      let phone = $('#number').val();

   $.ajax({
     type : "post",
     url: ajax_url,
     data : {name : name, mobile: phone},
     success: function(data) {   
           alert(data);
        }
}); 

});

});

</script>
submit.php

<?php

global $wpdb;

$name = $_POST['name'];
$mobile = $_POST['mobile'];

$table_name = 'wp_customers';
$q = $wpdb->insert( 
$table_name, 
array( 
'name' => $name, 
'phone' => $mobile,
)

);

if($q){ 
echo '200';
}


?>

Leave a Reply