0

So I've read a few tutorials on ajax and the codex documentation on it and I think I understand now how it is supposed to work, however it appears that wp_localize_script is not doing anything at all. According to what I've read in the codex and on various forums, the wp_localize_script should allow me to create a global object that an external javascript file can reference. But when I inspect the DOM in chrome it isn't there. My code is below

class Admin_Page extends Admin_Console {
static $add_script;




public static function init() {
    add_shortcode('CLADMIN', array(__CLASS__, 'handle_shortcode'));

    add_action('init', array(__CLASS__, 'register_script'));
    add_action('wp_footer', array(__CLASS__, 'print_script'));
    // add_action( 'wp_ajax_getData', 'data_response' );
}





static function data_response() {
//do stuff

}


public function register_script() {

    wp_enqueue_script('masterJS','/wp-content/plugins/AdminQuizConsole/js/master.js',     array('jquery','jquery-ui-core','jquery-effects-core'), true);
    wp_register_style( 'master', '/wp-content/plugins/AdminQuizConsole/css/master.css'     );
}

static function print_script() {
    if ( ! self::$add_script )
        return;


    wp_enqueue_style('master');
    wp_localize_script('masterJS', 'AjaxRequest', array( 'ajaxurl' => admin_url('admin-ajax.php') ) );

}
}


Admin_Page::init();

Now unless I'm mistaken according to what I see here the localize should be being called after the enqueue and therefore should add something like this to the DOM

/* <![CDATA[ */
var MyAjax = {
ajaxRequest: "http://example.com/wordpress/wp-admin/admin-ajax.php"
};
/* ]]> */ 

But that does not appear to be happening. Can someone please explain to me is there something I'm missing?

EDIT

Got the above question working but admin-page now returns with a zero

public static function init() {
    add_shortcode('CLADMIN', array(__CLASS__, 'handle_shortcode'));

    add_action('wp_enqueue_scripts', array(__CLASS__, 'register_script'));
    // add_action('wp_footer', array(__CLASS__, 'print_script'));
     add_action( 'wp_ajax_nopriv_get_data', 'data_response' );
}

public function data_response() {

    global $wpdb;
    $user_id=null;

    $user_id = $user_id = $user_id ? $user_id : get_current_user_id();
    $practiceKey = 'user_practice';

    //Get Practice
    $sql = $wpdb->prepare( "SELECT meta_value FROM {$wpdb->usermeta} WHERE user_id = %d AND meta_key = %s", $user_id, $practiceKey );
    $sql3 = $wpdb->prepare( "SELECT meta_value FROM {$wpdb->usermeta} WHERE user_id = %d AND meta_key = %s", $user_id, 'user_practice_level' );
    $practice = $wpdb->get_var( $sql );
    $usr_level = $wpdb->get_var( $sql3 );
    $db_name = $wpdb->prefix . 'plugin_slickquiz_scores';
    if($usr_level == 0){
        $get_data = $wpdb->prepare( "SELECT quiz_id,score,createdDate FROM $db_name WHERE usr = $user_id" );
        $results = $wpdb->get_results($get_data,ARRAY_A);
        $result_array = array();

        foreach ( $results as $value )
        {
            $result_array[] = $value;
        }
    } elseif ($usr_level == 1) {
        $get_data = $wpdb->prepare( "SELECT * FROM $db_name WHERE usr_practice = %s",$practice );
        $results = $wpdb->get_results($get_data,ARRAY_A);

        foreach ( $results as $value )
        {
            $result_array[] = $value;
        }
    } else {
        $result_array[] = (1);

    }



    $data_encode = json_encode($result_array);

    header( "Content-Type: application/json" );
    echo $data_encode;
    die();

}

    function get_level() {

        $.post(AjaxRequest.ajaxurl, {action : "get_data"})
            .done(function( json ){
                console.log(json);
            })

            .fail(function( jqxhr, textStatus, error){
                var err = textStatus + ', ' + error;
                console.log( 'Request Failed: ' + err);
            });


    }

The action name and the call back function seem to match up and it's being sent over post in case I wanted/needed to change the no_priv option.

I'm sure it's just something I'm missing but I've tested my output by taking the query out of the callback function and echoing it straight onto the page and it does return valid JSON so I'm not sure what I'm missing now.

2
  • Thanks that really helped but even though now it is sending the ajax request it's always returning with a 0. I'm sorry if these are stupid questions but this is my first time developing for wordpress. EDIT - I updated my code
    – richbai90
    Jun 22, 2013 at 6:40
  • sorry figured that out, moved the add actions to the top of my init function and changed the callback to array(CLASS, 'data_response' Thanks again for your help
    – richbai90
    Jun 22, 2013 at 6:53

1 Answer 1

3

Your timing is off. You are enqueueing script to echo in header, but you try to localize it long after the fact in footer.

You should be doing registration and localization in proper wp_enqueue_scripts hook (not init by the way).

Your Answer

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

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