Reading list Switch to dark mode

    Using AJAX in WordPress

    Updated 19 March 2021

    This article will demonstrate that how you can use ajax in wordpress. There is a different proccess of using ajax in wordpress as ajax request first goes to admin-ajax.php file and then proccess it. if there is no function created then admin-ajax.php will return -1.
    Here is sample code of using ajax in wordPress in front end.

    <?php 
    add_action( 'wp_enqueue_scripts', 'my_enqueue' );
    function my_enqueue() {
     wp_enqueue_script('like_post', get_template_directory_uri().'/js/post-like.js', '1.0', 1 );
     wp_localize_script('like_post', 'ajax_var', array(
     'url' => admin_url('admin-ajax.php'),
     'nonce' => wp_create_nonce('ajaxnonce')
     ));
    }
    
    ?>

    In above Code we have used wp_localize_script() function which Localizes a registered script with data for a JavaScript variable.  Inside which we have used an array for url and nonce.

    now we can use url and nonce variables in our javascript code easily.

    if you want execute the script  to fire on the front-end for both visitors and logged-in users, then you need to use these hooks:

    <?php
    add_action( 'wp_ajax_my_post_like', 'my_post_like' );
    add_action( 'wp_ajax_nopriv_my_post_like', 'my_post_like' );
    
     ?>

    where my_post_like() is our defined function which will be invoked once ajax request is fired .

    Searching for an experienced
    WordPress Company ?
    Read More
    var $wk_jq=jQuery.noConflict();
     (function($wk_jq){ 
     	$wk_jq(window).bind("load",function(){
    	$wk_jq(".post-like a").click(function(eve){ 
    		heart = $wk_jq(this);
    		post_id = heart.data("post_id"); 
    		$wk_jq.ajax({
    			type: "post",
    			url: ajax_var.url,   // variable defined above with an array for url and nonce 
    			data: "action=my_post_like&nonce="+ajax_var.nonce+"&post_id="+post_id,  // Action variable defines the name of the php function which proceess ajax request based on the variable we have passed   
    			success: function(count){
    				 // Do your stuff here once ajax response is returned
    			}
    		});
    		eve.preventDefault();
    				
    		return false;
    		});
    	});
    })($wk_jq);
    

    In our above code we also passing a nonce variable along with the post id for security reasons

    <?php
    function my_post_like()
    {
      $nonce = $_POST['nonce']; 
     // Verify nonce field passed from javascript code
        if ( ! wp_verify_nonce( $nonce, 'ajaxnonce' ) )
            die ( 'Busted!');
       
      if(isset($_POST['post_like']))
      {
        // do your stuff and return count;
        echo $count;
        }
        else
          echo "default text";
      }
      exit;
    }
    ?>

    If you have noticed, in above code we have used exit ajax in wordPress returns 0 for any function, so we must use exit at the end of the function

    That’s all for how to use Ajax in wordPress, still have any issue feel free to add a ticket and let us know your views to make the code better https://webkul.uvdesk.com/en/customer/create-ticket/

    . . .
    Discuss on Helpdesk

    Leave a Comment

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


    8 comments

  • sagar sharma
    thanks for solving my big problem
  • San Cube
    Thanx for the beautiful information, i have one doubt , if i want to fetch data from the database and show it in the textbox, then in which file or folder i should write that .php file which connect to database.
    • Amit Chauhan (Moderator)
      I will try to answer your question as much as possible, In respect to above code snippet that i have written
      inside post_like() function you will code for sql query like
      function post_like()
      {
      global $wpdb;
      $nonce = $_POST[‘nonce’];
      // Verify nonce field passed from javascript code
      if ( ! wp_verify_nonce( $nonce, ‘ajaxnonce’ ) )
      die ( ‘Busted!’);

      $result = $wpdb->query($wpdb->prepare(“select * from $tablename where %d”, cond));
      wp_send_json($result);
      exit;
      }

      Then in javascript code
      var $wk_jq=jQuery.noConflict();
      (function($wk_jq){
      $wk_jq(window).bind(“load”,function(){
      $wk_jq(“.post-like a”).click(function(eve){
      heart = $wk_jq(this);
      post_id = heart.data(“post_id”);
      $wk_jq.ajax({
      type: “post”,
      url: ajax_var.url, // variable defined above with an array for url and nonce
      data: “action=my_post_like&nonce=”+ajax_var.nonce+”&post_id=”+post_id, // Action variable defines the name of the php function which proceess ajax request based on the variable we have passed
      success: function(response){
      // Do your stuff here once ajax response is returned, get element by id
      $wk_jq(“#textboxid”).html(response);
      }
      });
      eve.preventDefault();

      return false;
      });
      });
      })($wk_jq);
      I hope, it will help you

  • uday
    hey thanks for this post but can you please provide porper file and folder name where i can put all this code so its better for every or else you can put your code in github
    • Amit Chauhan (Moderator)
      It depends upon, you are working inside a theme or a separate plugin. i will write my suggestion based on your response
  • Michael
    In the last code example, Is the function supposed to be called my_post_like()?
    And line 9: if(isset($_POST[‘my_post_like’])) ?
  • Daffy Duck
    yeah but where are you meant to place the above code ? which folders ? which files ?
    • Amit Chauhan (Moderator)
      You can place the code in theme functions.php file or if you are working inside a plugin then you can place this code in root file as well. the js file can be separated in assets/js(depends on directory structure).
      If you any other query regarding ajax in wordpress feel free to ask
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home