How to Implement Ajax in WordPress Themes

Posted in Coding, HowTos, JS & AJAX, WordPress • Posted on 64 Comments

AJAX(Asynchronous JavaScript And XML) as we all knows is a very democratic technology in web development that allows a web page to update the content without page reload or refresh. And WordPress is widely being used not just for Blogs but for CMS’s as well. I have used WordPress many times in my Projects and Built web applications by using WordPress as a CMS. While using WordPress for your websites or web applications you will need to use Ajax in your WordPress themes or plugins etc.

Today, I am going to show you how we can implement Ajax in our WordPress themes with the help of simple example.

Task:

Suppose Our task is to show the categories in a drop down box and upon selection of Parent Categories, Sub Categories should appear in another drop down box depending on the selection of main categories.
To achieve our task let’s take a walk through step by step.

Step 1:

At first, Create Categories: Parent and Sub as well as shown in figure below:

how-to-implement-ajax-in-wordpress-themes

Step 2:

Create a template in WordPress( I am not going in details of what are the templates of WordPress and how they process in WordPress themes) in which we will implement ajax functionality. Open a new php file and save it with any name like I saved it with implement-ajax.php
Add the following code in the newly created page.

<?php
/*
Template Name: Implement Ajax
*/
get_header();
get_footer();
?>

Above code is self-explanatory. Template Name: Implement Ajax is the name of the template in wordpress and functions like get_header(); and get_footer(); are used to display the header and footer of the page.
To add the ajax stuff you will first need to include the jQuery library file in your page. You can use any JavaScript library or can call ajax stuff with RAW JavaScript too. In our example we are implementing ajax with jQuery JavaScript Library which is very popular and very active in community.

Step 3:

Lets include the Jquery file in our template and call the wp_dropdown_categories function to retrieve the Parent list of Categories in a drop down.

<?php
/*
Template Name: Implement Ajax
*/
get_header();
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" ></script>

<style type="text/css">
#content{width:auto; height:400px; margin:50px;}
</style>
<div id="content">
<?php
wp_dropdown_categories('show_count=0&selected=-1&hierarchical=1&depth=1&hide_empty=0&exclude=1&show_option_none=Main Categories&name=main_cat');
?>
<select name="sub_cat" id="sub_cat" disabled="disabled"></select>
</div>
<?php
get_footer();
?>

To understand about the arguments of wp_dropdown_categories look at here
I added second dropdown to display the sub categories in it.

Step 4:

Let’s add the Jquery code to get the ID of selected main category and then pass it on to the functions.php file where we will get the sub categories of that parent category ID and then send the results back to the page without refreshing.


$(function(){
			$('#main_cat').change(function(){
					var $mainCat=$('#main_cat').val();

					// call ajax
					 $("#sub_cat").empty();
						$.ajax({
							url:"/wp-admin/admin-ajax.php",
							type:'POST',
														data:'action=my_special_action&main_catid=' + $mainCat,

							 success:function(results)
								 {
								//  alert(results);
				$("#sub_cat").removeAttr("disabled");
				$("#sub_cat").append(results);
										}
								   });
						  }
									);
});

In the above jQuery code we added the code at change event of main categories drop down with Id #main_cat.

 var $mainCat=$('#main_cat').val();   

.val() function gets the value of the selected option from drop down and stores in $mainCat variable.

$("#sub_cat").empty();

Now before calling ajax we will empty the sub category drop down #sub_cat with previous values if any.
Our next jQuery lines are for calling ajax jQuery Function. Look at the parameters of the ajax function below:

url:"bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',														data:'action=my_special_action&main_catid=' + $mainCat,

url parameter is used to make ajax working in WordPress. So, requests will be sent to admin-ajax.php file and then we will call the hooks in our functions.php file to get the posted data that is sent to the url:”/wp-admin/admin-ajax.php”

data parameter is used for sending the values along with request.
We have used 2 arguments with data parameter
1. action
2. main_catid

Step 5:

In functions.php file we will hook an action like below:

add_action('wp_ajax_my_special_action', 'my_action_callback');

above action hook has 2 arguments. Wp_ajax_[here will be the value that is sent with data parameter “action”] so it will be wp_ajax_my_special_action while second argument is the callback function which will process the data and send the results back.
Above action hook works with logged in users. Suppose you have something to show non-logged in users you can hook an action like this

add_action('wp_ajax_nopriv_my_special_action', 'my_action_callback');

what will be our final code after adding hooks for logged and non logged users and callback function

function implement_ajax() {
if(isset($_POST['main_catid']))
			{
			$categories=  get_categories('child_of='.$_POST['main_catid'].'&hide_empty=0');
			  foreach ($categories as $cat) {
				$option .= '<option value="'.$cat->term_id.'">';
				$option .= $cat->cat_name;
				$option .= ' ('.$cat->category_count.')';
				$option .= '</option>';
			  }

			  echo '<option value="-1" selected="selected">Scegli...</option>'.$option;
			die();
			} // end if
}
add_action('wp_ajax_my_special_ajax_call', 'implement_ajax');
add_action('wp_ajax_nopriv_my_special_ajax_call', 'implement_ajax');//for users that are not logged in.

Step 6:

Now create a new page in the dashboard and assign the template to it like shown in the figures below:
how to implement ajax in wordpress themes

Load the page in the browser and you will see first drop down with parent categories loaded in it.

how to implement ajax in wordpress themes

