Scroll to top

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:wamp64wwwhomewp-contentthemestwentynineteen

function showdata(){
$name=$_POST[‘name’];
echo “hello”.” “.$name;
die();
}
add_action(‘wp_ajax_showdata’,’showdata’);
add_action(‘wp_ajax_nopriv_showdata’,’showdata’);

Leave a Reply

Your email address will not be published.