Calling WordPress PHP function from AJAX

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:

Read More
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.

Related posts

Leave a Reply

1 comment

  1. Very close, three problems I can spot

    1. Your get_my_option() function is not sending back anything. You should do.

      function get_my_option()
      {
          //get applicant id (looks like this is what you want to get back?)
      
          //send json headers
          header( "Content-Type: application/json" );
      
          //print out you response as json
          echo json_encode( $applicantid );
      
          //must have an exit in the ajax action callback!
          exit();
      
      }
      
    2. Your jquery ajax request isn’t looking for the response, you success function should look like

      success: function( response ){
          console.log( response );
      })
      
    3. 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.