I am following an example on AJAX in Plugins on WordPress website. It’s very simple example, and I am trying to modify the example as I intend.

What I am trying to achieve is simple:

  • When a new option is selected in select/option dropdown, detect the selected value
  • Pass the selected value to PHP function via AJAX

However, the selected value doesn’t seem to be passed via AJAX.
The result I am getting is: whatever = 1234 | whatever2 =

How do I properly pass my variable to AJAX?

My code:

// Select/Option Dropdown

<select id="_type" name="_type">
  <option value="AAA"> AAA </option>
  <option value="BBB"> BBB </option>
  <option value="CCC"> CCC </option>
</select>


// Detect change and call and AJAX

<script type="text/javascript">
jQuery('#_type'.change(function($) {
  var val = jQuery('#_type').val(); <-- Here I am properly getting val as it changes.
  console.log( '_type is changed to ' + val );

  var data = {
    'action': 'my_action',
    'type': 'post',
    'whatever': 1234,
    'whatever2': val <-- But here val becomes empty.  
  };

  jQuery.post(ajaxurl, data, function(response) {
    alert( 'Got this from the server: ' + response );
  });
}).change();
</script>


// PHP function 'my_action'

add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
  global $wpdb;
  $whatever = $_POST['whatever'];
  $whatever2 = $_POST['whatever2'];
  echo 'whatever=" . $whatever . " | whatever2 = ' . $whatever2;
  wp_die();
}

3 Answers
3

The simple answer: Don’t bother with the Admin AJAX API, use the REST API!

Tell WordPress about your endpoint:

add_action( 'rest_api_init', function () { // register dongsan/v1/whatever
        register_rest_route( 'dongsan/v1', '/whatever/', array(
                'methods' => 'POST', // use POST to call it
                'callback' => 'dongsan_whatever' // call this function
        ) );
} );

Now we have an endpoint at example.com/wp-json/dongsan/v1/whatever!

We told WordPress to run dongsan_whatever when it gets called, so lets do that:

function dongsan_whatever( \WP_REST_Request $request ) {
    $name = $request['name'];
    return 'hello '.$name;
}

Note that we used $request['name'] to get a name parameter!

So we have a URL:

example.com/wp-json/dongsan/v1/whatever

And we can send a POST request with a name to it and get some JSON back that says Hello ‘name’! So how do we do that?

Simples, it’s a standard jQuery post request:

jQuery.post(
    'https://example.com/wp-json/dongsan/v1/whatever',
    { 'name': 'Dongsan' }
).done( function( data ) {
    Console.log( data ); // most likely "Hello Dongsan"
} );

Further reading:

  • https://tomjn.com/2017/01/23/writing-wp-rest-api-endpoint-2-minutes/
  • https://developer.wordpress.org/rest-api/
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *