wp_localize_script $data parameters in array

I’m trying to develop my first WordPress plugin, and to do this I want to use wp_localize_script to post forms data without refreshing page.
The problem is I don’t understand well how to setup the $data parameter in the wp_localize_script.

More explanations :

Read More
  • 1) I have a form with a list of data which have each one checkbox.

  • 2) When I click on a button to save the data which are checked, I try to post them on admin-ajax.php, but I don’t know how to setup the third parameter in my function wp_localize_script().

In examples on the WordPress Codex, it seems that the third data must be known… But I can’t know which data are checked at the moment the save button is clicked.

On the WordPress Codex :

<?php

wp_localize_script( $handle, $name, $data );


// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );

// Localize the script with new data
$translation_array = array(
    'some_string' => __( 'Some string to translate', 'plugin-domain' ),
    'a_value' => '10'
);
wp_localize_script( 'some_handle', 'object_name', $translation_array );

// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );

?>

In my plugin I would like to post an array of checked data, by passing posted data in json (stringified), but it doesn’t work yet (probably because I don’t understand yet how wp_localize_script() could work in this context).

For example, my script looks like this :

— Jquery part :

    // clic on the "save button"
$('#bppv_phcats_save').click(function(){

    // I load a div to show a loader ( only for the design )
    $('.bppv-loader').slideDown(150);

    // I create an empty array 
    var ph_cats = [];

    // I make a loop to check which checkbox is checked
    $('.bppv_phcat').each(function(i, obj) {

        // If current checkbox in loop is checked, I push it in the array with the data 1
        if($(this).prop('checked') === true){

            ph_cats[$(this).attr('name')] = 1;

        // Else if the current checkbox is unchecked, I push it into the array too but with the data 0
        }else{

            ph_cats[$(this).attr('name')] = 0;

        }

    });

    // I convert my array in json format and stringify this
    ph_cats = JSON.stringify($.extend({},ph_cats));

    // I test in the web console if the data looks like I want, it's ok        
    console.log(ph_cats);

    // I instanciate the variables
    var data = {
        action    : 'select_phcats',
        nonce     : bppv_phcats_obj.nonce,      // I create a nonce for more security
        ph_cats   : bppv_phcats_obj.ph_cats     // This is the data I want to retrieve in PHP
    };

    // I post the data to adamin-ajax.php
    $.post(bppv_phcats_obj.ajax_url, data, function(response){

        // I display an alert to check the response
        alert('Response : '+response);

    });

});

— PHP part
1) Register the .js script

// I register my .js script
wp_register_script('bppv_js',BPPV_ROOT_URL.'assets/js/bppv.js',array('jquery'),'1.0',true);

// I enqueue it
wp_enqueue_script('bppv_js');

// The famous wp_localize_script() function I don't understand
wp_localize_script('bppv_js','bppv_phcats_obj',array('ajax_url' => admin_url('admin-ajax.php'), ??? ));

2) My PHP function to get the posted data

function select_phcats(){

    global $wpdb;

    $nonce = $_POST['nonce'];

    if (!wp_verify_nonce($nonce,'ajax-nonce')){ die ( 'hum… It seems there is a problem…'); }

    if(isset($_POST['ph_cats'])){

        $PHcats = json_decode($_POST['ph_cats'],true);

        $PHcats = $_POST['ph_cats'];

        echo 'YEAH! I get my json data!';

    }else{

        echo 'shit! It doesn't work!';

    }

    wp_die();

}

Of course I can’t get my data in PHP side. I tried to specify the third parameter in wp_localize_script() like this :

wp_localize_script('bppv_js','bppv_phcats_obj',array('ajax_url' => admin_url('admin-ajax.php'),'nonce' => wp_create_nonce('ajax-nonce'),'ph_cats' => isset($_POST['ph_cats']) ? $_POST['ph_cats'] : 'no posted data'));

wp_localize_script('bppv_js','bppv_phcats_obj',array('ajax_url' => admin_url('admin-ajax.php'),'nonce' => wp_create_nonce('ajax-nonce'),'ph_cats' => $_POST['ph_cats']));

And like this too :

wp_localize_script('bppv_js','bppv_phcats_obj',array('ajax_url' => admin_url('admin-ajax.php'),'nonce' => wp_create_nonce('ajax-nonce'),'ph_cats' => $PHcats));

And I tried to see if this could work without setup the data in wp_localize_script(), like this :

wp_localize_script('bppv_js','bppv_phcats_obj',array('ajax_url' => admin_url('admin-ajax.php')));

Nothing is working for me, and in several topics from different tutorials on the web, I noticed that some persons don’t setup the third parameter in wp_localize_script(), but in the WordPress Codex, this third parameter seems to be required… So I don’t understand…

For information I running my script on WordPress 4.4.2.

Does somebody have any idea on how can I do?

Thanks to you to have read my question, and thanks in advance for your replies.

Cordialy,

BBFUNK01 😉

Related posts

1 comment

  1. I don’t think you need to use wp_localize_script for what you’re attempting to do.

    In order to access the POST data on the PHP side, you need to use the wp_ajax_(action) hook and/or the wp_ajax_nopriv_(action). The first hook is for admin side ajax, the second is for viewer-facing side. Once you register your functions with one or both of those hooks, the POST data will automatically be available.

    For example:

    add_action( 'wp_ajax_select_phcats', 'select_phcats' );
    add_action( 'wp_ajax_nopriv_select_phcats', 'select_phcats' );
    

    Edit:

    I see why you’re trying to use wp_localize_script. It appears that you want to use the object for the Nonce value and the ajax_url. On the admin side, the javascript variable ajaxurl should already be defined for you. If this is on the front end, add this:

    add_action('wp_head','pluginname_ajaxurl');
    function pluginname_ajaxurl() {
    ?>
    <script type="text/javascript">
        var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    </script>
    <?php
    }
    

    Then your ajax request would just look like this:

    $.post(ajaxurl, data, function(response){
    
        // I display an alert to check the response
        alert('Response : '+response);
    
    });
    

    As for using a nonce for security (which is a great idea!) you can put the nonce in a hidden input field. Here is an example.

    Using wp_localize_script to pass the admin-ajax url and the nonce

    I think that you can use wp_localize_script like this to pass the nonce and the ajax url:

    $nonce = wp_create_nonce( 'my-nonce' );
    wp_localize_script('bppv_js','bppv_phcats_obj',array('ajax_url' =>
       admin_url('admin-ajax.php'), 'nonce'=> $nonce));
    

    For more on how to use wp_localize_script, check out this tutorial.

Comments are closed.