AJAX in WordPress

Introduction

AJAX = Asynchronous JavaScript and XML

AJAX is not a programming language, but a way to use existing standards, AJAX is the art of exchanging data with a web-server, and updating parts of a web page – without reloading the whole page.
Ajax-vivacity
Here is a basic example of how we use AJAX in WordPress.
It explains how to take a variables from JavaScript and pass it to a PHP function,  and then pass it back to the JavaScript.

For using this you must know how to enqueue JavaScript in WordPress.
JavaScriptCode

//PS: you may need to add jQuery Library in your theme for using this in some cases, but in admin side, jQuery is already added.

jQuery(document).ready(function($) {

// here you can get any user input or can use variables that need to send to Ajax, I used a simple static variable, but you can use your own and can get them dynamically
var first_name= 'Vivacity';
var last_name= 'InfoTech';

// A simple ajax request "ajaxurl" in WordPressyou need not to worry about this, WordPress handles it automatically
$.ajax({
url: ajaxurl,
data: {
'action':'your_function_name', //you can use anything you want
'firstname' : first_name,
'lastname' : last_name
}, success:function(data) { // This outputs the result of the ajax request being made console.log(data); }, error: function(errorThrown){ console.log(errorThrown);//loggin errors in browser console } }); });

PHP Code


function your_function_name() {

// The $_POST contains all the data sent via ajax ($_REQUEST can also be used)
if ( isset($_POST) ) {

$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];

// you can do any programming of variables here, like I did simple to concatinate two strings

$fullname= $firstname +  lastname

// Now you can return result back to the javascript function, that will be returned in the response
echo $fullname;

}

// Always use exit() in functions when you do ajax
exit();
}

add_action( 'wp_ajax_your_function_name', 'your_function_name' );
// Please use "wp_ajax_" here for Ajax based function hooks

Advertisements