开发者

Passing a variable from PHP to jQuery on page load

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['re开发者_StackOverflow中文版f']."\"";

        $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


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));


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. ;)


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