4

I am writing a plugin for the first time, and I have a problem.

I am using AJAX in my plugin. My JavaScript file is in the folder ../wp-content/plugins/myplugin/js/ , and in it I am trying to call a PHP file, which is in the folder ../wp-content/plugins/myplugin/

jQuery.ajax({
    url: "/wp-content/plugins/myplugin/myfile.php?myparam=" + myparam,
    context: document.body
});

My question is: How can I get this URL reference work independent of, where the user installed the plugin. Because when for example a user install this plugin in http://localhost/subdir/, the reference is not correct. Can I somehow create a relative link ?

3 Answers 3

5

First of all, you shouldn't call your own PHP file. You should use admin-ajax endpoint. Documentation

On admin side, you could use ajaxurl to get URL for AJAX calls. On front side you have to declare by yourself variable with url. This is written in documentation:

Note: Unlike on the admin side, the ajaxurl javascript global does not get automatically defined for you, unless you have BuddyPress or another Ajax-reliant plugin installed. So instead of relying on a global javascript variable, declare a javascript namespace object with its own property, ajaxurl. You might also use wp_localize_script() to make the URL available to your script, and generate it using this expression: admin_url( 'admin-ajax.php' )

This should resolve problem:

add_action( 'wp_head', 'front_ajaxurl' );
function front_ajaxurl() {
    wp_register_script( 'admin_ajax_front', plugin_dir_url(__FILE__) . 'script.js' );
    $translation_array = array(
        'ajaxurl' => admin_url( 'admin-ajax.php' )
    );
    wp_localize_script( 'admin_ajax_front', 'front', $translation_array );
    wp_enqueue_script( 'admin_ajax_font', false, array(), false, true ); // last param set to true will enqueue script on footer
}

And then in your JS file:

$.ajax({
    url: front.ajaxurl,
    ...
})
5
  • 2
    Mixing up JavaScript and PHP code isn't a good practice. As the documentation quote says I would go with wp_localize_script(). That ensures that the variable will be defined before the script that depends on it will be loaded.
    – David
    Jul 27, 2016 at 9:16
  • Even better than wp_localize_script(), you can use wp_add_inline_script() since WordPress 4.5. This functions allows to print inline scripts within the great WordPress dependencies manager system, and not only limited to a JavaScript Object like wp_add_inline_script().
    – cybmeta
    Jul 27, 2016 at 9:25
  • i am still not getting it ... i still dont know how i refer to myfile.php and where ? will i make it into a function or how ? pls give me a hint, im lost Jul 27, 2016 at 11:02
  • If you really need to call file from your plugin you could do it by plugin_dir_url(__FILE__) Jul 27, 2016 at 11:28
  • i need to call myfile.php in my js as i showed in my question, of course, thats what i need ajax for. Its not clear to me also, if i should put admin-ajax.php in ajaxurl, or if its myfile.php i should put there instead ? Jul 27, 2016 at 12:03
2

I'm a beginner, but this worked for me

Add the following in functions.php. Note that 'wp_ajax' is a prefix by convention and 'do_something' is my arbitrarily chosen action name:

add_action( 'wp_ajax_do_something', 'do_something' );

function do_something() {
    //really, go ahead, do something
    die("return something");
}

To make the ajax call from the browser (client side), I was able to find my endpoint using wp.ajax.settings.url. wp global var is defined on the window object.

//do_something here must match above, you can add other params to this obj
var data = { action: 'do_something' };
jQuery.post(wp.ajax.settings.url, data, function(response) {
    console.log('Result: ' + response);
});

I have WordPress 4.6.1 (latest on time of writing) and some plugins installed. I referred to this reference that incorrectly says that ajaxurl is defined, but it's not in my case: https://codex.wordpress.org/AJAX_in_Plugins

2

I faced the same issue.

I wanted to use my own endpoint instead the admin-ajax endpoint because I have rewrite rules populating all the variables I need to run the ajax actions.

Thus, using (as said in the codex)

jQuery(document).ready(function($) {
    var data = {
        'action': 'my_action',
        'whatever': ajax_object.we_value      // We pass php values differently!
    };
    jQuery.post(ajax_object.ajax_url, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});

and

add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );

just makes my code more complicated.

I ended up doing this and it seems to work:

    jQuery.ajax({
        type: "post",
        url: MYCUSTOMENDPOINT?ajax_action,
        dataType: 'json',
        ...

combined with:

    add_action( 'init', 'rewrite_rules');
    add_filter( 'template_include','handle_ajax_action');

function rewrite_rules(){
    add_rewrite_tag(
        '%ajax_action%',
        '([^&]+)'
    );
}

function handle_ajax_action($template){

    $success = null;

    // since the "ajax" query variable does not require a value, we need to check for its existence
    if ( !$action = get_query_var( 'ajax_action' ) ) return $template; //ajax action does not exists

    $result = array(
        'input' =>  $_REQUEST,
        'message'=> null,
        'success'=> null,
    );

    $success = ...

    if ( is_wp_error($success) ){
        $result['success'] = false;
        $result['message'] = $success->get_error_message();

    }else{
        $result['success'] = $success;
    }

    header('Content-type: application/json');
    send_nosniff_header();
    header('Cache-Control: no-cache');
    header('Pragma: no-cache');

    wp_send_json( $result );  

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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