How to use ajax in wordpress.
In this post I will explain how to create simple ajax function in wordpress. The ajax function will send json data as string.
Enqueue the js file
We create the js file with file name script.js. What important in this script is localize the script. The ajax will not working if we not localize the script. There is 2 parameter we need to caution. First is myAjax and the second is ajaxurl both two parameters will be called in our js script.
wp_enqueue_script( 'my-script-js', get_template_directory_uri() . '/assets/script.js', array(), '01', true );
wp_localize_script('my-script-js', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
Create js function
Here we will create js function that send json data to php. We will convert json to string, using JSON.stringify. Here is the code:
$("#test_json").click(function (e) {
e.preventDefault();
var json_data = [{
"id": 1,
"first_name": "Rancell",
"last_name": "Byrkmyr"
}, {
"id": 2,
"first_name": "Ray",
"last_name": "Hinckes"
}, {
"id": 3,
"first_name": "Cathyleen",
"last_name": "Crufts"
}];
console.log(json_data);
var json_data_str = JSON.stringify(json_data);
console.log(json_data_str);
var data = {
action:'test_ajax',
data_json: json_data_str,
}
$.ajax({
type: "post",
url: my_Ajax.ajax_url,
data: data,
dataType: "json",
success:function(response){
console.log(response);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
})
There is some important thing that we need to have a note:
1. The url we use in ajax is set when we localize the script.
2. action key inside data will be used to call function on the php file.
Create function
Now we will define the function in php that will be called by the js.
we add 2 action
wp_ajax_test_ajax and
wp_ajax_nopriv_my_action and the function name will be
test_ajax_fun. The action name must start with
wp_ajax_ and
wp_ajax_nopriv_ continued with action name that we use on the javascript. wp_ajax_test_ajax is used when logged in and
wp_ajax_nopriv_test_ajax when you not logged in.
add_action("wp_ajax_test_ajax", "test_ajax_fun");
add_action("wp_ajax_nopriv_test_ajax", "test_ajax_fun");
function test_ajax_fun(){
$data_json_str = $_POST['data_json'];
$data_json_str = stripslashes($data_json_str);
$data_json_obj = json_decode($data_json_str, true);
$data_return->status = "new data";
$data_return->our_data = $data_json_obj;
echo json_encode($data_return);
wp_die();
}
you can check this ajax by using
inspect on chrome and choose
Network.
below is the screenshot: