{"id":500,"date":"2016-06-19T14:06:40","date_gmt":"2016-06-19T14:06:40","guid":{"rendered":"https:\/\/www.joetannorella.com\/?p=500"},"modified":"2022-05-13T05:02:48","modified_gmt":"2022-05-13T05:02:48","slug":"wordpress-ajax-tutorial-use-ajax-wordpress-theme-template","status":"publish","type":"post","link":"https:\/\/www.joetannorella.com\/wordpress-ajax-tutorial-use-ajax-wordpress-theme-template\/","title":{"rendered":"WordPress AJAX tutorial – how to use AJAX in a WordPress theme or template"},"content":{"rendered":"

Edit: the output of this tutorial can be seen with the ‘agree’ and ‘disagree’ buttons here:\u00a0http:\/\/www.youthenme.com\/sites\/review\/<\/a><\/p>\n

I’m fairly experienced with using AJAX and\u00a0its various jQuery shorthand implementations, but having never implemented AJAX into a WordPress theme I’ve had to do quite a bit of Googling.<\/p>\n

I’m writing this post to show how I’ve implemented AJAX into WordPress this time around, and also to highlight some of the quirks. You can also view article<\/a> to know the things to look out for while using AJAX in a WordPress theme.<\/p>\n

How AJAX works in WordPress<\/h2>\n

It’s quite simple, but there’s an added layer compared to how you’d usually implement it. All AJAX calls get routed through the following URL:<\/p>\n

 wp-admin\/admin-ajax.php <\/pre>\n

The way WordPress knows where to direct your AJAX call is via the ‘action’ parameter that your pass into the call. Here’s what that looks like:<\/p>\n

\r\n\r\n$.ajax({\r\n type:&amp;quot;POST&amp;quot;,\r\n url: ajaxurl,\r\n data: {\r\n  action: &amp;quot;review_vote_ajax_request&amp;quot;,\r\n },\r\n success:function(data){\r\n  alert(data);\r\n },\r\n error: function(errorThrown){\r\n  alert(errorThrown);\r\n }\r\n});\r\n<\/pre>\n

You will notice that the ‘url’ parameter contains a variable called ‘ajaxurl’. This is globally set in my header.php file. It’s set there because this allows me to define the variable globally using a WordPress function via PHP. So in my header.php file I have this:<\/p>\n

\r\n\r\n&amp;lt;script type=&amp;quot;text\/javascript&amp;quot;&amp;gt;\r\nvar ajaxurl = &amp;quot;&amp;lt;?php echo admin_url( 'admin-ajax.php' ); ?&amp;gt;&amp;quot;;\r\n&amp;lt;\/script&amp;gt;\r\n\r\n<\/pre>\n

All this looks like then when it echoes out is:<\/p>\n

 var ajaxurl = &amp;quot;my-website.com\/wp-admin\/admin-ajax.php&amp;quot; <\/pre>\n

So the AJAX call gets sent to \/wp-admin\/admin-ajax.php, and then the appropriate function gets called based on the ‘action’ parameter that you pass through via AJAX. In the case above, on the server side I want to process the AJAX call via a function called ‘review_vote_ajax_request’.<\/p>\n

Because I envisage myself doing quite a few different AJAX calls in this particular theme, and because it’s best practice regardless, I decided to put the PHP processing function into its own file called \/inc\/ajax.php. Then I include this into my functions.php file. I do this to keep everything more organised, otherwise, as with most WordPress stuff that I see, my project ends up being a bunch of functional spaghetti code!<\/p>\n

Warning<\/strong><\/p>\n

One extremely silly\u00a0error I made here though, which is not related to WordPress development<\/a> but to my own stupidity and tiredness while coding, was that I actually forgot to include my ajax.php file into my functions.php file. This meant that the server side function associated with my AJAX call actually never existed. It took 2 hours of debugging until I realised – what a nightmare!<\/p>\n

The reason I’m adding this warning into this article, is because it actually forced me to learn a subtle nuance of WordPress’ AJAx implementation. The function essentially didn’t exist, but WordPress was returning ‘0’ to the AJAX call response. It didn’t return anything like ‘function doesn’t exist’ etc. – it simply returned an integer of 0. This is the reason it took me so long to debug – it wasn’t immediately obvious that my function wasn’t even included as it would be if this wasn’t an AJAX call.<\/p>\n

The server side code<\/h2>\n

There are a few things to watch out for in your PHP function that takes the AJAX call.<\/p>\n

Logged in or logged out<\/h3>\n

As a security precaution, WordPress requires you to explicitly make\u00a0the AJAX function accessible to non-authenticated users. To enable the AJAX call to non-auth users, you must include the following action:<\/p>\n

\r\n\r\nadd_action( 'wp_ajax_nopriv_review_vote_ajax_request', 'review_vote_ajax_request' );\r\n\r\n<\/pre>\n

Don’t forget to\u00a0replace\u00a0‘_review_vote_ajax_request’ with your own function name.<\/p>\n

You also need to include the action to explicitly enable this for authenticated users:<\/p>\n

\r\n\r\nadd_action( 'wp_ajax_review_vote_ajax_request', 'review_vote_ajax_request' );\r\n\r\n<\/pre>\n

Kill the function<\/h3>\n

You must include the following at the end of your PHP AJAX function:<\/p>\n

\r\n\r\nwp_die();\r\n\r\n<\/pre>\n

Echo not return<\/h3>\n

I’m used to returning my AJAX responses from the server in Laravael where I’ll ‘return’ the response. However you must echo out your response back to AJAX, instead of returning it.<\/p>\n

The final code<\/h2>\n

Here’s my javascript:<\/p>\n

\r\n\r\njQuery(function($) {\r\n\r\n$('body').on('click', '.review-helpful-answer', function(e) {\r\ne.preventDefault();\r\n\r\nvar $reviewId = $(this).attr('data-review-id');\r\n\r\nvar post_id = $(this).data('id');\r\n$.ajax({\r\ntype:&amp;quot;POST&amp;quot;,\r\nurl: ajaxurl,\r\ndata: {\r\naction: &amp;quot;review_vote_ajax_request&amp;quot;,\r\npost_id: post_id\r\n},\r\nsuccess:function(data){\r\nalert(data);\r\n},\r\nerror: function(errorThrown){\r\nalert(errorThrown);\r\n}\r\n});\r\n\r\n})\r\n\r\n});\r\n\r\n<\/pre>\n

And the PHP function:<\/p>\n

\r\n\r\nfunction review_vote_ajax_request() {\r\n\r\n\/\/ do what you want with the variables passed through here\r\n\r\n$post_id = $_REQUEST['post_id'];\r\n\r\necho $post_id;\r\n\r\nwp_die();\r\n}\r\n\r\nadd_action( 'wp_ajax_nopriv_review_vote_ajax_request', 'review_vote_ajax_request' );\r\nadd_action( 'wp_ajax_review_vote_ajax_request', 'review_vote_ajax_request' );\r\n\r\n<\/pre>\n

 <\/p>\n","protected":false},"excerpt":{"rendered":"

Edit: the output of this tutorial can be seen with the ‘agree’ and ‘disagree’ buttons here:\u00a0http:\/\/www.youthenme.com\/sites\/review\/ I’m fairly experienced with using AJAX and\u00a0its various jQuery shorthand implementations, but having never implemented AJAX into a WordPress theme I’ve had to do quite a bit of Googling. I’m writing this post to show how I’ve implemented AJAX…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[7],"tags":[28],"yoast_head":"\nWordpress AJAX tutorial - how to use AJAX in a Wordpress theme or template - JoeTannorella.com<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.joetannorella.com\/wordpress-ajax-tutorial-use-ajax-wordpress-theme-template\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Wordpress AJAX tutorial - how to use AJAX in a Wordpress theme or template - JoeTannorella.com\" \/>\n<meta property=\"og:description\" content=\"Edit: the output of this tutorial can be seen with the ‘agree’ and ‘disagree’ buttons here:\u00a0http:\/\/www.youthenme.com\/sites\/review\/ I’m fairly experienced with using AJAX and\u00a0its various jQuery shorthand implementations, but having never implemented AJAX into a WordPress theme I’ve had to do quite a bit of Googling. I’m writing this post to show how I’ve implemented AJAX...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.joetannorella.com\/wordpress-ajax-tutorial-use-ajax-wordpress-theme-template\/\" \/>\n<meta property=\"og:site_name\" content=\"JoeTannorella.com\" \/>\n<meta property=\"article:published_time\" content=\"2016-06-19T14:06:40+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-05-13T05:02:48+00:00\" \/>\n<meta name=\"author\" content=\"admin\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.joetannorella.com\/wordpress-ajax-tutorial-use-ajax-wordpress-theme-template\/\",\"url\":\"https:\/\/www.joetannorella.com\/wordpress-ajax-tutorial-use-ajax-wordpress-theme-template\/\",\"name\":\"Wordpress AJAX tutorial - how to use AJAX in a Wordpress theme or template - JoeTannorella.com\",\"isPartOf\":{\"@id\":\"https:\/\/www.joetannorella.com\/#website\"},\"datePublished\":\"2016-06-19T14:06:40+00:00\",\"dateModified\":\"2022-05-13T05:02:48+00:00\",\"author\":{\"@id\":\"https:\/\/www.joetannorella.com\/#\/schema\/person\/84eafed4ad6cd6934b006e371c06c7ae\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.joetannorella.com\/wordpress-ajax-tutorial-use-ajax-wordpress-theme-template\/\"]}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.joetannorella.com\/#website\",\"url\":\"https:\/\/www.joetannorella.com\/\",\"name\":\"JoeTannorella.com\",\"description\":\"Web Development | Digital Marketing | Business\/Startups | Analytics\/data\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.joetannorella.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.joetannorella.com\/#\/schema\/person\/84eafed4ad6cd6934b006e371c06c7ae\",\"name\":\"admin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.joetannorella.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/257001162d06da1a465f242dfa80dd7b?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/257001162d06da1a465f242dfa80dd7b?s=96&d=mm&r=g\",\"caption\":\"admin\"},\"url\":\"https:\/\/www.joetannorella.com\/author\/admin\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Wordpress AJAX tutorial - how to use AJAX in a Wordpress theme or template - JoeTannorella.com","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.joetannorella.com\/wordpress-ajax-tutorial-use-ajax-wordpress-theme-template\/","og_locale":"en_US","og_type":"article","og_title":"Wordpress AJAX tutorial - how to use AJAX in a Wordpress theme or template - JoeTannorella.com","og_description":"Edit: the output of this tutorial can be seen with the ‘agree’ and ‘disagree’ buttons here:\u00a0http:\/\/www.youthenme.com\/sites\/review\/ I’m fairly experienced with using AJAX and\u00a0its various jQuery shorthand implementations, but having never implemented AJAX into a WordPress theme I’ve had to do quite a bit of Googling. I’m writing this post to show how I’ve implemented AJAX...","og_url":"https:\/\/www.joetannorella.com\/wordpress-ajax-tutorial-use-ajax-wordpress-theme-template\/","og_site_name":"JoeTannorella.com","article_published_time":"2016-06-19T14:06:40+00:00","article_modified_time":"2022-05-13T05:02:48+00:00","author":"admin","twitter_misc":{"Written by":"admin","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.joetannorella.com\/wordpress-ajax-tutorial-use-ajax-wordpress-theme-template\/","url":"https:\/\/www.joetannorella.com\/wordpress-ajax-tutorial-use-ajax-wordpress-theme-template\/","name":"Wordpress AJAX tutorial - how to use AJAX in a Wordpress theme or template - JoeTannorella.com","isPartOf":{"@id":"https:\/\/www.joetannorella.com\/#website"},"datePublished":"2016-06-19T14:06:40+00:00","dateModified":"2022-05-13T05:02:48+00:00","author":{"@id":"https:\/\/www.joetannorella.com\/#\/schema\/person\/84eafed4ad6cd6934b006e371c06c7ae"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.joetannorella.com\/wordpress-ajax-tutorial-use-ajax-wordpress-theme-template\/"]}]},{"@type":"WebSite","@id":"https:\/\/www.joetannorella.com\/#website","url":"https:\/\/www.joetannorella.com\/","name":"JoeTannorella.com","description":"Web Development | Digital Marketing | Business\/Startups | Analytics\/data","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.joetannorella.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.joetannorella.com\/#\/schema\/person\/84eafed4ad6cd6934b006e371c06c7ae","name":"admin","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.joetannorella.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/257001162d06da1a465f242dfa80dd7b?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/257001162d06da1a465f242dfa80dd7b?s=96&d=mm&r=g","caption":"admin"},"url":"https:\/\/www.joetannorella.com\/author\/admin\/"}]}},"_links":{"self":[{"href":"https:\/\/www.joetannorella.com\/wp-json\/wp\/v2\/posts\/500"}],"collection":[{"href":"https:\/\/www.joetannorella.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.joetannorella.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.joetannorella.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.joetannorella.com\/wp-json\/wp\/v2\/comments?post=500"}],"version-history":[{"count":11,"href":"https:\/\/www.joetannorella.com\/wp-json\/wp\/v2\/posts\/500\/revisions"}],"predecessor-version":[{"id":552,"href":"https:\/\/www.joetannorella.com\/wp-json\/wp\/v2\/posts\/500\/revisions\/552"}],"wp:attachment":[{"href":"https:\/\/www.joetannorella.com\/wp-json\/wp\/v2\/media?parent=500"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.joetannorella.com\/wp-json\/wp\/v2\/categories?post=500"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.joetannorella.com\/wp-json\/wp\/v2\/tags?post=500"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}