Expert Group of programming
Loading...

How to use Ajax in WordPress – Without Plugin

Posted by : Heycode Tech | Posted in : wordpress, WordPress Functions | Jul 30,2016 | 0 comments

AJAX is a big functionality in programming world and Everyone like this functionality because it loads the data without refreshing the page.

Now this article explains about the AJAX in wordpress. Now here we are describing the TRICKY about the AJAX in wordpress without using any plugin.

Let’s have an example about the search result via ajax.
Now we will create a text-box and user will type in text-box and result will display on below the text-box.

See the code.

//You will use this code in any template file where you need the ajax search.
<!-- HTML code -->
<div class="form-group">
<input type="text" name="pagelist" placeholder="Page list" class="ajax-search_text form-control">
<i class="loader-text">Loading......</i>
<div class="heycode-ajax-result">
</div>
</div>

//Past this code in footer.php, above the body tag.
<!-- JS CODE - Embedded in footer.php before body tag. -->
<script type="text/javascript">
jQuery(document).ready(function($){
 //when keyup on textbox
 $(".ajax-search_text").keyup(function(){

  var keyValue = $(this).val();
   if(keyValue){
    //********** call ajax code :start **********
//if you are using this code in PHP file then add : URL: <?php echo admin_url('admin-ajax.php'); ?>;
//otherwise change the path : http://heycodetech.com/wp-admin/admin-ajax.php : to own website path of file : admin-ajax.php :
    $.ajax({
            type : "POST",
            url  : "http://heycodetech.com/wp-admin/admin-ajax.php",
            data : 'action=get_search_list_via_ajax&text='+ keyValue ,
            beforeSend: function(){
                jQuery('i.loader-text').css('display','inline-block');
            },
            success: function(response) {
                $('i.loader-text').css('display','none');
               //past ajax result on result div.
               $(".heycode-ajax-result").html(response);
            }
        });
   //*********  Call ajax code  : end ************
   }else{
    // if textfield is blank then remove all the ajax list.
    $(".heycode-ajax-result").html("");
   }
});

//one more condition when textbox is blank then don't show the listing.
$(".ajax-search_text").blur(function(){
	var keyValue = $(this).val();
   if(!keyValue){
   	$(".heycode-ajax-result").html("");
   	$('i.loader-text').css('display','none');
   }
});

});
</script>

<!-- CSS code  -->
<style>
.loader-text{
    display:none;
    color:green;
    font-size:15px;
}
</style>

//past this code in file : functions.php : file : Don't past other file.
add_action("wp_ajax_get_search_list_via_ajax","get_search_list_via_ajax");
add_action("wp_ajax_nopriv_get_search_list_via_ajax","get_search_list_via_ajax");
function get_search_list_via_ajax(){
 $value  = $_POST['text'];
 $output = "<div class='heycodetech-ajax-listing'><ul class='heycodetech-pagelist'>";

  $argsAjax = array(
                   's'  => $value,
                   'posts_per_page'=>-1
                   );
  $queryAjax = new WP_Query($argsAjax);
  if($queryAjax->have_posts()):
    while ($queryAjax->have_posts()) : $queryAjax->the_post();
    
     $output .="<li><a href='".get_permalink()."'>".get_the_title()."</a></li>";

   endwhile;
   endif;
   wp_reset_query();
 $output .= "</ul></div>";
 echo $output;
 die(0);
}



//preview here.


Loading……


Let’s explain all the code one by one .

1 : HTML Code


In the HTML tab, you can seen a text-field and one more :DIV:which is used to show the :AJAX result:.When you will type in text-field then it will send AJAX request to database and display the result on here. See the preview section.

2: JS Code


Here is the JS CODE, once again.

