Hi all I need to return a results from PHP to Javascript.
Here is my PHP code and I need to form it to be used in javascript.
$result = dbMySql::Exec('SELECT Latitude,Longitude FROM data');
while ($row = mysqli_fetch_assoc($result))
$coordinates[] = 'new google.maps.LatLng(' . $row['Latitude'] . ', ' . $row['Longitude'] . ')';
I need to return an array $coordinates and implode it like this but with Javascript:
var flightPlanCoordinates = [<?php echo implode(',', $coordinates) ?>];
This is how I started in javascript:
$.ajax({
type: 'POST',
url: 'history.php',
data: {'query': url},
});
var flightPlanCoordinates = [<?php echo implode(',', $coordinates) ?>];
And I need to fill this variable with returned data and with the JOIN or some other function that does same thing as implode in PHP.
EDIT:
This is my ajax code:
$.ajax({
type: 'POST',
url: 'history.php',
data: {
'id_user':$('#select-choice-user').val(),
'reg_id':$('#select-choice-reg').val(),
'd_year1':$('#select-choice-year1').val(),
'd_month1': $('#select-choice-month1').val(),
'd_day1':$('#select-choice-day1').val(),
'd_year2':$('#select-choice-year2').val(),
'd_month2': $('#select-choice-month2').val(),
'd_day2':$('#select-choice-day2').val()
},
success: function(data)//callback to be executed when the response has been received
{
for (var i=0;i<data.length;i++)
{
flightPlanCoordinates[i] = new google.maps.LatLng(data[i].x,data[i].y);
}
}
});
These are returned values in JSON format:
[
{
"x": "46.5564266666667",
"y": "15.6467166666667"
},
{
"x": "46.5566583333333",
"y": "15.6465533333333"
},
{
"x": "46.5567416666667",
"y": "15.6465566666667"
},
{
"x": "46.556745",
"y": "15.646555"
},
{
"x": "46.5567366666667",
"y": "15.6465766666667"
},
{
"x": "46.55675",
"y": "15.6465933333333"
},
{
"x": "46.55677",
"y": "15.6466116666667"
},
{
"x": "46.5567766666667",
"y": "15.6466183333333"
},
{
"x": "46.5567783333333",
"y": "15.64662"
},
{
"x": "46.5567583333333",
"y": "15.6466066666667"
},
{
"x": "46.556725",
"y": "15.6465966666667"
},
{
"x": "46.5566983333333",
"y": "15.6465983333333"
}
]
I’ve checked in JSON validator and format is valid. So I have no idea what could be wrong.
I will put PHP code just to make sure that it is written as it should be:
$result = dbMySql::Exec($query);
while ($row = mysql_fetch_assoc($result))
{
$coordinates[] = array('x' => $row['Latitude'], 'y' => $row['Longitude']);
}
echo json_encode($coordinates);//send as JSON object
Type of the errors that I get in the console:
Uncaught Error: Invalid value for constructor parameter 0: undefined
Uncaught TypeError: Cannot set property '0' of undefined
Ok, reading the comments, it appears to be the case that
var flightPlanCoordinatesshould be assigned the return value of an ajax call. In that case:And, to avoid
eval, just return the data like so:That should do the trick