Pass PHP variable to javascript

Best practice method

Have a look at wp_localize_script, which is meant to do exactly that.

But it does require previous usage of wp_enqueue_scripts, hence you will need to move your JS to a separate file indeed.
It will be worth those few minutes of effort though, for sure.

function wpse_96370_scripts()
{
    if ( is_single() ) {

        wp_register_script(
           'your_script_handle',
           get_template_directory_uri() . '/js/your-script.js',
           array( /* dependencies*/ ),
           1.0,
           true
       );

       wp_enqueue_script( 'your-script-handle' );

       $script_params = array(
           /* examples */
           'post' => 99,
           'users' => array( 1, 20, 2049 )
       );

       wp_localize_script( 'your-script-handle', 'scriptParams', $script_params );

    }
}
add_action( 'wp_enqueue_scripts', 'wpse_96370_scripts' );

In the JS you will then be able to use the passed parameters like so:

var posts = scriptParams.post,
    secondUser = scriptParams.users[1]; /* index starts at 0 */

// iterate over users
for ( var i = 0; i < scriptParams.users.length; i++ ) {
    alert( scriptParams.users[i] );
}

[Edit] Your situation

As per your comment

I created a new db table with some response.ids from facebook api. This is the table: action_id, user_id,post_id, fb_id where fb_id is response.id from a facebook action. Then in single.php I have a button where if I press I must delete the fb action with api: FB.api("https://wordpress.stackexchange.com/"+fb.response, 'delete'); where fb.response should be fb_id from table.

Put the following your theme’s /js/ folder, create it, if it doesn’t exist.
Let’s call the file fb-response.js:

jQuery( '#button_id' ).click( function() {
    FB.api( "https://wordpress.stackexchange.com/" + fbParams.id, 'delete' );
});

Then register, enqueue and localize as seen above. Assuming that you have the ID you’d like to pass in let’s say $fb_id:

wp_register_script(
    'fb-response',
     get_template_directory_uri() . '/js/fb-response.js',
     array( 'jquery' ),
     1.0,
     true
);

wp_enqueue_script( 'fb-response' );

wp_localize_script( 'fb-response', 'fbParams', array( 'id' => $fb_id ) );

N.B. Obviously, the above is assuming this is in a theme. If we’re talking “plugin”, alter locations accordingly.

Leave a Comment