GeekedOut
GeekedOut

Reputation: 17185

How to use a php result set from a query in JavaScript

I am working on a page that displays all state parks. Something like this:

http://www.comehike.com/outdoors/state.php?country_id=1&state_id=6&state_name=California&country_name=

I have the park data, including lat/lng in my database and I already get that data during the request. What I want to avoid is doing an AJAX call which will query the park data again.

Is it possible for me to just send the PHP result set to the JS somehow and to loop through the parks and display them?

I am already doing something like that by sending the map-center lat/lng so I figured it is doable with a result set.

Thanks, Alex

Upvotes: 1

Views: 847

Answers (1)

JohnP
JohnP

Reputation: 50019

This depends on how your pages are setup. If you're using some kind of MVC setup, you need to pass the variable to your view first. Or if it's a single page, just retrieve the PHP above and pass it as a variable.

<?php
   $parkData   = $model->getData();  //make sure this returns an array or an object array or something
   $parkDataJson = json_encode($parkData);
?>

//in your view

<script type='text/javascript'>
   let parkData = <?php echo $parkDataJson ?>;
   //now you have a JSON array available for your use
</script>

Upvotes: 2

Related Questions