0

I'm setting up a plugin that requires passing of a variable from a stand alone jQuery file to options.php. I have (I think) set up the scripts to be used in my plugin file like so:

function ndw_js_init(){
    wp_enqueue_script('jquery');
    wp_register_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array( 'jquery' ), '', true );
    wp_enqueue_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array(), '1.0.0', true);
    $scriptdata = array('admin_ajax' => admin_url( 'admin-ajax.php' ));
    wp_localize_script( 'ndw_js', 'toremove', $scriptdata);
}
add_action('admin_init', 'ndw_js_init');

Where I am coming unstuck is in the jQuery file. The variable is passed onclick. So far I have this which works fine (tested using an alert()):

$('tr td .widget-remove a').click(function(){
     var toremove = $(this).attr('rel');
     var url = 'options.php'; // EDIT: Actualy, is this right? Or should the data be passed to the name of my plugin main page I wonder
     // Out of ideas
});

So what I need is help to use the correct AJAX syntax to pass the value of var 'toremove' to 'options.php' and then do something in 'options.php' using the value of 'toremove'.

Hope that makes sense!

EDIT No.1:

OK, so after playing with different settings provided by all of you I have a (semi) functional script:

function ndw_js_init(){
    wp_register_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array( 'jquery' ), '', true );
    wp_enqueue_script( 'ndw_js' ); // not working without this
    wp_localize_script( 'ndw_js', 'toremove', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
}
add_action('admin_init', 'ndw_js_init');

Without these settings as they are nothing works. In my external js file I now have:

$('tr td .widget-remove a').click(function(){
        var toremove = $(this).attr('rel');
        $.ajax({
            type: 'POST', 
            dataType: 'json',
            url: ajaxurl, 
            data: {
                nonce : toremove.nonce,
                toremove : toremove
            },
            complete: function( data ){
                alert(toremove + " ding!");
            }
        });
    });

This works - but only the jQuery code. In the Admin area on my plugin settings page the alert fires on click with the correct id no and the word 'ding!'.

Back to my plugin settings page and I add this (thanks @MMK):

function ndw_ajax_function(){            
    $toremove = $_POST['toremove'];
    echo "To remove: " . $toremove;
}

add_action('wp_ajax_my_ajax_action', 'ndw_ajax_function' );

This does not work, I view the generated source and the echoed line does not appear. However, I am not sure in that last add action what wp_ajax_my_ajax_action refers to.

  • 2
    Can you give us a little context about what you're trying to build and why you decided this was needed? This sounds like an XY problem – Tom J Nowell Oct 5 '15 at 13:22
  • Sure, the relevant (to this problem) part of the plugin is that I want the user to be able to click an item in an unordered list of links. These links have rel as an attribute. The value of the attributes is a post ID e.g. <li><a href="#" rel="123">Click me</a.</li> <li><a href="#" rel="456">Or me</a.</li> The value of the attribute gets picked up in my external js file like so: var toremove = $(this).attr('rel'); I then want to pass the value of 'toremove' to my main plugin file, pick the value up there, run delete_option using the value to remove that post. – Kev Oct 5 '15 at 13:31
  • 2
    You need AJAX. Search the site and the Codex for using AJAX in WordPress – s_ha_dum Oct 5 '15 at 13:58
  • @Kev I mean on a more generic level, you're describing a technical solution to a problem you're trying to solve, but you've not stated what the original problem is, e.g. what's the UI control you're trying to implement? What is its purpose? My current guess is you have a list of posts and you want to add delete/remove buttons powered by AJAX, correct? – Tom J Nowell Oct 5 '15 at 14:40
  • You may be looking for an ajax system. here is a link to one very good <a href="smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/…> on how to use it. Also you might want to check the codex on ajax in plugins. And since you are using the admin_init hook you might want to skip the admin_ajax key and value as its already populated by Wordpress and available in the backend. Just use the ajaxurl variable to get the ajax url. – MMK Oct 5 '15 at 14:41
0

May i suggest:

