0

So I have a php which gets set of coordinates from the database , I want it to run through a jquery variable. This is the PHP -

$sql = "SQL that works";
$vari = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($loc))
{echo "[";
 echo "''";
 echo $row['cor1'];
 echo ",";
 echo $row['cor2'];
 echo "]";
}

This is the jquery that I want it to pass through in this form -

var markers = [
['', 51.503454,-0.119562],
['', 51.499633,-0.124755]
];
2
  • 1
    why dont you use ajax call to prepare data? Commented May 31, 2017 at 21:34
  • 5
    Would it not be easier to json_encode() what you get back to work with the result set in jQuery? Commented May 31, 2017 at 21:34

2 Answers 2

1

Actually you have to change your php code like below:-

$sql = "SQL that works";
$vari = mysqli_query($con,$sql);
$data = array(); //create an rray variable
while($row = mysqli_fetch_assoc($loc)){ // use assoc for lighter $row array 
 $data[] = array('',$row['cor1'],$row['cor2']); // create sub-array and assign to final array
}

echo json_encode($data); //return final data to ajax

Note:-Now decode this json in your jQuery via parseJSON() and do further code.

Sign up to request clarification or add additional context in comments.

3 Comments

what if array value is too large? it can be worst.
@VK321 it depends what OP actually want to do with the data. he can use load more concept by using some limits to query
agree - though it's a better solution than what he is trying.
0

If you don't want to use ajax, you can do something like this.

For the PHP,

...
$vari   = mysqli_query($con,$sql);
$coOrds = mysqli_fetch_array($loc);
$coOrds = json_encode($coOrds);
?>

For the JS,

var coOrdsJson = <?php echo $coOrds; ?>;
var coOrds     = $.parseJSON(coOrdsJson);
var markersArr = [];

for (var i=0; i < coOrds.length; i++ ) {
    markersArr[] = "['', " + coOrds[i].cor1 + ", " + coOrds[i].cor2 + "]";
}

var markers = markersArr.join(',');
markers = "[" + markers + "]";

1 Comment

Needless to say - you wouldn't be able to put this JS into a separate JS file, unless you moved the PHP echo variable assign into global scope between <script> tags inside a .php file, before the JS file was included.

Your Answer

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