How To Use Ajax In WordPress
We have already shared a code to help you about passing PHP variables to JavaScript function . Now we are going to share a more practical example by using that code snippet i.e Using Ajax in WordPress
We will recommend to have a look on that code so it will be easy to learn the following tutorial for you. We have written a very basic and simple tutorial that will explain the usage of Ajax in WordPress with the help of admin-ajax.php
Let start our tutorial,
1. Basic WordPress Loop – index.php
[php]
Ajax Response wrapper.
3. Ajax Call – functions.js
We are near to end and here is the code about WordPress Ajax in the functions.js file,
[code lang=”js”]
(function($) {
/** jQuery Document Ready */
$(document).ready(function(){
$( ‘a.ajax-post’ ).off( ‘click’ ).on( ‘click’, function( e ) {
/** Prevent Default Behaviour */
e.preventDefault();
/** Get Post ID */
var post_id = $(this).attr( ‘id’ );
/** Ajax Call */
$.ajax({
cache: false,
timeout: 8000,
url: php_array.admin_ajax,
type: “POST”,
data: ({ action:’theme_post_example’, id:post_id }),
beforeSend: function() {
$( ‘#ajax-response’ ).html( ‘Loading’ );
},
success: function( data, textStatus, jqXHR ){
var $ajax_response = $( data );
$( ‘#ajax-response’ ).html( $ajax_response );
},
error: function( jqXHR, textStatus, errorThrown ){
console.log( ‘The following error occured: ‘ + textStatus, errorThrown );
},
complete: function( jqXHR, textStatus ){
}
});
});
});
})(jQuery);
[/code]
JavaScript code for the WordPress Ajax logic is self-explanatory. Just try it and don’t forget to share your experience in the form of comments.
You may also be interested in our other articles on wordpress variables in javascript , wordpress adding fields to categories , exclude categories from blog wordpress and wordpress get taxonomies for post .
We provide Full Site Editing WordPress themes and plugins fully compatible with Gutenberg, enabling seamless customization and control over your website’s design with intuitive block-based editing for a polished, professional look.
© 2024 DesignOrbital. All rights reserved.
All our WordPress themes & plugins are licensed under the GNU general public license.
Leave a Reply