0

I am trying to pass my php array to my external js file.

PHP

 if (!function_exists('myScripts')) {
     function myScripts() {
         wp_enqueue_style('my-css', get_stylesheet_directory_uri() . '/assets/css/mycss.css');
         wp_enqueue_script('my-js', get_stylesheet_directory_uri() . '/assets/js/myjs.js');

         $fields = get_sub_field('months'); // acf repeater field
         $data = json_encode($fields);

         wp_add_inline_script( 'my-js', 'const dateFields = ' . json_encode( array(
             'ajaxUrl' => admin_url( 'admin-ajax.php' ),
             'fields' => $data,
         ) ), 'before' );
     }
     add_action('wp_enqueue_scripts', 'myScripts');
 }

JS

 $(function(){
     console.log(dateFields.fields);
 });

If I change:

'fields' => $data,

to

'fields' => 'inline script working'

My console log does produce a false initially and "inline script working" successfully so I feel like its the:

 $data = json_encode($fields);

not working as the $fields variable is passing data to the console when I run a console_log in php

How can I successfully pass my php variable to js

0

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.

Browse other questions tagged or ask your own question.