{"id":138584,"date":"2022-01-02T08:00:32","date_gmt":"2022-01-02T08:00:32","guid":{"rendered":"http:\/\/premium.wpmudev.org\/blog\/?p=138584"},"modified":"2022-01-02T08:00:32","modified_gmt":"2022-01-02T08:00:32","slug":"using-ajax-with-wordpress","status":"publish","type":"post","link":"https:\/\/wpmu-dev.pro\/blog\/using-ajax-with-wordpress\/","title":{"rendered":"Using AJAX and PHP in Your WordPress Site Creating Your Own Plugin"},"content":{"rendered":"<p>Good design is invisible! It\u2019s like an air conditioner set on automatic temperature control. Until you feel too hot or cold, you don\u2019t pay any attention to it, concentrating instead on the task at hand, or just enjoying your time.<\/p>\n<p>For users surfing the web, Ajax is like an automatic air conditioner. It makes websites smoother and faster to use, resulting in a pleasurable experience. And most importantly, it just works!<\/p>\n<p>If you prefer a video instead, you&#8217;re in luck!<\/p>\n<p><span class=\"embed-youtube\" style=\"text-align:center; display: block;\"><span class=\"embed-youtube-lazy-id dev-hidden\">glH4b6-jyzQ<\/span><\/span><\/p>\n<p>Learn how to use Ajax Easily:<\/p>\n<ul>\n<li><a href=\"#WhatisAjax\">What is Ajax Exactly?<\/a><\/li>\n<li><a href=\"#AjaxBasics\">The Basics of Ajax<\/a><\/li>\n<li><a href=\"#SkillsNeeded\">Skills Needed to work with Ajax in WordPress<\/a><\/li>\n<li><a href=\"#AjaxProcess\">Process of using Ajax in WordPress<\/a><\/li>\n<li><a href=\"#AjaxPlugins\">Notable WordPress Plugins Which Use Ajax<\/a><\/li>\n<\/ul>\n<h3 id=\"WhatisAjax\">What is Ajax Exactly?<\/h3>\n<p>Ajax is a web development technique that stands for <em><strong>A<\/strong>synchronous <strong>J<\/strong>avaScript <strong>A<\/strong>nd <strong>X<\/strong>ML<\/em>. It\u2019s used to create dynamic web applications that are interactive and fun. With Ajax, you don\u2019t have to wait for the web page to reload to see a change. Everything\u2019s taken care of automatically in the background without disrupting what you\u2019re doing, thereby enhancing your user experience.<\/p>\n<figure class=\"wp-caption aligncenter\" data-caption=\"true\"><video loop muted autoplay playsinline class='dev-html5-video'><source src=\"https:\/\/wpmu-dev.pro\/blog\/wp-content\/uploads\/2015\/03\/Google-Autocomplete-Suggestions-735px.webm\" type=\"video\/webm\"><source src=\"https:\/\/wpmu-dev.pro\/blog\/wp-content\/uploads\/2015\/03\/Google-Autocomplete-Suggestions-735px.mp4\" type=\"video\/mp4\"><\/video><figcaption class=\"wp-caption-text\">Ajax at work!<\/figcaption><\/figure>\n<p>You\u2019ve probably come across Ajax on the web already. <a href=\"https:\/\/www.blog.google\/products\/search\/how-google-autocomplete-works-search\/\" rel=\"noopener\" target=\"_blank\">Google Search\u2019s autocomplete feature<\/a> is perhaps the most popular one. Google Maps is another. Live refresh of tweets, Facebook comments, Reddit posts, YouTube likes, all these incredible user experiences are made possible thanks to Ajax and related technologies.<\/p>\n<p>In this post, I\u2019ll give you a quick intro to Ajax, list its advantages, explain how it works in WordPress, and then we\u2019ll dive headfirst into creating a simple WordPress Ajax Plugin.<\/p>\n<p>Sounds fun? Let\u2019s get started.<\/p>\n<h3 id=\"AjaxBasics\">The Basics of Ajax<\/h3>\n<p>Ajax uses a combination of programming languages such as HTML\/CSS, JavaScript, XML\/JSON, and a server-side scripting language (PHP, ASP.NET, etc.). It works by sending data from the browser to the server, which processes it and sends back a response. This response is used by the browser to update the web page without reloading it.<\/p>\n<p>Here\u2019s how it usually goes:<\/p>\n<ul>\n<li>A user action triggers an event in a browser (like a button click).<\/li>\n<li>The Ajax call activates, which sends a request to the server, using XML\/JSON.<\/li>\n<li>The server-side script processes this request. It can also access the database if it needs to.<\/li>\n<li>The server then sends a response back to the browser.<\/li>\n<li>A second JavaScript function, called a callback function, receives the response and updates the web page.<\/li>\n<\/ul>\n<div  class=\"wpdui-pic-regular  \"><img loading=\"lazy\" decoding=\"async\" class=\"attachment-600x600 size-600x600\" src=\"https:\/\/wpmu-dev.pro\/blog\/wp-content\/uploads\/2015\/03\/AJAX-Basics-101-for-WPMU_DEV.png\" alt=\"infographic illustrating the basics of Ajax\" width=\"600\" height=\"338\" \/><\/div>\n<h3>The Many Advantages of Ajax<\/h3>\n<ol>\n<li>Minimizes bandwidth usage and optimizes network operations, as the servers won\u2019t be required to process loads of data.<\/li>\n<li>Saves time for both the users and the server, as the user can see the response from the server immediately.<\/li>\n<li>Increased performance. Since no full-page data is being sent, Ajax improves the performance, speed, and usability of web pages\/apps.<\/li>\n<li>Increased responsiveness. By eliminating full-page reload, websites will be swifter and highly responsive, thus more user-friendly.<\/li>\n<\/ol>\n<h3 id=\"SkillsNeeded\">Skills Needed to Work with Ajax in WordPress<\/h3>\n<ul>\n<li>Knowledge of HTML, CSS, and JavaScript (jQuery is enough)<\/li>\n<li>Basic familiarity with XML or JSON data interchange formats<\/li>\n<li>Know-how of PHP for server-side scripting<\/li>\n<\/ul>\n<p>If your jQuery or PHP knowledge is touch and go, don\u2019t fret! You can still follow the tutorial logic. Feel free to hop into the comments section if you\u2019re stuck or need help with something :)<\/p>\n<h3>Intro to Ajax in WordPress<\/h3>\n<p>The core of WordPress already uses Ajax, but only in the admin screens. For instance, when you\u2019re moderating comments or adding\/deleting items from categories or posts, you can see instant updates thanks to Ajax. It\u2019s also the tech behind the much loved auto-save functionality.<\/p>\n<p>Ajax is most commonly used with jQuery functions on WordPress, as it\u2019s much simpler when compared to VanillaJS. Moreover, WordPress core already comes loaded with the jQuery library.<\/p>\n<h2 id=\"AjaxProcess\">Here\u2019s what the process for using Ajax in WordPress looks like:<\/h2>\n<ol>\n<li>The user triggers an Ajax request, which is first passed to the <em>admin-ajax.php<\/em> file in the <em>wp-admin<\/em> folder.<\/li>\n<li>The Ajax request needs to supply at least one piece of data (using the GET or POST method). This request is called the <em>action<\/em>.<\/li>\n<li>The code in <em>admin-ajax.php<\/em> uses the <em>action<\/em> to create two hooks: <em>wp_ajax_youraction<\/em> and <em>wp_ajax_nopriv_youraction<\/em>. Here, <em>youraction<\/em> is the value of the GET or POST variable <em>action<\/em>.<\/li>\n<li>The first hook <em>wp_ajax_youraction<\/em> executes only for logged-in users, while the second hook <em>wp_ajax_nopriv_youraction<\/em> caters exclusively for logged-out users. If you want to target all users, you need to fire them both separately.<\/li>\n<li>Plan the hook functions for <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Glossary\/Graceful_degradation\" rel=\"noopener\" target=\"_blank\">graceful degradation<\/a>. It ensures that your code will work even on browsers with JavaScript disabled.<\/li>\n<\/ol>\n<div  class=\"wpdui-pic-regular  \"><img loading=\"lazy\" decoding=\"async\" class=\"attachment-600x600 size-600x600\" src=\"https:\/\/wpmu-dev.pro\/blog\/wp-content\/uploads\/2015\/03\/AJAX-in-WordPress-A-Simple-Primer.png\" alt=\"Infographic illustrating how Ajax is used with WordPress\" width=\"600\" height=\"338\" \/><\/div>\n<h3>Let\u2019s Create a WordPress Ajax Plugin<\/h3>\n<p>Every great journey begins with a single step, and so does our learning. Let us build a basic WordPress plugin called <em>Post Likes Counter<\/em> with the following features:<\/p>\n<ul>\n<li>Logged-in users can like posts.<\/li>\n<li>The plugin keeps a tally of the total number of post likes and displays them.<\/li>\n<li>The post likes counter is updated instantaneously on the front-end.<\/li>\n<li>Logged-out users will be shown an error message if they attempt to like a post.<\/li>\n<\/ul>\n<p>To start, create an empty WP plugin and activate it. If you need help with this, you can refer to our <a href=\"https:\/\/wpmu-dev.pro\/blog\/wordpress-plugin-development-guide\/\" target=\"_blank\">WordPress plugin development guide<\/a>. WordPress Codex also has a detailed page on <a href=\"https:\/\/developer.wordpress.org\/plugins\/\" rel=\"noopener\" target=\"_blank\">writing a WP plugin<\/a>.<\/p>\n<h3>Find Your Theme\u2019s Post Template<\/h3>\n<p>After that, you need to find your theme\u2019s <em>single.php<\/em> post template. It\u2019s used when a single post is queried, which is where we want our post likes counter to be. This file can be found in the root folder of your active theme. Keep it open for editing.<\/p>\n<h3>Get the Post Template Ready for an Ajax Call<\/h3>\n<p>Let\u2019s create a link here to let users like posts. If a user has JavaScript enabled, it\u2019ll use the JavaScript file we\u2019ll create later; if not, it\u2019ll just follow the link directly. Place the code given below in your <em>single.php<\/em> file.<\/p>\n<div class=\"gist\" data-gist=\"1379ac822720e8c8c1860209a2bfe323\" data-gist-file=\"Ready-AJAX-Call.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/1379ac822720e8c8c1860209a2bfe323.js?file=Ready-AJAX-Call.php\">Loading gist 1379ac822720e8c8c1860209a2bfe323<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>Alternatively, you can add this code to any of the <em>template parts<\/em> your <em>single.php<\/em> file includes. For instance, if you\u2019re using the official <em>Twenty Nineteen<\/em> theme, you can insert this code in your theme\u2019s <em>content-single.php<\/em> file. For testing this plugin code, I inserted it in this file at the very end of its <em>div.entry-content<\/em> section.<\/p>\n<h3>Addressing the Ajax Call Without JavaScript<\/h3>\n<p>Clicking the link created above will take you to the <em>admin-ajax.php<\/em> script, but you won\u2019t see any useful output as you\u2019ve not created any function yet to run your action.<\/p>\n<p>To do that, create a function in your plugin file and add it to the two hooks that were created by WordPress for you. Follow the code shown below:<\/p>\n<div class=\"gist\" data-gist=\"5b77823b65250637eee4396d8abcc5a0\" data-gist-file=\"AJAX-Action-Hook-Plugin-Functions.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/5b77823b65250637eee4396d8abcc5a0.js?file=AJAX-Action-Hook-Plugin-Functions.php\">Loading gist 5b77823b65250637eee4396d8abcc5a0<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>If everything checks out, when a logged-in user clicks the <em>Like this Post<\/em> link, the like counter above it should increase by 1 automatically. For browsers with JavaScript disabled, the page will refresh, but it\u2019ll still show the updated like count.<\/p>\n<p>The function to handle logged-out users doesn\u2019t do much here except for throwing up an error message. It\u2019s only meant to serve as an example. You can, of course, build on this and give your visitors more helpful options.<\/p>\n<h3>Finally, Adding Support for JavaScript<\/h3>\n<p>It\u2019s a good practice to add support for JavaScript towards the end, as it makes things much clearer. To use Ajax on WordPress, you need to enqueue jQuery library as well as your plugin\u2019s custom JavaScript file. For this, go to your plugin and append the following script:<\/p>\n<div class=\"gist\" data-gist=\"c4ba96f5ac2997b294c70c90b82d43d3\" data-gist-file=\"Add-Javascript-AJAX-Support\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/c4ba96f5ac2997b294c70c90b82d43d3.js?file=Add-Javascript-AJAX-Support\">Loading gist c4ba96f5ac2997b294c70c90b82d43d3<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>Once that\u2019s done, it\u2019s time to create the <em>liker_script.js<\/em> JavaScript file. Then you have to upload this file to the location referenced in the previous code (hint: it\u2019s your plugin\u2019s root folder). Here\u2019s the code for <em>liker_script.js<\/em>:<\/p>\n<div class=\"gist\" data-gist=\"9d3183eeca419da10b9ff997ef236b87\" data-gist-file=\"liker_script.js\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/9d3183eeca419da10b9ff997ef236b87.js?file=liker_script.js\">Loading gist 9d3183eeca419da10b9ff997ef236b87<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>The <em>my_user_like()<\/em> function defined in our plugin should send our browser a response as a JSON-encoded result array, which can also be used as a JavaScript object. Using this, we can update the post like count without reloading the web page.<\/p>\n<p>And that\u2019s it! Hurrayyyyyy!<\/p>\n<p>You\u2019ve now enabled Ajax functionality for your plugin. Of course, you can expand on this and add more features as per your liking. Go ahead, tweak it till you make it!<\/p>\n<div  class=\"wpdui-pic-regular  \">\n<figure class=\"wp-caption alignnone\" data-caption=\"true\"><img loading=\"lazy\" decoding=\"async\" class=\"attachment-600x600 size-600x600\" src=\"https:\/\/wpmu-dev.pro\/blog\/wp-content\/uploads\/2015\/03\/Post-Like-Counter-Basic.png\" alt=\"Screenshot showing our simple post like counter on the frontend of a post. &quot;Like this post&quot; link that increases the count each time you click it.\" width=\"600\" height=\"300\" \/><figcaption class=\"wp-caption-text\">Our simple post like counter. You can add styles, animations, and other scripts to level it up.<\/figcaption><\/figure>\n<\/div>\n<h3 id=\"AjaxPlugins\">Notable WordPress Plugins Which Use Ajax<\/h3>\n<p>Need some Ajax inspiration to fire you up? Check out these amazing WordPress plugins that use the power of Ajax to build powerful features and smoother user experiences.<\/p>\n<ol>\n<li><a href=\"https:\/\/wpmu-dev.pro\/blog\/6-lazy-load-plugins-to-make-your-wordpress-site-faster\/\" target=\"_blank\"><strong>Lazy Load Plugins<\/strong><\/a><br \/>\nLazy Loading is a web development technique used to improve initial page loading time. It\u2019s done by <a href=\"https:\/\/wpmu-dev.pro\/blog\/lazy-load-wordpress\/\" target=\"_blank\">delaying the loading of resource-heavy assets<\/a> that aren\u2019t visible to the user in their browser\u2019s viewport. These assets are loaded automatically when the user scrolls down the web page. The <a href=\"https:\/\/wordpress.org\/plugins\/wp-smushit\/\" rel=\"noopener\" target=\"_blank\">free version of Smush<\/a> supports lazy loading.<\/li>\n<li><a href=\"https:\/\/wordpress.org\/plugins\/forminator\/\" rel=\"noopener\" target=\"_blank\"><strong>Forminator<\/strong><\/a><br \/>\nA completely expandable form maker plugin that also supports polls, quizzes, <a href=\"https:\/\/wpmu-dev.pro\/blog\/how-to-build-order-forms-with-payments-for-free-in-wordpress\/\" target=\"_blank\" rel=\"noopener\">order forms with payment options<\/a>, etc. It has an option to enable form submissions with Ajax, making it a seamless experience for the users.<\/li>\n<li><a href=\"https:\/\/wordpress.org\/plugins\/login-with-ajax\/\" rel=\"noopener\" target=\"_blank\"><strong>Login With Ajax<\/strong><\/a><br \/>\nPower your WordPress site with smooth Ajax login and registration effects with this feature-rich plugin. If you\u2019re looking to give your users a better login and registration experience than the default WordPress one, look no further.<\/li>\n<li><a href=\"https:\/\/wordpress.org\/plugins\/wp-postratings\/\" rel=\"noopener\" target=\"_blank\"><strong>WP-PostRatings<\/strong><\/a><br \/>\nThis simple plugin adds an Ajax rating system for your WordPress website\u2019s posts and pages. It also adds shortcode support for the ratings, so that you can display them anywhere you want.<\/li>\n<li><a href=\"https:\/\/wordpress.org\/plugins\/yith-woocommerce-ajax-navigation\/\" rel=\"noopener\" target=\"_blank\"><strong>YITH WooCommerce Ajax Product Filter<\/strong><\/a><br \/>\nAn extremely helpful and powerful plugin for WooCommerce that lets you apply the exact filters you need to display the product variations you\u2019re looking for. Ajax makes sure that it all happens in a jiffy.<\/li>\n<li><a href=\"https:\/\/wordpress.org\/plugins\/ajax-search-lite\/\" rel=\"noopener\" target=\"_blank\"><strong>Ajax Search Lite<\/strong><\/a><br \/>\nA responsive, live search plugin for WordPress, powered by Ajax. It also includes Google autocomplete and keyword suggestions. Give your users a better search experience on your website with this plugin.<\/li>\n<li><a href=\"https:\/\/wordpress.org\/plugins\/simple-ajax-chat\/\" rel=\"noopener\" target=\"_blank\"><strong>Simple Ajax Chat<\/strong><\/a><br \/>\nHave you ever wondered if you could chat with other users on a website, live? This Ajax-powered plugin is the answer to that. It\u2019s mobile compatible and is built to be extremely customizable as per your liking.<\/li>\n<\/ol>\n<p><a href=\"https:\/\/wordpress.org\/plugins\/tags\/ajax\/\" rel=\"noopener\" target=\"_blank\">Head over to WordPress.org\u2019s plugin repository<\/a> for more brilliant Ajax implementations.<\/p>\n<h3>Keep Calm and Ajax On!<\/h3>\n<p>What\u2019s good for the &lt;body&gt; is good for the user and server too, but you need to balance it out. Ajax is a powerful tool in your arsenal to enhance website performance and user experience. But you should only use it where it\u2019s necessary. Always focus on the user experience aspect. It\u2019ll be a bit rough in the beginning, but once you\u2019ve mastered the basics of Ajax, there\u2019s no stopping you!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Ajax is a powerful set of web techniques that enables you to update a web page without reloading the page. Learn all about how to use Ajax with WordPress here.<\/p>\n","protected":false},"author":761786,"featured_media":200720,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"blog_reading_time":"","wds_primary_category":0,"wds_primary_tutorials_categories":0,"footnotes":""},"categories":[557,263],"tags":[9974,1256,390,10881],"tutorials_categories":[],"class_list":["post-138584","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-development","category-tutorials","tag-wordpress","tag-ajax","tag-code","tag-plugin"],"_links":{"self":[{"href":"https:\/\/wpmu-dev.pro\/blog\/wp-json\/wp\/v2\/posts\/138584","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/wpmu-dev.pro\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/wpmu-dev.pro\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/wpmu-dev.pro\/blog\/wp-json\/wp\/v2\/users\/761786"}],"replies":[{"embeddable":true,"href":"https:\/\/wpmu-dev.pro\/blog\/wp-json\/wp\/v2\/comments?post=138584"}],"version-history":[{"count":32,"href":"https:\/\/wpmu-dev.pro\/blog\/wp-json\/wp\/v2\/posts\/138584\/revisions"}],"predecessor-version":[{"id":216264,"href":"https:\/\/wpmu-dev.pro\/blog\/wp-json\/wp\/v2\/posts\/138584\/revisions\/216264"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/wpmu-dev.pro\/blog\/wp-json\/wp\/v2\/media\/200720"}],"wp:attachment":[{"href":"https:\/\/wpmu-dev.pro\/blog\/wp-json\/wp\/v2\/media?parent=138584"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/wpmu-dev.pro\/blog\/wp-json\/wp\/v2\/categories?post=138584"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/wpmu-dev.pro\/blog\/wp-json\/wp\/v2\/tags?post=138584"},{"taxonomy":"tutorials_categories","embeddable":true,"href":"https:\/\/wpmu-dev.pro\/blog\/wp-json\/wp\/v2\/tutorials_categories?post=138584"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}