Search code examples
javascriptphpjquerypluginswordpress

Wordpress plugin pass javascript variable to php


Can somebody help me? I'm feeling so stupid. I took example code from WordPress codex, made a example plugin in my webpage, but there no respond...

PHP code is here:

/**
 * Plugin Name: Ada Ajax Test
 * Description: WP Codex based ajax example
 * Version: 1.0.0
 * Author: M. A. Tomas
 * Author URI: http://www.matomas.cz
 * License: GPL2
 */

add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
    if( 'index.php' != $hook ) {
    // Only applies to dashboard panel
    return;
    }

    wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery') );

    // in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
    wp_localize_script( 'ajax-script', 'ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
}

// Same handler function...
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
    global $wpdb;
    $whatever = intval( $_POST['whatever'] );
    $whatever += 10;
  return $whatever;
    wp_die();

}



 // shortcode pro zobrazeni na strance
add_shortcode( 'ajax-zkouska', 'my_action_callback' );

and Javascript code in external file is here:

    // JavaScript Document

jQuery(document).ready(function($) {
    var data = {
        'action': 'my_action',
        'whatever': ajax_object.we_value      // We pass php values differently!
    };
    // We can also pass the url value separately from ajaxurl for front end AJAX implementations
    jQuery.post(ajax_object.ajax_url, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});

Where I mistake?


Solution

  • You have a few things mixed up.

    Front End

    If you are targeting the frontend, then you need to use this hook:

    add_action( 'wp_enqueue_scripts', 'my_enqueue' );

    This allows you to add the needed scripts to the front end and not the admin side.

    Ajax Calls

    All ajax calls are executed within the admin context. So you will need to test for it and add the ajax hooks accordingly.

    if ( is_admin() ) {
        add_action( 'wp_ajax_my_frontend_action', 'my_frontend_action_callback' );
        add_action( 'wp_ajax_nopriv_my_frontend_action', 'my_frontend_action_callback' );
        add_action( 'wp_ajax_my_backend_action', 'my_backend_action_callback' );
        // Add other back-end action hooks here
    } else {
        // Add non-Ajax front-end action hooks here
    }
    

    No Priv

    The no_priv hook is meant for users that are not logged in. Add it if that's your intention.