Skip to main content

How to use properly ajax in wordpress ?

                          use ajax in wordpress 

            Use in main.php file which you will create

<html>
<head>
<script src="<?php echo plugin_dir_url(__FILE__);?>/js/jquery.min.js"></script>
<script>
jQuery(document).ready(function($){
$(".select").change(function(){
var name = $(".select").val();

alert(name);
var data = {
'action' : 'showdata',
'name' : name,
};
var ajaxurl = $(".ajaxurl").val();
jQuery.post(ajaxurl, data, function(response) {

console.log(response);
$(".result").val(response);

});
});
});

</script>

<style>
.wrap{

width:80%;
margin:auto;

}

</style>
<head>
<body>
<div class="wrap">
<select class="select" >
<option value="jaspreet">jaspreet</option>
<option value="Developer">Developer</option>
<option value="Hello">Hello</option>
</select>
<div class="demo"></div>
<input type="hidden" class="ajaxurl" value="<?php echo admin_url('admin-ajax.php');?>">
<input type="text" class="result">
</div>
</body>
</html>




Use in function.php file which is located in --------->>>>>>>>>> C:\wamp64\www\home\wp-content\themes\twentynineteen





function showdata(){
$name=$_POST['name'];
echo "hello"." ".$name;
die();
}
add_action('wp_ajax_showdata','showdata');
add_action('wp_ajax_nopriv_showdata','showdata');

Comments

Popular posts from this blog

How to check date format in PHP?

Check date format in PHP function isCorrectDateFromat($date){     if(!empty($date)){         $dateString = $date; // Replace this with your date string         $format = "Y-m-d"; // Replace this with your expected date format         $dateTime = DateTime::createFromFormat($format, $dateString);         if ($dateTime === false) { /*             echo "The date is not in the correct format."; */         } else {             $errors = DateTime::getLastErrors();             if (empty($errors)) { /*                 echo "The date is in the correct format."; */                 return true;             } else { /*                 echo "...