Even if admin-ajax.php
and Ajax API were created to be used in ajax requests, they can be used in normal http requests with no issues, just be aware that is_admin()
will be true even if user is not logged and the request is done from frontend.
What you have to do is create a callback for the ajax api. In your plugin or functions.php
put:
$survey_action = 'my_survey';
add_action( "wp_ajax_{$survey_action}", 'my_survey_callback' );
add_action( "wp_ajax_nopriv_{$survey_action}", 'my_survey_callback' );
function my_survey_callback() {
echo "Welcome to the survey!";
exit(); // always exit() at the end, when using ajax api
}
now, when you send a request to admin-ajax.php
containing the ‘action’ request var set to "my_survey"
the my_survey_callback
function will be triggered.
So, if you now put in your browser address bar an url like
http://www.example.com/wp-admin/admin-ajax.php?action=my_survey
the server will response with a “Welcome to the survey!”.
Regarding using this url in javascript, yes, ajaxurl
global variable is available in admin pages by default, however nothing prevents you to set a similar variable in non-admin pages, using wp_localize_script
.
Assuming you javascript file is named my-script.js
and is located in the ‘js’ subfolder inside theme folder, then you can enqueue the file and pass the ajax url like so:
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
$handle="myscript";
wp_enqueue_script( $handle, get_template_directory_uri() . '/js/my-script.js' );
$data = array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
);
wp_localize_script( $handle, 'my_script_data', $data );
}
Using code above, inside my-script.js
you have access to a global object named my_script_data
whose ajaxurl
property will be the proper ajax url you have to use, so, you can do there something like that:
window.open( my_script_data.ajaxurl + '?action=my_survey' );
And a new browser tab will be opened showing an awesome “Welcome to the survey!”.