Home Ajax Wordpress Ajax working example

Wordpress Ajax working example

by therichpost
4 comments
wordpress

Hello to all, welcome to therichpost.com. In this post, I will tell you, Wordpress Ajax working example.

If you are new in Wordpress then please check old post related to Wordpress.

In this post, I am showing very simple Wordpress Ajax working example but sometime this takes lot of time to find the solution.


Here is I am showing the working code snippet and please follow carefully:


1. Here is the code and you can add this code into any of your theme’s template file:

<!-- Button Click for fire ajax request -->
<button type="submit" class="btn btn-default" id="addProductUrl">Submit</button>


<!-- Ajax Request Code -->
<script>
  jQuery(document).ready(function($) {
    $("#addProductUrl").click(function(event) {
      event.preventDefault();
      /* Act on the event */
      var formData = new FormData();
      formData.append('action', 'foobar');
      formData.append('id', '12345');
      $.ajax({
          url: '<?php echo admin_url('admin-ajax.php'); ?>',
         type: 'post',
         contentType: false,
         processData: false,
         data: formData,
         success: function (response) {
             //Get Ajax request response
             console.log(response)
             
         },
         error: function (response) {
          console.log(response)
         }
     });
    });
  });
</script>

 

 

2. Here is the working code and you need to add into theme’s functions.php file:

add_action( 'wp_ajax_foobar', 'my_ajax_foobar_handler' );
add_action('wp_ajax_nopriv_foobar', 'my_ajax_foobar_handler'); 
function my_ajax_foobar_handler() {
    echo $_POST['id'];

   die();
}

 

 

This is it. If you have any query related to this post, then please do comment below or ask question.

Harjas

Thank you

You may also like

4 comments

Brad lupstic August 14, 2019 - 7:05 am

Good working example

Reply
Julien Pitt September 17, 2019 - 5:28 am

Your code always help me a lot. Simple and easy
Thank you

Reply
Amanjeet November 27, 2019 - 4:42 am

Great, it helped

Reply
Ajay Malhotra June 6, 2020 - 6:38 am

Thank you all

Reply

Leave a Comment

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