Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Wordpress: How to call a plugin function with an ajax call

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.32k
    Comment on it

    In web development field we face different situations in order to fulfil the requirements. Sometimes we have to customize the well managed CMS/frameworks. Today we are going to take an sample example of wordpress plugin development. There is one situation in which we have to call the function which is defined in plugin using ajax.


    First of all we need to write an ajax script in jquery like below

    <script>
    $(document).ready(function(){
    
    $('#text_bar').click(function(){
    
    var formData = {
                'action':'country_list',
                'testing_title': 'testing ajax',
              };
              $.ajax({
        type        : 'POST', 
        url         : "<?php echo admin_url( 'admin-ajax.php' ); ?>", 
        data        : formData 
    }).done(function(data){
        console.log(data);
    });
    
    });
    </script>
    

    You need to put this in your footer file and give the id named text_bar to any element in your page. On click event we will process a ajax request.

    <p id="text_bar">Click here to process the ajax request </p>
    

    We are going to share small plugin with one static function and we will call this function in ajax request.

    <?php
    /**
    Plugin Name: testing master
    Plugin URI: http://findnerd.com
    Description: only for blog 
    Author: findnerd.com
    Version: 2.4.1
    Author URI: http://findnerd.com    
    */
    
    class Tonkk
    {
    
    public static function  country_details()
    {
        echo 'Plugin function';
    
    }
    
    }
    
    ?>
    

    Now its time to put the ajax action hooks in function.php. Please find the code below. function.php

    function country_listing()
    {
        Tonkk::country_details();
        echo 'task done';
        exit;
    }
    add_action('wp_ajax_country_list','country_listing');
    add_action('wp_ajax_nopriv_country_list','country_listing'); 
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: