i've done an ajax request in my wordpress plugin.My request is based on steps below:
1) i am including js file and starting a request document on ready
2)At the php side i want to take this request and print it to test.
for all these stuff i wrote these codes:
main.js:
$(function(){
$.post('/wp-content/plugins/dsn/functions.php',{token:"1tibu4"},function(data) {
console.log(data);
},"json");
});
functions.php:
<?php
add_action('loop_end', 'init');
function init(){
global $_POST;
$post= $_POST;
echo json_encode($post);Exit;
}
My question is when request complete there is nothing on the response tab of console screen.How come this happen?
WordPress has a unique way of handling AJAX. If you make a request to the php file directly, then you are not loading the rest of the WordPress framework and a lot of WordPress specific functionality will not be available to you.
In the PHP side, what you have to do is use code that looks like this:
//for logged in users
add_action('wp_ajax_my_action', 'my_action_callback');
//for not logged in users
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
function my_action_callback() {
//your function here
exit; //always call exit at the end of a WordPress ajax function
}
In the JS side, you need to send your request to a file called "wp-admin/admin-ajax.php"
So your request would look like this (using jQuery):
$.ajax({
url : '/wp-admin/admin-ajax.php',
type : 'get', //or 'post'
data : {
action: 'my_action_callback'
}
})
.fail(function(r,status,jqXHR) {
console.log('failed');
});
.done(function(r,status,jqXHR) {
console.log('success');
});
Note the my_action_callback parts.
Make sure you have enqueuied your custom script as follows. if your script is included before the Wordpress JQuery scripts are custom injected ur code might not work properly.
function my_scripts_method() {
wp_enqueue_script(
'custom-script',
get_template_directory_uri() . '/js/main.js',
array('jquery')
);
}
add_action('wp_enqueue_scripts', 'my_scripts_method');