How to Use AJAX in WordPress Child Theme

0 Comments

Last updated on

In this tutorial, I am going to show you how we can implement AJAX in WordPress Child Theme or any WordPress theme with the help of a simple example.

First, Make sure you activated Child Theme on your WordPress site.

Now follow the below steps to implement Ajax in your theme.

Step 1:

We are taking a simple example of the form in Template File to submit through Ajax.

Please look at a simple form with single text input and a block for display output results.

<?php   

/*
 * Template Name: Example Page Template
 *
 */

get_header(); 
?>
   
   <div id="result_bind">
       // WE WILL DISPLAY AJAX RESULT HERE!
   </div>

   <form id="user_form" class="form form-horizontal" method="post">
       <div class="form-group">
           <input class="form-control" type="text" id="username" name="username">
       </div>
       <div class="form-group">
           <input type="button" id="submit" class="btn btn-primary" name="submit" value="Submit" >
       </div>
   </form>

Step 2:

We are in the same PHP file to add more code to send Ajax requests using Javascript/jQuery. Please take a look I am updating the template file code.

<?php   

/*
 * Template Name: Example Page Template
 *
 */

get_header(); 
?>
   
   <div id="result_bind">
       // WE WILL DISPLAY AJAX RESULT HERE!
   </div>

   <form id="user_form" class="form form-horizontal" method="post">
       <div class="form-group">
           <input class="form-control" type="text" id="username" name="username">
       </div>
       <div class="form-group">
           <input type="button" id="submit" class="btn btn-primary" name="submit" value="Submit" >
       </div>
   </form>


<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script type="text/javascript" >

  $('#submit').click(function(e) {
    
    e.preventDefault();
    var username = $('#username').val();

    if(username != ''){
        var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' );?>';

        var data = {
          'action': 'my_custom_action',
          'username': username
        };
        $.post(ajaxurl, data, function(response) {
            if(response != ''){
                $('#result_bind').html(response);
            }else{
                $('#result_bind').html("No Data Found");
            }
        }).fail(function(xhr, status, error) {
            console.log(status);
            console.log(error);
        });
    }else{
      return false;
    }

  });
</script>

<?php
get_sidebar();
get_footer();
?>

Step 3:

Now we will update the functions.php file of your child theme.

In this file we will use WordPress actions like the below:

add_action(‘wp_ajax_my_custom_action’,’custom_fn_callback’);

The above action hook has 2 arguments. wp_ajax_[here will be the value that is sent with data parameter “action” in code of ajax] so it will be wp_ajax_my_custom_action while the second argument is the callback function which will process the data and send the results back.

If you want to show ajax results for non-logged-in users also for that you can add actions like this

add_action(‘wp_ajax_nopriv_my_custom_action’, ‘custom_fn_callback’);

Here is the final sample code of the functions.php file after adding both action hooks.

 add_action('wp_ajax_my_custom_action','custom_fn_callback');
 add_action('wp_ajax_nopriv_my_custom_action', 'custom_fn_callback');

function custom_fn_callback() {

    $html = '';
    if(isset($_POST['username'])){
        $username = $_POST['username'];

        if (empty($username)){
            $html = "Error, You didn\'t enter a user name!";
            wp_die();
        }
        $username = esc_sql($username);
        $html = $username;
        }
    }
    echo $html;

    wp_die();
}

Step 4:

If you want to test my code then please follow this step:

  1. Login to your WordPress dashboard
  2. Add a new page and choose “Ajax Example Page Template
  3. Visit the page and see the Magic!

This above code of AJAX in WordPress Child Theme is a core code for beginners…If you want to do more complex code using my method then also you will get your desired result.

Leave a Comment