Here we will learn how to use AJAX in WordPress. We will see how WordPress AJAX works as Beginner level. In this we will pass a variable from Javascript and pass it to WordPress theme function file. After doing necessary process, we will pass the result content back to the Javascript.

We are assumming that you already know how to enqueue javascript, etc.

Send Argument to the function :

Javascript :

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

 //We'll pass this variable to the PHP function example_ajax_request
 var car = 'BMW';

 // This does the ajax request
 $.ajax({
  url: codecanal_ajax_object.ajax_url,
  data: {
   'action':'codecanal_ajax_request',
   'car' : car
  },
  success:function(data) {
  // The OutPut after successfull receiveing content
  console.log(data);
  },
  error: function(errorThrown){
  console.log(errorThrown);
  }
 });
});

 

Implementation of Argument

If you are using AJAX in theme custom coding then put the below code in theme’s function.php file

function codecanal_ajax_request() {

 // The $_REQUEST contains all the data sent via ajax
 if ( isset($_REQUEST) ) {

 // You can check what data is received in the function by debugging it
 // print_r($_REQUEST);

 $car = $_REQUEST['car'];

 // Let's take the data that was sent and do something with it
 // Start the required process you have to do with the received data
 if ( $car == 'BMW' ) {
 $car = 'Audi';
 }

 // We are displaying the result here
 // We can send any type of output in response
 echo $car;
}

// To return to the front page, always finish after echoing the desired content.
die();
}
add_action( 'wp_ajax_codecanal_ajax_request', 'codecanal_ajax_request' );

// For allowing non-logged in users to use AJAX function
// add_action( 'wp_ajax_nopriv_codecanal_ajax_request', 'codecanal_ajax_request' );

/* We can define the AJAX url with using wp_localize_script */
function codecanal_ajax_enqueue() {
 wp_localize_script( 'ajax-script', 'codecanal_ajax_object',
 array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'codecanal_ajax_enqueue' );

 

Do not use normal PHP AJAX in WordPress

Generally most of Php developers who start working in WordPress do this big mistake in using AJAX in WordPress. They simply make new PHP file in theme or plugin directory and simply load “wp-load.php” file in the top of the code. This will work but this is not hack proof and it may be put your site in danger. This will also not give you WordPress system’s default amazing features.

We will also provide the WordPress AJAX pagination tutorial in future.

There are currently no comments.