Second drop down is empty and not loaded yet. Select any value from the first drop down and see how it works.

how to implement ajax in wordpress themes

ajax implementation in wordpress themes

Summary:

This was a simple example I used for showing you how to implement the ajax in WordPress themes. You can fit this implementation of ajax in any of your needs. If you have any problems regarding WordPress implementation you can ask me in comments. I may come up with solutions in my next tutorials. So, don’t be afraid from developing advanced themes or use it as a CMS for your Projects.

1 Written ArticlesWebsite

Hi! I am Adnan, a Full time freelance developer who gets his hands dirty with php,xhtml/css,PSD Slicing and Conversions to Xhtml/CSS, jquery,wordpress,oscommerce and facebook programming. I am presently attending the great Virtual University of Pakistan to earn my MS in Computer Science by the end of 2010. Find out more about me at my blog and tweets

64 Comments Best Comments First
  • noel

    Wednesday, November 24th, 2010 14:41

    22

    i somehow get the following error corresponding the step 4 of your tutorial ($(function(){… ):

    error: $ is not a function

    i probably missed where and how to add the Jquery code.

    +7
  • Brett Widmann

    Tuesday, December 14th, 2010 16:27

    23

    This has been very helpful! Thanks for the great tutorial.

    +3
  • Jake Goldman

    Tuesday, March 30th, 2010 18:25

    7

    To prevent conflicts with other jQuery enabled scripts, you should really use wp_enqueue_script above the header to load jQuery.

    +2
  • Danny

    Tuesday, July 26th, 2011 15:12

    49

    Hey,

    Is there a way to use this code to implement a custom taxonomy (category) ?

    I can get the first select box to show the classifieds_categories but the secon box stays blank..

    Thanks..

    Danny.

    +2
    • Janvier

      Tuesday, January 31st, 2012 12:52

      58

      To use a different taxonomy, on the get_categories(‘child_of=’.$_POST['main_catid'].’&hide_empty=0′); add taxonomy=YOURTAXONOMY where YOURTAXONOMY is the name of the taxonomy you want to use.

      All becomes get_categories(‘child_of=’.$_POST['main_catid'].’&hide_empty=0&taxonomy=YOURTAXONOMY’);

      Likewise, change wp_dropdown_categories(‘show_count=0&selected=-1&hierarchical=1&depth=1&hide_empty=0&exclude=1&show_option_none=Main Categories&name=main_cat’); TO wp_dropdown_categories(‘show_count=0&selected=-1&hierarchical=1&depth=1&hide_empty=0&exclude=1&show_option_none=Main Categories&name=main_cat&taxonomy=YOURTAXONOMY’);

      0
  • Dragon Blogger

    Tuesday, March 30th, 2010 16:38

    6

    Really nice tutorial, does adding ajax add overhead to blog load times? If you have particularly large amounts of categories? I also need to read more about creating wordpress templates.

    +2
  • David

    Monday, May 30th, 2011 19:56

    38

    Hello Adnan,

    I have your code working successfully!

    Now I am wondering if there is a way to take the final Select to the child of the child categories?

    Dropdown One — Parent Categories
    Dropdown Two — Child categories of the selected Parent category
    Dropdown Three — (the end of the categories) the children of the sub category selected in Dropdown Two

    Can your example be modified to the next level — child of the child?

    Thank you so much for your kind reply?

    +2
  • emano

    Monday, March 29th, 2010 20:36

    2

    very useful guide! great! :)

    +2
  • Thiago

    Saturday, June 18th, 2011 17:47

    41

    To avoid returning ‘0’ just add die(); before closing the php function implement_ajax()

    +1
  • Chris

    Tuesday, March 30th, 2010 19:25

    8

    Great tut my friend, You can also checkout the article from Chris Coyier from CSS-tricks from last month: “AJAXing a WordPress Theme” http://bit.ly/aQjo9G

    +1
  • raju

    Monday, July 25th, 2011 22:21

    46

    Can anyone solve the issue? I am having problem with the script. When the sub category is selected, it doesn’t display any article associated. I wonder if it needs a button to view the article of the selected category/sub-category.

    +1
  • Janvier

    Tuesday, January 31st, 2012 12:53

    59

    Great piece of code to start from. However, I noticed you have a lot of typos which leads to all kinds of errors. If you could look into that, it’s be fantastic! I got it working and I appreciate the efforts indeed

    +1
  • Tim

    Monday, November 1st, 2010 21:06

    20

    did you ever get to the bottom of the -1 0 issue I’m getting the same thing on a site I’m building at the minute for no obvious reason?

    0
  • Phillip Bryan

    Tuesday, January 25th, 2011 00:27

    24

    Fantastic. This is just what I needed. With a couple of tweaks I was able to add AJAX to my blog, and I love it.

    Thanks!

    0
  • Yummy

    Thursday, November 11th, 2010 13:30

    21

    One word for this post. AWESOME.

    This helped me implement this feature in a blog recently. Keep writing. This is truly great work.

    0
  • anthony

    Monday, February 14th, 2011 04:01

    25

    HI All,

    Would like to check with you all, may i know where should i place the code in step 4.

    Thank you.

    0
  • Leonardo

    Monday, September 27th, 2010 14:36

    19

    Thanks for this really helpful tutorial! I have some questions about doing this with the content of a page. Is it possible? Loading the header/sidebar/footer if there’s nothing to change on them doesn’t make much sense…

    Thanks for the help again!

    0
  • Tim

    Friday, April 23rd, 2010 22:48

    10

    Nice. Am going to try this out. Isn’t adding code to functions.php a bad practise? Isn’t there an alternative for that?

    0
    • zm

      Sunday, August 29th, 2010 17:24

      18

      that’s actually best practice. adding content to functions.php in your themes folder.

      0
  • Beppe

    Friday, April 2nd, 2010 15:00

    9

    Hello, very great tutorial. I would ask if is possible have four dropdown menus…? Many Thanks!

    0
  • Squiders

    Tuesday, March 30th, 2010 19:51

    5

    great tips, has got me thinking of plans!

    0
  • Rilwis

    Tuesday, March 30th, 2010 11:21

    3

    Nice tutorial. I like this type: step-by-step, code and screenshots included.

    But in this post, is it a mistake when you name the action “wp_ajax_nopriv_my_special_ajax_call” while in the code above you make a request with data: “data:’action=my_special_action&main_catid=’ + $mainCat”? I think it should be “wp_ajax_nopriv_my_special_action”.

    0
    • Adnan

      Tuesday, March 15th, 2011 08:33

      32

      Yes, it is a mistake. I’m gonna post the files used in this example. So, please check them!

      0
  • ebsoft

    Tuesday, March 30th, 2010 08:25

    4

    Nice tutorial
    I hope can implement ajax in my blog
    Thank you

    0
  • Abhinav

    Friday, May 14th, 2010 06:04

    11

    Hi

    I followed the tutorial. It was really helpful. I am not sure what am i doing wrong because my ajax call made successfully but it always return back “0”. Can you please suggest me how to debug it?

    Thanks

    0
  • Sovit Tamrakar

    Sunday, July 11th, 2010 14:22

    12

    Thanks, this helped me a lot. :)

    0
  • Thunder

    Wednesday, March 9th, 2011 00:26

    28

    I have worked for a full day and have seen nothing but the first selector field and a disabled field.

    I would like to see the full code completely assembled in the template and the full code sitting in the function.php file. I have worked with WordPress for six years. I have a good working knowledge of modifying it but there are some pieces of explanation missing that make my multitude of guesses futility.

    Particularly just how step 4 fits. The javascript says nothing about wrapping it in javascript tags but I assume it is, but where on the template page it is integrated in relation to the second field value is unclear, although I have tried numerous configurations.

    This tutorial was left unfinished.

    0
  • jinesh

    Monday, August 2nd, 2010 08:16

    15

    hi,

    I am a new for wordpress, and i want to know that where to make this implement_ajax.php file in theme folder?

    Please help me….

    Thanks in advance

    0
  • gunter

    Friday, July 23rd, 2010 20:05

    13

    Hi,
    I keep getting -1 as the returned value. The id of the selected category is passed on to the javascript but the return from the function is -1. Any help would be appreciated.
    Cheers

    0
    • Darren

      Tuesday, August 17th, 2010 01:53

      17

      Ah, I figured out why it was showing the “-1″ and “0”. I had neglected to put in the “die();” at the end of the PHP function.

      If your data is not showing up, it is likely due to mis-named functions or a typo in your code, probably not related to the “-1″/”0″ issue you’re seeing.

      0
    • Darren

      Tuesday, August 17th, 2010 01:45

      16

      I’m actually getting the same problem with the “-1″ showing up.

      At first I thought it was WordPress saying there was no data to return or a similar error. It turns out I was returning the data in the PHP function when what I needed to do was echo it. As such, the data returns and displays fine.

      It seems the “-1″ is related to whether or not the user is logged in. When I logged in, it changed to “0”. Still searching for a solution.

      0
      • pandikamal

        Tuesday, February 22nd, 2011 14:47

        26

        hi,
        I’m actually getting the same problem with the “-1″ showing up and after login it will showing 0.
        And so removed the die() and also it will be show the same.

        Please help me how to hook the ajax action in functions.php file

        0
        • David

          Saturday, February 26th, 2011 06:17

          27

          I haven’t gone through and implemented the code, so I can’t answer you directly, but

          For Anyone who’s having trouble, here’s a much more thorough article about implementing ajax by wphardcore.com
          http://www.wphardcore.com/2010/5-tips-for-using-ajax-in-wordpress/

          Cheers!

          PS He also quickly responds to every comment which is a huge plus!

          0
  • John J. Camilleri

    Tuesday, July 27th, 2010 15:36

    14

    One thing I noticed is that you cannot write an AJAX handler ONLY for the frontend;
    In other words:
    `add_action(‘wp_ajax_nopriv_my_special_ajax_call’, ‘implement_ajax’);`
    will not work without the
    `add_action(‘wp_ajax_my_special_ajax_call’, ‘implement_ajax’);`

    Or rather everything will seem to be fine, but you will always get a response of 0.

    0
  • Sefo

    Thursday, August 4th, 2011 00:39

    50

    IT WORKS!! Thanks a lot!

    0
  • Saul

    Tuesday, December 6th, 2011 22:55

    56

    I have the follow Error: ¿Could you help me please?
    Fatal error: Call to undefined function add_action() in /httpdocs/site/wp-includes/functions.php on line 4569
    I have installed the WordPress Version 3.2.1

    My Code:
    function implement_ajax() {
    if(isset($_POST['estado_id']))
    {
    $pages= get_pages(‘title_li=&sort_column=menu_order&parent=’.$_POST['estado_id'].’&child_of=’.$_POST['estado_id'].’&hierarchical=0′);
    foreach ($pages as $pagg) {
    $option = ‘ID ) . ‘”>';;
    $option .= $pag->post_title;
    $option .= ”;
    }

    echo ‘Scegli…’.$option;
    die();
    } // end if
    }
    add_action(‘wp_ajax_my_special_action’, ‘implement_ajax’);
    add_action(‘wp_ajax_nopriv_my_special_action’, ‘implement_ajax’);

    0
  • Beratz Gashi

    Tuesday, December 6th, 2011 02:27

    55

    if somebody can post a video tutorial of this will help us more to beginners

    0
  • Alvin

    Wednesday, August 24th, 2011 13:22

    54

    Hi super tutorial biut how to implement this in an existing theme ?
    I have found the following code in my theme , but what should be modified ?
    I am a total noob in php :(
    —————————————————————————————————————-
    <?php
    $select = wp_dropdown_categories( 'show_option_none=Select&show_count=0&orderby=name&echo=0&hide_empty=0' );
    $select = preg_replace( '||i’, ”, $select );
    echo $select;
    ?>

    —————————————————————————————————————-

    Hope someone can help me out here!

    Gr. Alvin

    0
  • Muhammad Adnan

    Thursday, August 4th, 2011 23:44

    52

    function my_special_ajax_call() {
    if(isset($_POST['main_catid']))
    {
    global $wpdb;
    $categories = get_categories(‘child_of=’.$_POST['main_catid'].’&show_count=1&hide_empty=0′);
    if(count($categories) > 0){
    foreach ($categories as $cati) {
    $option .= ‘term_id.'”>';
    $option .= $cati->cat_name;
    //$option .= ‘ (‘.$cati->category_count.’)';
    $option .= ”;
    }}else{

    $option = ‘None';

    }

    //
    echo $option;
    die();
    } // end if
    }
    add_action(‘wp_ajax_my_special_ajax_call’, ‘my_special_ajax_call’);
    add_action(‘wp_ajax_nopriv_my_special_ajax_call’, ‘my_special_ajax_call’);//for users that are not logged in.

    0
  • Take

    Saturday, August 20th, 2011 13:22

    53

    How i can add this function in some other php file, not in admin-ajax.php, can i add in functiones.php inside my theme?

    0
  • Todd

    Saturday, January 28th, 2012 16:49

    57

    On the last Code Snippet block, it should be

    add_action(‘wp_ajax_my_special_action’, ‘implement_ajax’);
    add_action(‘wp_ajax_nopriv_my_special_action’, ‘implement_ajax’);//for users that are not logged in.

    and not wp_ajax_my_special_ajax_call. Took me a while to find out why it was returning 0 always.

    0
  • Madhavi

    Wednesday, April 11th, 2012 06:23

    64

    I have followed all the steps but, i have got error messages in function.php file. So, i would like to know whether any body solved the problem of Categories and Sub-categories. please help me to wrote this code.

    0
  • Franl

    Sunday, April 8th, 2012 17:02

    63

    Hi.

    Great tutorial.

    How can I do for don´t show the number of post for each subcategory????

    thanks

    0
  • Todd

    Tuesday, March 20th, 2012 23:35

    62

    Super love you website, I am new to wordpress plugin development, I try like 5hours to use ajax with wordpress and search like all website. but fortunately, your website explain me step by step clearly. THanks so muchhhhh

    0
  • Veronica

    Thursday, February 9th, 2012 06:04

    60

    This was a great tutorial. I’ve read ebooks, tutorials, etc. on WP ajax and was about to give up when I stumbled on your tutorial. It was straight forward and I was able to finish my chained select boxes based on custom post type meta data with no problems. Thank you!

    0
  • carlos victor

    Friday, February 10th, 2012 10:00

    61

    Great tutorial, man! Like others said, I also search in many websites and could not understand how to use ajax in wordpress. Congratulations!
    ps: I had the same problem of the user thinkdj. So, would be nice if you could fix in the tutorial the name of the function.

    0
  • Sefo

    Thursday, August 4th, 2011 04:03

    51

    I’ve the “-1/0″ problem. I’m working with the downloaded files. with die(); at the end and all that corrections.

    As I can see, if i log as admin it works fine. But if i’m logged as editor or something else, the problem starts.

    Can somebody help me?

    0
  • Shah Alam

    Friday, June 10th, 2011 06:37

    39

    I use your code but in action page it does not make any call back data .so its return 0 would please explain to use it.

    0
  • Amer

    Wednesday, May 11th, 2011 21:27

    36

    This is working fine for me but the frontend is returning 404 page if i’m not logged in. Maybe my permission to the wp-admin folder is preventing it from working

    0
  • abc

    Wednesday, March 9th, 2011 16:56

    30

    I am always getting 0 as response. i created a sub- categories of the main categories still it show 0 always. Can anybody has the ability to help me.

    0
    • dusuarez

      Wednesday, July 20th, 2011 07:50

      45

      There is a bug in code.
      On step 5, at lines 16 and 17, just change “my_special_ajax_call” to “my_special_action”

      0
    • Shawn Janas

      Friday, April 29th, 2011 06:34

      35

      Same here :(

      0
      • Muhammad Adnan

        Monday, July 11th, 2011 07:31

        44

        Check the code I posted in comments.

        -1
        • raju

          Tuesday, July 26th, 2011 01:35

          47

          Hi adnan, I did copy and paste your code attached still there is no result when the drop down is selected. The sub category gets populated after the parent category is selected but when the sub category is selected, it does not do anything. Can you please help? Thank you.

          -1
        • raju

          Tuesday, July 26th, 2011 02:58

          48

          Ok I added javascript on step 3 as follows:

          var dropdown = document.getElementById("sub_cat");
          function onCatChange() {
          if ( dropdown.options[dropdown.selectedIndex].value > 0 ) {
          location.href = "/?cat="+dropdown.options[dropdown.selectedIndex].value;
          }
          }
          dropdown.onchange = onCatChange;


          Now, when the sub cat is selected, it shows the posts. It will be better if the drop holds the category on the option so that the user knows where they are.

          +1
  • Lena Tailor

    Monday, March 29th, 2010 16:15

    1

    Appreciate Efforts.

    Great post, I am planing on implementing it on my personal Blog.. Tx

    0
  • Kaleem Ahmad

    Monday, May 16th, 2011 07:30

    37

    Any one got the solution, please let me know , I am stuck in this.

    0
  • Tandil Ajedrez

    Tuesday, July 5th, 2011 20:54

    43

    Existe any plugin for make the entire site in ajax?

    0
  • Gonza

    Wednesday, June 22nd, 2011 07:03

    42

    EXACTLY what i was looking for. You saved me long hours of hard work.
    Genius!!1
    Thank you thank you thank you

    0
  • Luke

    Wednesday, March 9th, 2011 03:46

    29

    Hi and thanks so much for the tutorial.

    I am however having trouble getting it to return anything other than ‘0’ into the second category selection box. No matter what, it just returns ‘0’.

    Any thoughts on this? I think it must be in the functions.php code snippet, but I’m not sure how/why it’s doing it.

    Thanks
    Luke

    -1
    • Muhammad Adnan

      Tuesday, March 15th, 2011 09:42

      33

      Here is the download link for the files used in this tutorial
      http://www.imblog.info/implement-ajax.zip

      0
      • Sjaakie

        Friday, June 10th, 2011 14:15

        40

        Thank you very much! I finally got it working with these files. Like other people here ive been working with this tutorial for a few hours with no result. Thank you for posting these.

        0
    • Thunder

      Wednesday, March 9th, 2011 17:31

      31

      Will just one person who has gotten this to work please come back and show us the code?

      I never fail to eventually get all kinds of modifications working.

      2 days now I have spent hour after hour with all possible permutations and I get nothing but a 0 or -1.

      I am testing on a localhost and even gave the complete http url to the admin-ajax.php script. Put the jquery script in the actual header, too.

      I have a virgin WP 3.1 script on PHP 5 and Mysql 5.

      I set up Categories both parent and sub cats and am good to go.

      The first dropdown shows those categories.

      Nothing output but 0 or -1 in the second.

      Adnan, there’s something crucial that is missing!

      But if someone has figured it out please share the exact script that works.

      +1
      • Adnan

        Tuesday, March 15th, 2011 08:36

        34

        @Thunder I’m gonna post the files used in this example. So, please check them! if they doesn’t work still. then send me your live link of that page. I will see what is going wrong with it.

        +1
  • Madhavi

    Wednesday, April 11th, 2012 06:23

    64

    I have followed all the steps but, i have got error messages in function.php file. So, i would like to know whether any body solved the problem of Categories and Sub-categories. please help me to wrote this code.

    0
  • Franl

    Sunday, April 8th, 2012 17:02

    63

    Hi.

    Great tutorial.

    How can I do for don´t show the number of post for each subcategory????

    thanks

    0
  • Todd

    Tuesday, March 20th, 2012 23:35

    62

    Super love you website, I am new to wordpress plugin development, I try like 5hours to use ajax with wordpress and search like all website. but fortunately, your website explain me step by step clearly. THanks so muchhhhh

    0
  • carlos victor

    Friday, February 10th, 2012 10:00

    61

    Great tutorial, man! Like others said, I also search in many websites and could not understand how to use ajax in wordpress. Congratulations!
    ps: I had the same problem of the user thinkdj. So, would be nice if you could fix in the tutorial the name of the function.

    0
  • Veronica

    Thursday, February 9th, 2012 06:04

    60

    This was a great tutorial. I’ve read ebooks, tutorials, etc. on WP ajax and was about to give up when I stumbled on your tutorial. It was straight forward and I was able to finish my chained select boxes based on custom post type meta data with no problems. Thank you!

    0
  • Janvier

    Tuesday, January 31st, 2012 12:53

    59

    Great piece of code to start from. However, I noticed you have a lot of typos which leads to all kinds of errors. If you could look into that, it’s be fantastic! I got it working and I appreciate the efforts indeed

    +1
  • Todd

    Saturday, January 28th, 2012 16:49

    57

    On the last Code Snippet block, it should be

    add_action(‘wp_ajax_my_special_action’, ‘implement_ajax’);
    add_action(‘wp_ajax_nopriv_my_special_action’, ‘implement_ajax’);//for users that are not logged in.

    and not wp_ajax_my_special_ajax_call. Took me a while to find out why it was returning 0 always.

    0
  • Saul

    Tuesday, December 6th, 2011 22:55

    56

    I have the follow Error: ¿Could you help me please?
    Fatal error: Call to undefined function add_action() in /httpdocs/site/wp-includes/functions.php on line 4569
    I have installed the WordPress Version 3.2.1

    My Code:
    function implement_ajax() {
    if(isset($_POST['estado_id']))
    {
    $pages= get_pages(‘title_li=&sort_column=menu_order&parent=’.$_POST['estado_id'].’&child_of=’.$_POST['estado_id'].’&hierarchical=0′);
    foreach ($pages as $pagg) {
    $option = ‘ID ) . ‘”>';;
    $option .= $pag->post_title;
    $option .= ”;
    }

    echo ‘Scegli…’.$option;
    die();
    } // end if
    }
    add_action(‘wp_ajax_my_special_action’, ‘implement_ajax’);
    add_action(‘wp_ajax_nopriv_my_special_action’, ‘implement_ajax’);

    0
  • Beratz Gashi

    Tuesday, December 6th, 2011 02:27

    55

    if somebody can post a video tutorial of this will help us more to beginners

    0
  • Alvin

    Wednesday, August 24th, 2011 13:22

    54

    Hi super tutorial biut how to implement this in an existing theme ?
    I have found the following code in my theme , but what should be modified ?
    I am a total noob in php :(
    —————————————————————————————————————-
    <?php
    $select = wp_dropdown_categories( 'show_option_none=Select&show_count=0&orderby=name&echo=0&hide_empty=0' );
    $select = preg_replace( '||i’, ”, $select );
    echo $select;
    ?>

    —————————————————————————————————————-

    Hope someone can help me out here!

    Gr. Alvin

    0
  • Take

    Saturday, August 20th, 2011 13:22

    53

    How i can add this function in some other php file, not in admin-ajax.php, can i add in functiones.php inside my theme?

    0
  • Muhammad Adnan

    Thursday, August 4th, 2011 23:44

    52

    function my_special_ajax_call() {
    if(isset($_POST['main_catid']))
    {
    global $wpdb;
    $categories = get_categories(‘child_of=’.$_POST['main_catid'].’&show_count=1&hide_empty=0′);
    if(count($categories) > 0){
    foreach ($categories as $cati) {
    $option .= ‘term_id.'”>';
    $option .= $cati->cat_name;
    //$option .= ‘ (‘.$cati->category_count.’)';
    $option .= ”;
    }}else{

    $option = ‘None';

    }

    //
    echo $option;
    die();
    } // end if
    }
    add_action(‘wp_ajax_my_special_ajax_call’, ‘my_special_ajax_call’);
    add_action(‘wp_ajax_nopriv_my_special_ajax_call’, ‘my_special_ajax_call’);//for users that are not logged in.

    0
  • Sefo

    Thursday, August 4th, 2011 04:03

    51

    I’ve the “-1/0″ problem. I’m working with the downloaded files. with die(); at the end and all that corrections.

    As I can see, if i log as admin it works fine. But if i’m logged as editor or something else, the problem starts.

    Can somebody help me?

    0
  • Sefo

    Thursday, August 4th, 2011 00:39

    50

    IT WORKS!! Thanks a lot!

    0
  • Danny

    Tuesday, July 26th, 2011 15:12

    49

    Hey,

    Is there a way to use this code to implement a custom taxonomy (category) ?

    I can get the first select box to show the classifieds_categories but the secon box stays blank..

    Thanks..

    Danny.

    +2
    • Janvier

      Tuesday, January 31st, 2012 12:52

      58

      To use a different taxonomy, on the get_categories(‘child_of=’.$_POST['main_catid'].’&hide_empty=0′); add taxonomy=YOURTAXONOMY where YOURTAXONOMY is the name of the taxonomy you want to use.

      All becomes get_categories(‘child_of=’.$_POST['main_catid'].’&hide_empty=0&taxonomy=YOURTAXONOMY’);

      Likewise, change wp_dropdown_categories(‘show_count=0&selected=-1&hierarchical=1&depth=1&hide_empty=0&exclude=1&show_option_none=Main Categories&name=main_cat’); TO wp_dropdown_categories(‘show_count=0&selected=-1&hierarchical=1&depth=1&hide_empty=0&exclude=1&show_option_none=Main Categories&name=main_cat&taxonomy=YOURTAXONOMY’);

      0
  • raju

    Monday, July 25th, 2011 22:21

    46

    Can anyone solve the issue? I am having problem with the script. When the sub category is selected, it doesn’t display any article associated. I wonder if it needs a button to view the article of the selected category/sub-category.

    +1
  • Tandil Ajedrez

    Tuesday, July 5th, 2011 20:54

    43

    Existe any plugin for make the entire site in ajax?

    0
  • Gonza

    Wednesday, June 22nd, 2011 07:03

    42

    EXACTLY what i was looking for. You saved me long hours of hard work.
    Genius!!1
    Thank you thank you thank you

    0
  • Thiago

    Saturday, June 18th, 2011 17:47

    41

    To avoid returning ‘0’ just add die(); before closing the php function implement_ajax()

    +1
  • Shah Alam

    Friday, June 10th, 2011 06:37

    39

    I use your code but in action page it does not make any call back data .so its return 0 would please explain to use it.

    0
  • David

    Monday, May 30th, 2011 19:56

    38

    Hello Adnan,

    I have your code working successfully!

    Now I am wondering if there is a way to take the final Select to the child of the child categories?

    Dropdown One — Parent Categories
    Dropdown Two — Child categories of the selected Parent category
    Dropdown Three — (the end of the categories) the children of the sub category selected in Dropdown Two

    Can your example be modified to the next level — child of the child?

    Thank you so much for your kind reply?

    +2
  • Kaleem Ahmad

    Monday, May 16th, 2011 07:30

    37

    Any one got the solution, please let me know , I am stuck in this.

    0
  • Amer

    Wednesday, May 11th, 2011 21:27

    36

    This is working fine for me but the frontend is returning 404 page if i’m not logged in. Maybe my permission to the wp-admin folder is preventing it from working

    0
  • abc

    Wednesday, March 9th, 2011 16:56

    30

    I am always getting 0 as response. i created a sub- categories of the main categories still it show 0 always. Can anybody has the ability to help me.

    0
    • Shawn Janas

      Friday, April 29th, 2011 06:34

      35

      Same here :(

      0
      • Muhammad Adnan

        Monday, July 11th, 2011 07:31

        44

        Check the code I posted in comments.

        -1
        • raju

          Tuesday, July 26th, 2011 01:35

          47

          Hi adnan, I did copy and paste your code attached still there is no result when the drop down is selected. The sub category gets populated after the parent category is selected but when the sub category is selected, it does not do anything. Can you please help? Thank you.

          -1
        • raju

          Tuesday, July 26th, 2011 02:58

          48

          Ok I added javascript on step 3 as follows:

          var dropdown = document.getElementById("sub_cat");
          function onCatChange() {
          if ( dropdown.options[dropdown.selectedIndex].value > 0 ) {
          location.href = "/?cat="+dropdown.options[dropdown.selectedIndex].value;
          }
          }
          dropdown.onchange = onCatChange;


          Now, when the sub cat is selected, it shows the posts. It will be better if the drop holds the category on the option so that the user knows where they are.

          +1
    • dusuarez

      Wednesday, July 20th, 2011 07:50

      45

      There is a bug in code.
      On step 5, at lines 16 and 17, just change “my_special_ajax_call” to “my_special_action”

      0
  • Luke

    Wednesday, March 9th, 2011 03:46

    29

    Hi and thanks so much for the tutorial.

    I am however having trouble getting it to return anything other than ‘0’ into the second category selection box. No matter what, it just returns ‘0’.

    Any thoughts on this? I think it must be in the functions.php code snippet, but I’m not sure how/why it’s doing it.

    Thanks
    Luke

    -1
    • Thunder

      Wednesday, March 9th, 2011 17:31

      31

      Will just one person who has gotten this to work please come back and show us the code?

      I never fail to eventually get all kinds of modifications working.

      2 days now I have spent hour after hour with all possible permutations and I get nothing but a 0 or -1.

      I am testing on a localhost and even gave the complete http url to the admin-ajax.php script. Put the jquery script in the actual header, too.

      I have a virgin WP 3.1 script on PHP 5 and Mysql 5.

      I set up Categories both parent and sub cats and am good to go.

      The first dropdown shows those categories.

      Nothing output but 0 or -1 in the second.

      Adnan, there’s something crucial that is missing!

      But if someone has figured it out please share the exact script that works.

      +1
      • Adnan

        Tuesday, March 15th, 2011 08:36

        34

        @Thunder I’m gonna post the files used in this example. So, please check them! if they doesn’t work still. then send me your live link of that page. I will see what is going wrong with it.

        +1
    • Muhammad Adnan

      Tuesday, March 15th, 2011 09:42

      33

      Here is the download link for the files used in this tutorial
      http://www.imblog.info/implement-ajax.zip

      0
      • Sjaakie

        Friday, June 10th, 2011 14:15

        40

        Thank you very much! I finally got it working with these files. Like other people here ive been working with this tutorial for a few hours with no result. Thank you for posting these.

        0
  • Thunder

    Wednesday, March 9th, 2011 00:26

    28

    I have worked for a full day and have seen nothing but the first selector field and a disabled field.

    I would like to see the full code completely assembled in the template and the full code sitting in the function.php file. I have worked with WordPress for six years. I have a good working knowledge of modifying it but there are some pieces of explanation missing that make my multitude of guesses futility.

    Particularly just how step 4 fits. The javascript says nothing about wrapping it in javascript tags but I assume it is, but where on the template page it is integrated in relation to the second field value is unclear, although I have tried numerous configurations.

    This tutorial was left unfinished.

    0
  • anthony

    Monday, February 14th, 2011 04:01

    25

    HI All,

    Would like to check with you all, may i know where should i place the code in step 4.

    Thank you.

    0
  • Phillip Bryan

    Tuesday, January 25th, 2011 00:27

    24

    Fantastic. This is just what I needed. With a couple of tweaks I was able to add AJAX to my blog, and I love it.

    Thanks!

    0
  • Brett Widmann

    Tuesday, December 14th, 2010 16:27

    23

    This has been very helpful! Thanks for the great tutorial.

    +3
  • noel

    Wednesday, November 24th, 2010 14:41

    22

    i somehow get the following error corresponding the step 4 of your tutorial ($(function(){… ):

    error: $ is not a function

    i probably missed where and how to add the Jquery code.

    +7
  • Yummy

    Thursday, November 11th, 2010 13:30

    21

    One word for this post. AWESOME.

    This helped me implement this feature in a blog recently. Keep writing. This is truly great work.

    0
  • Tim

    Monday, November 1st, 2010 21:06

    20

    did you ever get to the bottom of the -1 0 issue I’m getting the same thing on a site I’m building at the minute for no obvious reason?

    0
  • Leonardo

    Monday, September 27th, 2010 14:36

    19

    Thanks for this really helpful tutorial! I have some questions about doing this with the content of a page. Is it possible? Loading the header/sidebar/footer if there’s nothing to change on them doesn’t make much sense…

    Thanks for the help again!

    0
  • jinesh

    Monday, August 2nd, 2010 08:16

    15

    hi,

    I am a new for wordpress, and i want to know that where to make this implement_ajax.php file in theme folder?

    Please help me….

    Thanks in advance

    0
  • John J. Camilleri

    Tuesday, July 27th, 2010 15:36

    14

    One thing I noticed is that you cannot write an AJAX handler ONLY for the frontend;
    In other words:
    `add_action(‘wp_ajax_nopriv_my_special_ajax_call’, ‘implement_ajax’);`
    will not work without the
    `add_action(‘wp_ajax_my_special_ajax_call’, ‘implement_ajax’);`

    Or rather everything will seem to be fine, but you will always get a response of 0.

    0
  • gunter

    Friday, July 23rd, 2010 20:05

    13

    Hi,
    I keep getting -1 as the returned value. The id of the selected category is passed on to the javascript but the return from the function is -1. Any help would be appreciated.
    Cheers

    0
    • Darren

      Tuesday, August 17th, 2010 01:45

      16

      I’m actually getting the same problem with the “-1″ showing up.

      At first I thought it was WordPress saying there was no data to return or a similar error. It turns out I was returning the data in the PHP function when what I needed to do was echo it. As such, the data returns and displays fine.

      It seems the “-1″ is related to whether or not the user is logged in. When I logged in, it changed to “0”. Still searching for a solution.

      0
      • pandikamal

        Tuesday, February 22nd, 2011 14:47

        26

        hi,
        I’m actually getting the same problem with the “-1″ showing up and after login it will showing 0.
        And so removed the die() and also it will be show the same.

        Please help me how to hook the ajax action in functions.php file

        0
        • David

          Saturday, February 26th, 2011 06:17

          27

          I haven’t gone through and implemented the code, so I can’t answer you directly, but

          For Anyone who’s having trouble, here’s a much more thorough article about implementing ajax by wphardcore.com
          http://www.wphardcore.com/2010/5-tips-for-using-ajax-in-wordpress/

          Cheers!

          PS He also quickly responds to every comment which is a huge plus!

          0
    • Darren

      Tuesday, August 17th, 2010 01:53

      17

      Ah, I figured out why it was showing the “-1″ and “0”. I had neglected to put in the “die();” at the end of the PHP function.

      If your data is not showing up, it is likely due to mis-named functions or a typo in your code, probably not related to the “-1″/”0″ issue you’re seeing.

      0
  • Sovit Tamrakar

    Sunday, July 11th, 2010 14:22

    12

    Thanks, this helped me a lot. :)

    0
  • Abhinav

    Friday, May 14th, 2010 06:04

    11

    Hi

    I followed the tutorial. It was really helpful. I am not sure what am i doing wrong because my ajax call made successfully but it always return back “0”. Can you please suggest me how to debug it?

    Thanks

    0
  • Tim

    Friday, April 23rd, 2010 22:48

    10

    Nice. Am going to try this out. Isn’t adding code to functions.php a bad practise? Isn’t there an alternative for that?

    0
    • zm

      Sunday, August 29th, 2010 17:24

      18

      that’s actually best practice. adding content to functions.php in your themes folder.

      0
  • Beppe

    Friday, April 2nd, 2010 15:00

    9

    Hello, very great tutorial. I would ask if is possible have four dropdown menus…? Many Thanks!

    0
  • Chris

    Tuesday, March 30th, 2010 19:25

    8

    Great tut my friend, You can also checkout the article from Chris Coyier from CSS-tricks from last month: “AJAXing a WordPress Theme” http://bit.ly/aQjo9G

    +1
  • Jake Goldman

    Tuesday, March 30th, 2010 18:25

    7

    To prevent conflicts with other jQuery enabled scripts, you should really use wp_enqueue_script above the header to load jQuery.

    +2
  • Dragon Blogger

    Tuesday, March 30th, 2010 16:38

    6

    Really nice tutorial, does adding ajax add overhead to blog load times? If you have particularly large amounts of categories? I also need to read more about creating wordpress templates.

    +2
  • Squiders

    Tuesday, March 30th, 2010 19:51

    5

    great tips, has got me thinking of plans!

    0
  • ebsoft

    Tuesday, March 30th, 2010 08:25

    4

    Nice tutorial
    I hope can implement ajax in my blog
    Thank you

    0
  • Rilwis

    Tuesday, March 30th, 2010 11:21

    3

    Nice tutorial. I like this type: step-by-step, code and screenshots included.

    But in this post, is it a mistake when you name the action “wp_ajax_nopriv_my_special_ajax_call” while in the code above you make a request with data: “data:’action=my_special_action&main_catid=’ + $mainCat”? I think it should be “wp_ajax_nopriv_my_special_action”.

    0
    • Adnan

      Tuesday, March 15th, 2011 08:33

      32

      Yes, it is a mistake. I’m gonna post the files used in this example. So, please check them!

      0
  • emano

    Monday, March 29th, 2010 20:36

    2

    very useful guide! great! :)

    +2
  • Lena Tailor

    Monday, March 29th, 2010 16:15

    1

    Appreciate Efforts.

    Great post, I am planing on implementing it on my personal Blog.. Tx

    0

Comments are closed.

54.227.171.163 - unknown - unknown - US