WordPress: Making Ajax Calls

Just Like i promised, today we will cover making Ajax Calls
Well lets start with the basics shall we? Each request needs to supply at least one piece of data (using the GET or POST method) called action. Based on this action, the code in admin-ajax.php creates two hooks, wp_ajax_my_action and wp_ajax_nopriv_my_action, wheremy_action is the value of the GET or POST variable action.

Adding a function to the first hook means that that function will fire if a logged-in user initiates the action. Using the second hook, you can cater to logged-out users separately.

add_action( 'wp_enqueue_scripts', 'my_script_enqueuer' );

function my_script_enqueuer() {
   wp_register_script( "my_script", WP_PLUGIN_URL.'/my_plugin/my_script.js', array('jquery') );
   wp_localize_script( 'my_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));        
   wp_enqueue_script( 'my_script' );
}

If you’re unclear about what’s happening above i suggest you go through this firstLocalizing Scripts. Ok then let me explain this.
Suppose I have a script in my plugin name “my_plugin” named my_script.js. I’m sending an object name myAjax into the script with the data admin_url as data. so i can probably call this like so alert(myAjax.ajaxurl).
How even that’s the url that you’ll specify in your admin ajax call. Unclear? well let me make it clear with and example then.

For the purpose of this exercise lets create a form that checks if an email is already taken? Savvy?

Here’s the HTML for the form

<form id="digthisCheck">
<div class="message alert alert-danger" style="display:none"></div>
<div class="form-group col-sm-8"><label for="exampleInputEmail1">Email address</label>
<input id="exampleInputEmail1" class="form-control" type="email" placeholder="Enter email" />
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>

Here’s my_script.js

jQuery( document ).ready(function( $ ) {
  jQuery('#digthisCheck').submit(function(e){
    e.preventDefault();  
    var email = jQuery('#digthisCheck #exampleInputEmail1').val();
    //the ajax begins now
    jQuery.ajax({  
           type: 'POST',  
           url: myAjax.ajaxurl,  
           data: {action: 'my_ajax_handler',email:email},  
    beforeSend: function(){
      
    },
    success: function(response){
          jQuery('#digthisCheck .message').html(response).show();
         },  
       error: function(MLHttpRequest, textStatus, errorThrown){  
           console.log(errorThrown);  
       }  
      });        

    });
});

Here’s my code to handle the ajax call

add_action("wp_ajax_my_ajax_handler", "my_ajax_handler");
add_action("wp_ajax_nopriv_my_ajax_handler", "my_ajax_handler");
function my_ajax_handler()
{
 $email = $_POST['email'];
 if( email_exists( $email )) {
 echo "Sorry:Email already exists"; 
 }
 else{
 echo "you're good to go"; 
 }
 die();
}

So basically you enter an email address if it exists an affirmative comes up else a negative comes.



Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.