Skip to main content

How to use Ajax in WORDPRESS

How AJAX Works In WordPress

What's AJAX?
AJAX stands for Asynchronous JavaScript And XML. It is the use of the XMLHttpRequest object to communicate with servers, which means it can communicate with the server, exchange data, and update the page without having to refresh the page.

Step1: Define the Ajax URL.
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' );?>';

Step2: Define its action and perform with using POST method

var emailAddress = jQuery('#uemail').val();
var searchData = {
action: 'get_registered_email',
email_address:emailAddress,
}

Step 3: Perform ajax request
jQuery.ajax({
url: ajaxurl,
type: "POST",
data: searchData,
success: function(data){
  jQuery("div#divLoading").removeClass('show');
  jQuery('#memberResult').html(data);
  //alert(data);
},
error: function(errorThrown){
alert(errorThrown);
}
});

Step 4: Use Wordpress 2 ajax hooks i.e wp_ajax_your_action and wp_ajax_nopriv_your_action

Example: In Our ajax request we have defined action name as "get_registered_email" so our ajax action hook will be as follows:

add_action('wp_ajax_nopriv_get_registered_email', 'wpyog_get_registered_email'); // for not logged in users
add_action('wp_ajax_get_registered_email', 'wpyog_get_registered_email');

Step5: Ajax request callback function
function wpyog_get_registered_email(){
wp_die();
}

Full Example 1:
JavaScript: 
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' );?>';
var emailAddress = jQuery('#uemail').val();
var searchData = {
action: 'get_registered_email',
email_address:emailAddress,
}
jQuery.ajax({
url: ajaxurl,
type: "POST",
data: searchData,
success: function(data){
  jQuery("div#divLoading").removeClass('show');
  jQuery('#memberResult').html(data);
  //alert(data);
},
error: function(errorThrown){
alert(errorThrown);

});

functions.php
add_action('wp_ajax_nopriv_get_registered_email', 'wpyog_get_registered_email'); // for not logged in users
add_action('wp_ajax_get_registered_email', 'wpyog_get_registered_email');
function wpyog_get_registered_email(){
echo "<pre>"; print_r($_REQUEST); exit;
wp_die();
}


Full Example 2:

// create nonce using php
//$nonce = wp_create_nonce("techsudhir_profile_update");
add_action( 'init', 'techsudhir_script_enqueuer' );

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

}

techsudhir_script.js
jQuery(document).ready( function() {

   jQuery(".user_action").click( function(e) {
      e.preventDefault(); 
      post_id = 12;
      nonce = 'techsudhir_profile_update';

      jQuery.ajax({
         type : "post",
         dataType : "json",
         url : myAjax.ajaxurl,
         data : {action: "save_techsudhir_profile", post_id : post_id, nonce: nonce},
         success: function(response) {
            if(response.type == "success") {
               console.log(response.view_count)
            }
            else {
               alert("Your vote could not be added")
            }
         }
      })   

   })

})

add_action("wp_ajax_save_techsudhir_profile", "save_techsudhir_profile");
add_action("wp_ajax_nopriv_save_techsudhir_profile", "save_techsudhir_profile");

function save_techsudhir_profile() {

   if ( !wp_verify_nonce( $_REQUEST['nonce'], "techsudhir_profile_update")) {
      exit("No naughty business please");
   }   

   $result['type'] = "success";
   $result['view_count'] = 11;

   if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
      $result = json_encode($result);
      echo $result;
   }
   else {
      header("Location: ".$_SERVER["HTTP_REFERER"]);
   }

   die();


}

Comments

Popular posts from this blog

Generate XML file in Cakephp

Steps to Generate XML file using CakePHP: Step-1 Enable to parse xml extension in config route.php file.     Router::parseExtensions('xml'); Step-2 Add Request Handler Component to the Controller    var $components = array(‘RequestHandler’); Step-3 Add controller Action For XML Generation in Post Controller     function generateXMLFile()     {         if ($this->RequestHandler->isXml()) { // check request type             $this->layout = 'empty'; // create an empty layout in app/views/layouts/empty.ctp              }        }  Add header code in empty layout <?php header('Content-type: text/xml');?> <?php echo $this->Xml->header(); ?> <?php echo $content_for_layout; ?> Step-4 Set up View To generate XML Create xml folder inside Posts vi...

How To Create Shortcodes In WordPress

We can create own shortcode by using its predified hooks add_shortcode( 'hello-world', 'techsudhir_hello_world_shortcode' ); 1. Write the Shortcode Function Write a function with a unique name, which will execute the code you’d like the shortcode to trigger: function techsudhir_hello_world_shortcode() {    return 'Hello world!'; } Example: [hello-world] If we were to use this function normally, it would return Hello world! as a string 2. Shortcode function with parameters function techsudhir_hello_world_shortcode( $atts ) {    $a = shortcode_atts( array(       'name' => 'world'    ), $atts );    return 'Hello ' . $a['name'] . !'; } Example: [hello-world name="Sudhir"] You can also call shortcode function in PHP using do_shortcode function Example: do_shortcode('[hello-world]');

How to replace plain URLs with links

Here we will explain how to replace Urls with links from string Using PHP $string ='Rajiv Uttamchandani is an astrophysicist, human rights activist, and entrepreneur. Academy, a nonprofit organization dedicated to providing a robust technology-centered education program for refugee and displaced youth around the world.  CNN Interview - https://www.youtube.com/watch?v=EtTwGke6Jtg   CNN Interview - https://www.youtube.com/watch?v=g7pRTAppsCc&feature=youtu.be'; $string = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-=#]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $string); Using Javascript <script> function linkify(inputText) {     var replacedText, replacePattern1, replacePattern2, replacePattern3;     //URLs starting with http://, https://, or ftp://     replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;     replacedText = inputT...