//Past this code in footer.php, above the body tag.
<!-- JS CODE - Embedded in footer.php before body tag. -->
<script type="text/javascript">
jQuery(document).ready(function($){
 //when keyup on textbox
 $(".ajax-search_text").keyup(function(){
  var keyValue = $(this).val();
   if(keyValue){
    //********** call ajax code :start **********
//if you are using this code in PHP file then add : URL: <?php echo admin_url('admin-ajax.php'); ?>;
//otherwise change the path : http://heycodetech.com/wp-admin/admin-ajax.php : to own website path of file : admin-ajax.php :
    $.ajax({
            type : "POST",
            url  : "http://heycodetech.com/wp-admin/admin-ajax.php",
            data : 'action=get_search_list_via_ajax&text='+ keyValue ,
            beforeSend: function(){
                jQuery('i.loader-text').css('display','inline-block');
            },
            success: function(response) {
                $('i.loader-text').css('display','none');
               //past ajax result on result div.
               $(".heycode-ajax-result").html(response);
            }
        });
   //*********  Call ajax code  : end ************
   }else{
    // if textfield is blank then remove all the ajax list.
   $(".ajax-list").html("");
   }
});
});
</script>

In this code, you can seen that we will start from the :keyup: event . So when you will type any word in text-box then event :keyup: is called. Here is the summary points.

> $.ajax() method is used to send AJAX request. it have following important parameter.

> Type parameter => it is used to define the method of request Like POST, GET.

> URL parameter => In the wordpress, we will use the path(static and define path) of file : admin-ajax.php: Here is the full path : http://www.example.com/wp-admin/admin-ajax.php .

Note : This is the main reason,I ask you to past this JS code in footer.php so that I can use this path via PHP function. I have another method also : wp_localize_script : for send any value in JS file.

> data : 'action=get_search_list_via_ajax&text='+ keyValue : In the data parameter, we will set two things .
  >> action : it is used to verify which AJAX is called and what’s it’s data .
  >> data is managed with key and value form and we will include many key’s like.
data : 'action=get_search_list_via_ajax&key1='+ value1 +'&key2='+value2+'&key3='+value3

> Parameter : beforeSend : is used for showing the loading text when AJAX start and till AJAX request END.

> Success : parameter is used to display the result when ajax is successful .
  >> we will also stop the loading text.
  >> Past the AJAX result on the specified location.

3: CSS CODE


it is used to design and initially display none of the loading text.

4: Functions.php file code


Let’s see the code :

//past this code in file : functions.php : file : Don't past other file.
add_action("wp_ajax_get_search_list_via_ajax","get_search_list_via_ajax");
add_action("wp_ajax_nopriv_get_search_list_via_ajax","get_search_list_via_ajax");
function get_search_list_via_ajax(){
....
...
}

Actually this code page into the file : functions.php file : Let’s start the discussion about this hooks.
Here is the actual syntax :-

add_action("wp_ajax_{action name from js file}","{function_name_1}");
add_action("wp_ajax_nopriv_{action name from js file}","{function_name_2}");
function function_name_1(){
....
...
}
function function_name_2(){
.....
...
}

Function name may be same or different.It depends on what exactly you want to do. If you want to show just a short message, use the same callback for both.

But if you need completely different objects and load different additional files depending on the log-in status, use separate callbacks.
For more information about this hooks, click here

Here is the summary points.

> action name will be used with ajax hooks, see above.
> Get the data value by using the Method like $_POST[‘key’];
Like :
As per JS key - see above.
$value1 = $_POST['key1'];
$value2 = $_POST['key2'];

> We need to print the output.
> In the last we call the function : die(0); : otherwise 0 i.e zero will print with the AJAX result.
> if you will use any script like social sharing icons then you must include once again on JS code – when successfully.

5:Preview Section


It is testing module of code.

Use this code and let me know if need any help for me.

Tags:

Author information - Heycode Tech

Every world can ask question and my website registered user give the suggestion.

See all posts by Author

Connect to author

About us

Heycodetech is a platform where you can ask any questions related to the programming like PHP,jQuery, MYSQL,HTML , CSS and more Here is the Expert group of programming.