How to use Ajax in Wordpress

Avinash singh | 12:04 PM

How to call wordpress function using Ajax

How to call wordpress function using Jquery

Simple wp ajax example

Put this code in your template file like home.php

<input type="text" id="txt"  />
<div id="ajax"></div>

Create a file //custom.js
jQuery("button").click( function (){
    var name=jQuery("#txt").val();                                        // get text value

            url: ajaxURL.URL,
            data: 'action=demo_page&name='+name ,             //wordpress function name (demo_page)
            beforeSend: function(){ jQuery("#ajax").html('<h1>Loading  ...</h1>'); },
            success:function(msg){ jQuery("#ajax").html(msg); }

Put this code in your //function.php
function my_scripts_method() {
    wp_enqueue_script('custom', get_template_directory_uri().'/custom.js','jquery');
    wp_localize_script('custom', 'ajaxURL', array('URL'=>admin_url('admin-ajax.php')) );

add_action('wp_enqueue_scripts', 'my_scripts_method');    // to call custom.js and admin-ajax.php

add_action("wp_ajax_demo_page", "demo_pages");                    // get called when admin logged in
add_action("wp_ajax_nopriv_demo_page", "demo_pages");        // get called for frontend users
function demo_pages()
   echo "Hello Mr. ".$_REQUEST['name']."Welcome <hr/>";

Avinash Kumar Singh © 2013. All Rights Reserved | Powered by-Blogger