shshanker
8/12/2015 - 11:27 AM

WordPress simple ajax

WordPress simple ajax

/*html*/
<form id="form-id">
<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>

/*register ajax*/
<?php 
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' );
}

/*ajax callback function*/

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();
}
?>

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

    });
});
</script>