How to use Ajax in wordpress

Ajax is fast and Smooth Way of Display content Result in Ajax is now used in many various ways on a website, such as submitting blog comments, liking posts and uploading files.

Given the popularity of Ajax, most of the leading CMS platforms use it within their architecture. WordPress is no different. Actually WordPress employs Ajax in a very robust and easy way, and today I will show you just how you can use Ajax in WordPress with a real world example.

Adding JavaScript and Your First Ajax Call

Now it’s time to create our Ajax call. Open the read-me-later.jsfile from our js folder. Add the below code:

jQuery(document).ready( function(){         
    jQuery('#content').on('click', 'a.rml_bttn', function(e) { 
        e.preventDefault();
        var rml_post_id = jQuery(this).data( 'id' );    
        jQuery.ajax({
            url : readmelater_ajax.ajax_url,
            type : 'post',
            data : {
                action : 'read_me_later',
                post_id : rml_post_id
            },
            success : function( response ) {
                jQuery('.rml_contents').html(response);
            }
        });
        jQuery(this).hide();            
    });     
}); Defining The Ajax url
wp_localize_script( 'rml-script', 'readmelater_ajax', array( 'ajax_url' => admin_url('admin-ajax.php')) );

Ajax Action Hook
Now for the important so far

So far we’ve created the Read Me Later link and connected it with Ajax. But the link doesn’t do anything yet, because we haven’t written any server side code to process the Ajax request.

// Setup Ajax action hook
add_action( 'wp_ajax_read_me_later', array( $this, 'read_me_later' ) );
Social Share

2 thoughts on “How to use Ajax in wordpress”

Leave a Comment