How To Use AJAX In WordPress in Three Simple Steps

Step 1:
First we need to Add JQuery Script And Need to Initial Ajax Variable Global as shown below
add_action( 'init', 'ajax_script_enqueuer' );
 
function ajax_script_enqueuer() {
   wp_register_script( "ajax_script", WP_PLUGIN_URL.'/your_plugin/script.js', array('jquery') );
   wp_localize_script( 'ajax_script', 'ajaxuse', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));        
 
   wp_enqueue_script( 'jquery' );
   wp_enqueue_script( 'ajax_script' );
 
}
Step 2:
Second we need to Handle the Ajax Request this can be using Post and Get Hooks in WordPress as shown below
add_action("wp_ajax_ajax_response", "ajax_response"); //Login 
add_action("wp_ajax_nopriv_ajax_response", "ajax_response"); //not login
 
function ajax_response() {
  $result = "welcome to Wpdadd Ajax";
    $result = json_encode($result);
      echo $result;
   die();
 
}
Step 3:
Finally we need to Trigger Ajax as shown below
jQuery('.button').click(function(){
 
     jQuery.ajax({
         type : "post",
         dataType : "json",
         url : ajaxuse.ajaxurl,
         data : {action: "ajax_response"},
         success: function(response) {
        alert('success');
         },error: function(XMLHttpRequest, textStatus, errorThrown) { 
         alert("Status: " + textStatus); alert("Error: " + errorThrown); 
    }  
      })  
 
 
  });

0 comments:

Post a Comment

Don't Forget to comment