Roots Discourse

Pass php to javascript

Hi Guys,

how can i pass PHP Variables to JavaScript ?

i have:

public function suche(){
$js_data = array(
‘location1’ => “1234”,
‘location2’ => ‘5678’
return $js_data;

init() {
/* eslint-disable /
var myVar = {
loc1: location1,
loc2: location2
eslint-enable no-unused-vars */

But it don’t work, I know there is wp_enqueue_script , but i don’t know how to get it to work.
i want to pass “location1” etc. from PageUmkreis.php Controller to the JS in umkreis.js.
I hope anyone can help me, Thank You.

My first choice would be using data attributes.
As second choice, using WordPress to inject JavaScript variables into the page for enqueued scripts (wp_localize_script.).
As you try to filter/select by radius (“Umkreis”), you may want a dedicated filter plugin?

i want to add a custom post type for “Projects” with longtitude and latitude, then i will create a form with “postalcode”. The user Enter his postal code and my Script search for this Postalcode within a radius of ~10 km. The Results will be displayed in Google Maps as Markers. i get Google Maps and Markers work with Sage. I think i can get all the Projects with long and lat… but the dificult thing is how to get these values to the javascript to build the Markers. i have no opinion how to do this with data attributes or something like that. i see this or that, but no clue how this can work for me.

i got gmaps to work, thats not the problem. or what do u mean ?

The example on the ACF site also describes how to use data attributes for the longitude/latitude.
The data in the attributes is used by JavaScript.
You can use the same approach to use that data in JavaScript for filtering (radius / Google APIs).