I am trying to pass a checkbox value when it is checked from an AJAX form. Now I get the value to my AJAX function but I have no success in calling a PHP function then/passing the value to PHP.
Here is the AJAX function (applicantid.js), I get the alert message with correct value here:
function sendAjaxRequest(value){
jQuery.ajax({
url: my_ajax_script.ajaxurl,
data: ({action : 'get_my_option', value:value}),
success: function() {
alert(value);
}
});
}
Here is the code with the PHP function I’ve added to functions.php:
function your_function_name()
{
wp_enqueue_script( 'myfunction', get_template_directory_uri().'/assets/js/applicantid.js', array( 'jquery' ), '1.0',true);
wp_localize_script( 'myfunction', 'my_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('template_redirect', 'your_function_name');
function get_my_option()
{
$value = $_POST['value'];
$applicantid = get_field('applicant id', $value);
$wp_session[$value] = $applicantid;
//print($value);
}
add_action("wp_ajax_nopriv_get_my_option", "get_my_option");
add_action("wp_ajax_get_my_option", "get_my_option");
I’m really lost here and not sure what is wrong. I appreciate your support, thanks.
Very close, three problems I can spot
Your
get_my_option()
function is not sending back anything. You should do.Your jquery ajax request isn’t looking for the response, you success function should look like
Your jquery ajax request doesn’t have a type set, and so will be sent as a GET but your callback looks for a POST variable. Use
type: 'POST'
as an option for the ajax call.Using something like the network tab on chrome developer tools you can look at what’s going. You should see a request to admin-ajax.php and you can look at the request actually getting sent and the response.