$('tr td .widget-remove a').click(function(){
    var toremove = $(this).attr('rel');
    // Out of ideas     -     you shouldn't really be for we are here!
    $.ajax({
        type: 'POST',         // use the method you want
        dataType: 'json',
        url: ajaxurl,        // this is the url to the admin ajax script
        data: {
            nonce : your_script_data_object.nonce,
            toremove: toremove
        },
        complete: function( object ){
            // do what you want here when the ajax requests completes
        }
    });
});

Now in your plugin somewhere you will have to have a function that intercepts the data that your are sending. You should just make sure you are adding your ajax intercept function to the right action hook in wordpress. Here's how you can do it.

Here is the non-oop way.

add_action('wp_ajax_my_ajax_action', 'my_ajax_function' );

And here the oop way.

add_action('wp_ajax_my_ajax_action', array( $this, 'my_ajax_function' ) );

Here is the function:

function my_ajax_function(){            
    // do what you want here - the world is open to you
    $toremove = $_POST['toremove'];
    // Any other thing you want to do
    wp_send_json_success( array( 'AnyDataYouWantToSend' => $your_data ) );
}

If you encounter any error in my_ajax_function then use wp_send_json_error in place of wp_send_json_success.

I also noted one unusual thing. Why are you using wp_register_script and wp_enqueue_script on the same script. Here is something you can do. Remove the wp_register_script line and let your function look like this:

function ndw_js_init(){
    wp_register_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array( 'jquery' ), '', true );
    wp_enqueue_script( 'ndw_js' );
    wp_localize_script( 'ndw_js', 'toremove' );
}
add_action('admin_init', 'ndw_js_init');

You don't need the $scriptdata variable you were using since as i told you the ajaxurl javascript variable already gives you access to the admin ajax url. That is only if you are in the admin. On the frontend make sure your $scriptdata var is present as the parameter for wp_localize_script

You don't need this line too:

wp_enqueue_script('jquery');

This is because you are already telling Wordpress that your script requires jquery in the dependencies array parameter array( 'jquery' ).

Hope that helps.

  • I've edited the original question (see Edit No.1) – Kev Oct 8 '15 at 11:11
  • Dear Kev, the string wp_ajax_my_ajax_action is called a hook in WordPress. There are hooks for different things in wordpress. The wp_ajax_my_ajax_action hook is a wp ajax hook. Whenever you want to do ajaxing in wordpress you have to use this hook. it is divided into two parts. First wp_ajax_ and then my_ajax_action. my_ajax_action works like an id. When your script sends action: 'my_ajax_action' this tells wordpress to fire the function associated with that action. In this case it is ndw_ajax_function. – MMK Oct 12 '15 at 12:27
0

OK, I got this working like so:

Step One: Main Plugin File

function ndw_js_init(){
    wp_register_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array( 'jquery' ), '', true );
    wp_enqueue_script( 'ndw_js' );
    wp_localize_script( 'ndw_js', 'removeid', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
}
add_action('admin_init', 'ndw_js_init');

Step Two: External JS File

$('tr td .widget-remove a').click(function(){
    var toremove = $(this).attr('rel');
    $.ajax({
        url: removeid.ajaxurl,
        data:{
            'action' : 'ndw_ajax_function',
            'passiton' : toremove
        },
        success: function( data ){
            $('.widget-remove').html(data);
        }
    });
});

Step Three: Back in Main Plugin File

function ndw_ajax_function(){
    $toremove = $_REQUEST['passiton'];
    echo $toremove;
    die();
}
add_action('wp_ajax_ndw_ajax_function', 'ndw_ajax_function' );
add_action( 'wp_ajax_nopriv_ndw_ajax_function', 'ndw_ajax_function' );

This works just fine. Thank you for your help, its greatly appreciated.

  • Forgot one thing in my answer as you may have noticed. You have to use the action key in your data object in your script. as you have done it. Note that wp_ajax_nopriv makes your function ndw_ajax_function callable from the front-end. wp_ajax_nopriv is meant for non-logged in users. If your plugin's purpose is to work in the back-end only you must not use add_action( 'wp_ajax_nopriv_ndw_ajax_function', 'ndw_ajax_function' ); – MMK Oct 12 '15 at 12:32
  • your_script_data_object is the name of the object you gave when you localized your script using wp_localize_script( 'your-script-handle', 'your_script_data_object', your array here') . – MMK Oct 12 '15 at 12:35

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.