0

I have built a plugin and I need to use ajax in the admin and have followed the documentation here: https://codex.wordpress.org/AJAX_in_Plugins

However, this is out of date and I cannot find any good examples to get it working.

I use a class for the plugin and have the jquery in a seperate file. So apparently I need to use the wp_localize_script to pass the variables. This is where I am struggling to understand how to pass the variable from the selectObject.value in the JQuery to the PHP function.

Can anyone assist?

myplugin-admin.js

function getFeatureIDs(selectObject){
    var value = selectObject.value;  
    console.log(value);  //I want to pass this value but it doesnt work
    console.log(ajax_object.we_value); 

    var data = {
        'action': 'get_etim',
        'whatever': ajax_object.we_value   
    };
   
    
    jQuery.post(ajax_object.ajax_url, data, function(response) {
        alert('Got this from the server: ' + response);

    });

}

class-myplugin-admin.php

class myplugin_Admin {
    private $myplugin;
    private $version;

    public function __construct($myplugin,$version ) {
        
        add_action( 'wp_ajax_get_etim', array( $this, 'get_etim' ) );

    }

    public function enqueue_scripts() {

        wp_enqueue_script( $this->myplugin, plugin_dir_url( __FILE__ ) . 'js/myplugin-admin.js', array( 'jquery' ), $this->version, false );

        wp_localize_script( $this->myplugin, 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
    }

    public function get_etim() {

        echo $_POST['whatever'];

        wp_die();
    }
}

Results in console:

EC003025
1234
https://mytestsite.plesk.page/wp-admin/admin-ajax.php

Alert is,

"Got this from the server: 1234"

This needs to be the select variable.

2
  • try passing the value you wanted aka value, rather than ajax_object.we_value. Keep in mind that this is leaving WordPress and going into generic javascript, nothing in this question requires WordPress knowledge, and any javascript developer can help.
    – Tom J Nowell
    Mar 3 at 19:47
  • Ah seems obvious now, I was fixtated on the ajax_object as shown in the example in the documentation. Thanks again
    – LeeTee
    Mar 3 at 20:34

1 Answer 1

0

You put your value JS variable that you created in the data that gets sent to your php function via ajax like:

var data = {
    'action': 'get_etim',
    'whatever': ajax_object.we_value,
    'select_value': value   
};

Then in the php function that Ajax sends to you can use select_value the same way you used whatever in your code like:

echo “Whatever is: “ . $_POST[‘whatever’] . “, and Select value is: “ . $_POST[‘select_value’];

Don’t forget to use a nonce, sanitize input data, and escape output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.