Use ajax without a plugin in wordpress

Plugin code is just… code, it can go in a themes functions.php, or a plugin file, there’s no magical or special difference other than the order they’re loaded .

The problem you’re facing is that you’ve tried to put your logic inside the search page.

Instead, the code needs to be in functions.php which is always loaded.

How AJAX Works

Ajax is actually just Javascript. It is short for Asynchronous Javascript And XML.  This means that you will use it in conjunction with the rest of your Javascript code, your CSS, HTML and perhaps even PHP.

After a lot of tinkering I finally got the answer:

First of all you don’t need this: Delete it

add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
    wp_register_script('ajax_search',TEMPLATEPATH.'/new/js/ajax_search.js', array('jquery'));
    wp_localize_script('ajax_search', 'admin_ajax_url', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));

   wp_enqueue_script( 'jquery' );
   wp_enqueue_script( 'ajax_search' );
}

Second, I was messing up GET and POST data. Use this to create an ajax search form:

<form method="post" id="searchbox">
    <input value="latestpost" name="post_id" class="ajax">
    <input type="button" class="customajax" value="submittext" name="submit">
</form>
Title: <span id="tt"></span> //to test the output

And make the ajax call with a script below this like this:

<script>
jQuery(document).ready(function($) {
    $("body").on("click",".customajax",function(){
        console.log("fire");
        var s_str = $(".ajax").val();
        var ajax_url = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
        var get_title_nonce = "<? echo $get_title_nonce; ?>";
        var data = {
            nonce: get_title_nonce,
            action: "get_title",
            post_id: s_str, 
        };
        $.post(
            ajax_url,
            data,
            function(data) {                    //callback
                $("#tt").html(data);              //insert server response
            }
        );
    });
});
</script>

Finally use this code in your template’s functions.php file:

function get_title() {

   if ( !wp_verify_nonce( $_POST['nonce'], "get_title_nonce")) {
      exit("No naughty business please");
   }   
   $result = get_the_title($_POST["post_id"]);

   if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
      //$result = json_encode($result);
      echo $result;
   } else {
      header("Location: ".$_SERVER["HTTP_REFERER"]);
   }

   die();
}
function get_title_must_login() {
   echo "You must log in to get title";
   die();
}
Social Share

Leave a Comment