Using AJAX With PHP on Your WordPress Site Without a Plugin
Today Discussed Using Ajax with php on your wordpress site without a plugin. It enables websites to load content into various elements without refreshing the page. This may not seem like a huge feature list but it allows us to do so much.
How AJAX Works
- You specify information to send
- You configure the Ajax call
- The XMLHttpRequest object is used to send the data to the server
- The server response is returned and can be used by your JS code
- Ajax is most commonly used through jQuery wrapper functions. If you would like to learn Ajax without jQuery I suggest taking a look at the W3Schools Tutorial. Here we’ll be looking at the jQuery functions only.
add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );
function ajax_test_enqueue_scripts() {
wp_enqueue_script( 'test', plugins_url( '/test.js', __FILE__ ), array('jquery'), '1.0', true );
}
Creating the Ajax Call
jQuery(document).ready( function($) {
$.ajax({
url: "http://yourwebsite.com",
success: function( data ) {
alert( 'Your home page has ' + $(data).find('div').length + ' div elements.');
}
})
})
Storing And Displaying Our Data
We’ll be storing the number of “loves” a post has received in a meta field in the database, let’s call it post_love. The value of this field will be displayed under each post in the single page, here’s how:
add_filter( 'the_content', 'post_love_display', 99 );
function post_love_display( $content ) {
$love_text = '';
if ( is_single() ) {
$love = get_post_meta( get_the_ID(), 'post_love', true );
$love = ( empty( $love ) ) ? 0 : $love;
$love_text = '<p class="love-received"><a class="love-button" href="#" data-id="' . get_the_ID() . '">give love</a><span id="love-count">' . $love . '</span></p>';
}
return $content . $love_text;
}