Seach

php ajax wordpress example

wp_ajax_function_name,wp_ajax_nopri_function_name are the methods used for secure ajax call in wordpress to admin-ajax.php here is a simple example for ajax wordpress call .for privilage user we user wp_ajax_function name,for non privilage user we use wp_ajax_nopri_function_name here is an example for it
create a plugin and add ajax.php
<?php
/*
 * Plugin Name:ajax
 */
function my_ajax_callback_function() {
        echo "hiii";
        exit();
    }
    add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' );  
// If called from admin panel
    add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' );

create a js file and add it to wordpress 
(function($)
    {
        $(document).ready(function(e)
        {
           $.ajax(
                   {
                       url: "<?php echo admin_url('admin-ajax.php'); ?>",
                       type: 'POST',
                       data: 
                               ({action  : "my_action_name","name":"xxx","age":"xxx"}),
                       success: function (data, textStatus, jqXHR) {
                        console.log(data);
                    }
                   });
        });
    }(jQuery));
by using a plugin we dont need to inser directly into the functions.php of the wordpress