-2

I am trying to fetch latitude, longitude and venue by using

sites[0] // gets latitude
sites[1] // gets longitude
sites[2] // gets venue

This is my code, don't mind the sql queries, I know they are bad but it's functional for now. I just need help with this array:

  var sites = [<?php

include_once'config/connect.php';

$search= $_POST['search'];
$search = stripslashes($search);

$search = mysql_real_escape_string($search);

$sql= "select * from venue where vID in (select vID from sv where sID in (select sID from sports where sN = '$search'));";

$result=mysql_query($sql)or die(mysql_error()); 

while($data=mysql_fetch_array($result))
{
    echo ",[".$data['latitude']."]";
    echo ",[".$data['longitude']."]";
    echo ",[".$data['venue']."]";

}

?> ];
3
  • 2
    So what do you want and what error are you getting? Commented Jan 9, 2014 at 12:26
  • i want to get for example latitude if i type sites[0] but it doesn't work. let me check that Commented Jan 9, 2014 at 12:31
  • 1
    1. Don't use the mysql_ methods; they're deprecated. 2. Don't try to format your JSON yourself, use json_encode. Commented Jan 9, 2014 at 12:37

3 Answers 3

1

Create a normal PHP array containing the values you want, and call json_encode to convert it to JSON. Echo that, and parse it on the client.

<?php
    $data = mysql_fetch_array($result);
    $array = array($data['latitude'], $data['longitude'], $data['venue']);
?>

<script>
    var sites = <?php echo json_encode($array); ?>;
</script>

Edit: as @kba points out, the mysql_ methods are deprecated.

0

If you sql is working fine, then you just need to remove the extras "[" "]", so it will be like this:

echo $data['latitude'].", ";
echo $data['longitude'].", ";
echo $data['venue'];

Then your javascript array will be working ok

1
  • Why downvote?? It fixes the js array construction, that he was doing wrong. Commented Jan 9, 2014 at 12:36
0

if u hav a php array $sites, u need to add it to js array sites

<?php
$sit="";
foreach($sites as $ar)
{
    if($sit=="")
    {
        $sit=$ar;
    }
    else
    {
        $sit=$sit.",".$ar;
    }
}
?>

in js:

var sites = [<?php echo $sit;] ?>;
4
  • What if $sit contains a ','? Or a ']'? Commented Jan 9, 2014 at 12:40
  • its variable to store the values seperated with comma, after all the iteration sit contains all the values in array seperated by comma. Commented Jan 9, 2014 at 12:41
  • Oh yeah. But you know what I mean - the PHP string isn't being escaped and could generate invalid JS. Commented Jan 9, 2014 at 12:49
  • no its working fine for meeee,,, me using this for generating chart using high charts,,,, no error for me... Commented Jan 9, 2014 at 12:55

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.