1

I'm trying to take a reference variable from the url, and query my database when the user first visits the page. I then need to take this results and plot on google maps.

<?php 
    include('storelocator/db/config.php');
    include('storelocator/db/db.php');  

    if(isset($_GET['ref'])){

        $ref = stripslashes($_GET['ref']);

        $sql = "SELECT * FROM `markers` WHERE `ref` = \"".$_GET['ref']."\"";

        $result = mysql_query($sql);    
        $row = mysql_fetch_row($result);
        print_r($row);
    }
?>

This is my code at the top of my index page, it works fine, the print_r gives the correct results. I'm just not sure how to pass these results to jQuery to be plotted. (I know how to plot, I basically need to know how to pass a variable $row['latlng'] to jQuery.)

thanks

3
  • thanks for the quick replies. echoing out the variable works, I'm wondering if this considered bad practise, because now my page begins with a <script> element. Commented May 31, 2011 at 13:19
  • The obvious answer is to do the "echoing" in the appropriate place in your document Commented May 31, 2011 at 13:21
  • makes sense. Brains clearly not turned on today, cheers Commented May 31, 2011 at 13:27

3 Answers 3

2

Something like this

<script type="text/javascript">
var markers = <?php echo json_encode($row) ?>;
</script>

Now the markers JavaScript variable will be available to any scripts following the above.

You can access associative entries from the PHP $row array using

var latlng = markers.latlng;

While we're here, you should protect your query from SQL injection. Whilst I always recommend using PDO and parameter binding, a quick fix for you would be

$ref = get_magic_quotes_gpc() ? stripslashes($_GET['ref']) : $_GET['ref'];
$sql = sprintf("SELECT * FROM `markers` WHERE `ref` = '%s'",
               mysql_real_escape_string($ref));
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for using json_encode which takes care of escaping special characters.
1

In line with

print_r($row);

put:

echo '<script type="text/javascript">';
echo 'var latlng = "' . $row['latlng'] . '";';
echo '</script>';

This is the way to pass data to JavaScript. ;)

Comments

0

the following code pass your data to the javascript variable: 'data'

echo "<script>var data='".$row['latlng']."';</script>"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.