vendredi 20 novembre 2015

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?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire