How to Pass WordPress Data to AJAX

In this post you will learn how to use AJAX in WordPress, what Asynchronous Data Exchange is and why it is useful.

Step 1: Write the PHP

First of all is to understand that JavaScript can’t call a specific php function, what it does is to call the entire php file. WordPress allows to call a function through the hook system ‘add_action(‘wp_ajax_hook_name’, ‘function_name’)’.

function function_name(){

//Your code goes here//

echo json_encode($data);

die();

}

To send the data you just need to do an echo. A good practice is to encode it into a JSON, so when you work with the data in the JS you can transform it into an array.

wp_ajax returns a ‘0’ so is important to end the php function with ‘die()’

You can locate the php function anywhere as long as the file is referenced in the index.php

include_once ‘file_path.php’;

Step 2: Write AJAX

Ajax is a jQuery function that allows an asynchronous data exchange with a server. It allows to update parts of a web page without reloading. [Read more about asynchronous data exchange below or click here]

To use jQuery in wordpress you need to declare a function so it knows you are going to use the jQuery library.

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

//Your code goes here//

}

This means that when the document is loaded it will run the anonymous function with just the dollar symbol as parameter, which we can use to replace the word ‘jQuery’. An Ajax function can be called at the when the script loads or as an event to some action (clicking a button, changing the value of an input…).

After this all is left to do is write the Ajax function which needs some parameters.

  • url of the file, in wordpress is constant, you need to call the admin-ajax.php which absolute path is ‘/wp-admin/admin-ajax.php’.
  • data: This has to be an action that contains a string with the name of the hook written in the php file and every data you want to send to the php.
  • type: Type of the request either post or get.
  • datatype: Not mandatory. It is to let the ajax function know in what format the information arrives.
  • success: If the ajax function did it’s job this will run a function which parameter will be the server response.
  • error: Not mandatory. If the ajax function failed for some reason this will run a function.
$.ajax({
url: ‘/wp-admin/admin-ajax.php’,
type: “post”,
data: {
action: ‘hook_name’,
},
success: function (response) {

let dataFromServer = JSON.parse(response);

//Your code goes here//

},

error: function(){

//Your code goes here//

}

Step 3: Testing

After writing the ajax function all is left to do is to test.

Example

PHP File

function call_to_server(){

$tblPrefix = “wp_”; //Use your wordpress table prefix
global $wpdb; //Wordpress global access to the database connection
$query = “SELECT * FROM ” . $tblPrefix . “posts”; //String variable with the query you wish to use

//note, “posts” is only used for illustration purposes: wordpress provides access to posts tablem using the global variable global ‘$post’

$db_result = $wpdb->get_results($query); //The DB sends the result of the query and saves them into a variable

$data = array(); //Array declaration to save the data

foreach ($db_result as $row) { //Start loop | The DB response is not an array but an object, with this loop we can transform the object into an array which is something a developer can work with easier.
$data[] = $row;
}//End loop

echo json_encode($data); //Send the data to the Ajax function that has triggered the function encoded into a JSON object
die(); //Ending the code with the die() function so ‘admin-ajax.php’ stops sending data

}

add_action(‘wp_ajax_get_db_data’, ‘call_to_server’); //Hook to trigger the function ‘call_to_server’. If there is another function in the file this will ignore them and just trigger the ‘call_to_server’ function

 

JS File

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

$.ajax({//Start ajax petition
url: ‘/wp-admin/admin-ajax.php’, //Path to let WordPress know is an Ajax function
type: “post”,
data: {
action: ‘get_db_data’, //Name of the hook that calls the php function
},
success: function (response) {

let dbData = JSON.parse(response); //Transform the database response into an array of JSON OBJECTS.

for(let i = 0; i < dbData.length; i++){

console.log(dbData[i]); //Display through the browser console the data from the array

} //End loop

},//End success

error: function(){

alert(‘Error with the Ajax petition’); //Alert if the ajax petition goes wrong

});//End Ajax function

});//End of jQuery onload function

Asynchronous Data Exchange

Asynchronous programming is a technique that enables your program to start a potentially long-running task, and then rather than having to wait until that task has finished, to be able to continue to be responsive to other events while the task runs. Once the task is completed, your program is presented with the result.

Many functions provided by browsers, and especially the most interesting ones, can potentially take a long time, and are therefore asynchronous. For example:

  • making HTTP requests with fetch();
  • accessing the user’s camera or microphone with getUserMedia();
  • asking the user to select files for you to access using showOpenFilePicker();

So even though you may not have to implement your own asynchronous functions very often, you are very likely to need to use them correctly.

Conclusion

As you have read in this post, it is not that hard to use AJAX and it is also often beneficial to use it!

 

If you would like to view another WordPress Tutorial by Arrow Design (Correctly enqueue javascript and css in WordPress) please click here

 

Arrow Design, based in Dublin, Ireland, provides quality website design services in Dublin and beyond at affordable prices. If you would like help with implementing the above code, or any wordpress website development project, contact us. We love website design and it shows! We provide custom wordpress plugin development, website design training and lots more.

We do it all, so you don’t have to!

enqueue scripts
enqueue scripts
enqueue scripts

…We do more, so you can do less 🙂

 

Leave a message and we will be straight back to you!

Pin It on Pinterest

Share This