WordPress Ajax Call Example [Basic & React JS Example]

WordPress Ajax Call Example

If you are searching for a quick and straightforward WordPress Ajax call example, I will quickly show you one of the examples I have recently used in a React WordPress project. 

I presume if you are looking for WordPress Ajax call example you are already familiar on how Ajax works.

Ajax Asynchronous JavaScript And XML

If you are not familiar;  AJAX = Asynchronous JavaScript And XML is a library that allows you to make requests or post to a server some data.

AJAX request can be a GET or POST to an URL like the WordPress admin URL or any other URL.

You can add custom parameters to the data and manipulate it to suit your needs.

AJAX request in WordPress is essentially used to transfer the data between client and server without reloading or refreshing the page.

WordPress Ajax Call Example

Take for example in my recent react WordPress application I need to post the data from the form below to a server and create a custom post type.

wordpress ajax call exampleTo send this data we need to know how WordPress Ajax works and since we are on the front end we need to have two files

  1. JavaScript file where we will write the WordPress Ajax call example 
  2. PHP file that will have the function to receive the data and process it.

So basically here we are doing only two things; getting the data from the form using JavaScript and sending the form to the server.

We can later process the data inside the PHP function that

Client Side Action WordPress Ajax Call Example

On the client side, the following is the code snippet that should be in your JavaScript File

$(document).on("click", ".submit-button", function (e) {

e.preventDefault();

var fd = new FormData($('#form-id');
fd.append( "action", 'example_function_to_process_data');

$.ajax({
type: 'POST',
url: object_handle.ajax_url, //defined with wp_localize function
data: fd,

success: function(data, textStatus, XMLHttpRequest) {
console.log(data);
},

error: function(MLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
}

});

});

Server Side Action WordPress Ajax Call Example

On the server side, we simply want to create the function we declared as the action "action", 'example_function_to_process_data' and use it to process the data that we received from the Ajax call post.

In this case we need to use the two hooks that are used for Ajax front end and the names should be in the same pattern specifically the hooks the callback function can have different names:

[php] add_action( ‘wp_ajax_example_function_to_process_data’, ‘example_function_to_process_data_request’ );
add_action( ‘wp_ajax_nopriv_example_function_to_process_data’, ‘example_function_to_process_data_request’ );
[/php]

Note how I have just prefixed the hooks wp_ajax_ and wp_ajax_nopriv_ with the action we declared in the JS file – "action", 'example_function_to_process_data'. This is the trick of making it work and you should not overlook this part.

WordPress Ajax Call Example Callback Function

Now we can create the callback function and process the data:

function example_function_to_process_data_request() {

$name = isset($_POST['name'])?trim($_POST['name']):"";

$response = array();

$response['message'] = "Ajax Call WordPress Example Successful Request";

echo json_encode($response);

exit;
}

This function will log the message in the console and you will see you have successfully made the WordPress Ajax call.

WordPress Ajax Call Example React JS

In my recent project as I mentioned before I did the Ajax call using Axios in React JS and WordPress application. In the react competent the following was my code

import { Component } from 'react';
import './App.css';
import axios from 'axios';

class App extends Component {

render() {
return (
<div className="App">
<ContactForm />

</div>
);
}
}

class ContactForm extends Component{

constructor(props) {
super(props);
this.state = {
name: '',
email: '',
country: '',
city: '',
job: '',
}
}

handleFormSubmit( event ) {
event.preventDefault();

const reactAppData = window.wpRoomDesigner || {}
const { ajax_url} = reactAppData

let formData = new FormData();
formData.append('action', 'processAxioData');
formData.append('name', this.state.name)
formData.append('email', this.state.email)
formData.append('city', this.state.city)
formData.append('country', this.state.country)
formData.append('job', this.state.job)

// console.log(this.state);

/* Logging Form Data
for (var key of formData.entries()) {
console.log(key[0] + ', ' + key[1]);
} */

axios.post(ajax_url, formData).then(function(response){
console.log(response.data);
})
}

render(){
return(

<form>
<label>Name</label>
<input type="text" name="name" value={this.state.name}
onChange={e => this.setState({ name: e.target.value })}/>

<label>Email</label>
<input type="email" name="email" value={this.state.email}
onChange={e => this.setState({ email: e.target.value })}/>

<label>Country</label>
<input type="text" name="country" value={this.state.country}
onChange={e => this.setState({ country: e.target.value })}/>

<label>City</label>
<input type="text" name="city" value={this.state.city}
onChange={e => this.setState({ city: e.target.value })}/>

<label>Job</label>
<input type="text" name="job" value={this.state.job}
onChange={e => this.setState({ job: e.target.value })}/>

<input type="submit" onClick={e => this.handleFormSubmit(e)} value="Create Contact" />
</form>

);

}
}

export default App;

Here there are 3 key things to remember, you can see I am using FormData object, you need to declare the action which is the function name you will use in the PHP server side.

You also need to declare the ajax_url which you can utilize the wp_localize_script() function and finally you need to pass the form data.

wordpress ajax call example

Conclusion

In this post, we have looked at the WordPress Ajax Call example and outlined how you can make the same call in a WordPress React app.

I hope this helps you get started with making Ajax calls in WordPress.

Similar Articles