X
    Categories: Wordpress

How to use ajax in wordpress?

Hi, In this tutorial I am going to explain how to use jquery ajax in wordpress.
It’s very simple to use if you are familiar with javascript or jquery ajax.
Just Follow 2 Steps:

Step 1 :

Add this PHP code in Functions.php

function example_ajax_request() {

    // The $_REQUEST contains all the data sent via ajax
    if ( isset($_REQUEST) ) {
            print_r($_REQUEST);
        // If you're debugging, it might be useful to see what was sent in the $_REQUEST
    }
    
    // Always die in functions echoing ajax content
   die();
}

add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );

Step 2:


Add this PHP code in Yourjs.js

jQuery(document).ready(function($) {

    // This does the ajax request
    if( $.trim(username) != '' && $.trim(email) != '' && $.trim(password) != '' && $.trim(cpassword) != '')
    {
    // url: will be 'wp-admin/admin-ajax.php' || '/wp-admin/admin-ajax.php' || ajaxurl
    $.ajax({
        url: 'wp-admin/admin-ajax.php',
        data: {
            'action':'example_ajax_request',
            'name' : 'Marimuthu',
            'password' : 'Marimuthu'
        },
        success:function(data) {
            // This outputs the result of the ajax request
              alert(data);
        },
        error: function(errorThrown){
            alert(errorThrown);
        }
    });
    }

});

Thats all, Enjoy with working ajax in wordpress.

If you like this article don’t forget to share and comment.

Marimuthu:

View Comments