0

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
user123_456
  • 5,635
  • 26
  • 84
  • 140
  • So, what is the question? Or the problem? – Havelock Oct 18 '12 at 13:01
  • I want to use a javascript. So when I get results I need to get them with ajax and then I need to fill the array with the javascript and not with the php – user123_456 Oct 18 '12 at 13:02
  • I don't like the look of your `$coordinates`: `new google.maps.LatLng(' . $row['Latitude'] . ', ' . $row['Longitude'] . ')` looks like `eval` is immanent. please, please, please don't use `eval` – Elias Van Ootegem Oct 18 '12 at 13:03
  • I need to change var flighPlanCoordinates to be all javascript – user123_456 Oct 18 '12 at 13:03
  • @EliasVanOotegem how would you form it? – user123_456 Oct 18 '12 at 13:04
  • @denonth: Sorry, can't delete the comment (yet)... the `var flightPlanCoordinates` bit hasn't got anything to do with ajax, right? – Elias Van Ootegem Oct 18 '12 at 13:06
  • I need to fill that variable with the results that will come back from ajax. So ajax will return me an array to a javascript variable and then I need to fill `var flighPlanCoordinates` with that results – user123_456 Oct 18 '12 at 13:07
  • @denonth: check my answer: AJAX is _Asynchronous_, so you need a `success` callback. The data should be returned in `JSON` format, too. I also suggested a slightly different approach that doesn't require eval to create the new google objects – Elias Van Ootegem Oct 18 '12 at 13:13

4 Answers4

4

Have you seen json_encode? This should do the magic for you.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
1

Ok, reading the comments, it appears to be the case that var flightPlanCoordinates should be assigned the return value of an ajax call. In that case:

var flightPlanCoordinates = [];
$.ajax({type: 'POST',
        url: 'history.php',
        data: {'query': url},
        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);
            }
        }
    });

And, to avoid eval, just return the data like so:

while ($row = mysqli_fetch_assoc($result))
{
    $coordinates[] = array('x' => $row['Latitude'], 'y' => $row['Longitude']);
}
echo json_encode($coordinates);//send as JSON object

That should do the trick

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • It's perfectly simple: your requesting the data via AJAX calls: the JS has allready been sent to the client, so you can't add anything to that code. instead, you request the data and send it [JSON-encoded](http://www.php.net/json_encode). jQuery will parse this for you, and give you an array of objects to play with... _only in the `success` function_, mind you. In this function, you can then process the data further, in this case: instantiate new objects. – Elias Van Ootegem Oct 18 '12 at 13:20
  • I am getting this error: `Uncaught TypeError: Cannot set property '0' of undefined` at this line `flightPlanCoordinates[i] = new google.maps.LatLng(data[i].x,data[i].y);` and I have data in the array – user123_456 Oct 19 '12 at 18:53
  • post your current `$.ajax` code, bc it could be any of a million things... you're goign to have to narrow it down – Elias Van Ootegem Oct 19 '12 at 21:22
  • I have edited my question with the new problem. Only one thing that I have changed is that I have use `mysql_fetch_assoc() ` and you have used `mysqli` but I don't think that this should be the problem as I am getting response from the server – user123_456 Oct 20 '12 at 10:25
  • @denonth, the fetched data looks like a php var_dump, what does your console say when you `console.log(data)` in the success callback? – Elias Van Ootegem Oct 21 '12 at 11:35
  • I am getting valid JSON data: `[{"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"}] ` – user123_456 Oct 21 '12 at 11:47
  • Try declaring `flightPlanCoordinates` as a global variable (obviously, I don't approve of global vars, but since I have no context, that's all I can suggest): `var flightPlanCoordinates = [];`<-- on the very top of your script – Elias Van Ootegem Oct 21 '12 at 18:02
  • Hi Elias, I have tried what you said and I don't have error anymore but problem is that `data` has records as I wrote before but when I go in the for loop `flighPlanCoordinates` is filling an array but x and y have `Nan` values?? Any idea? and I data is recieved – user123_456 Oct 22 '12 at 16:25
  • I suspect that you're encountering the JS [float precision](http://stackoverflow.com/questions/1458633/elegant-workaround-for-javascript-floating-point-number-problem) problem. Perhaps, judging by the data you posted as a comment here, you'd be fine with this as a quick fix: `new google.maps.LatLng(+(data[i].x.substring(0,5)),+(data[i].y.substring(0,5)));` – Elias Van Ootegem Oct 22 '12 at 19:19
  • Okay I will try that but honestly I need all decimal places as these are coordinates. So the "bigger" number gives me mire realistic point on the map :) – user123_456 Oct 22 '12 at 19:26
  • @denonth: I understand that, but JS floats have their limits... as indeed do all FP numbers in all languages. [This might be a worth-while link](http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference) a bit dry, but quite useful. If you want to know why this problem exists, and will continue to exist, [here's an even drier, but _very interesting_ paper](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Elias Van Ootegem Oct 22 '12 at 19:31
  • Thank you for your effort. But there is another error now: `Cannot call method 'substring' of undefined ` any idea? – user123_456 Oct 22 '12 at 20:27
  • What happens if you `JSON.parse(data[i]).x`, try `console.log(data[i]);` and make sure `data[i]` is an object and not a string – Elias Van Ootegem Oct 22 '12 at 20:37
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/18429/discussion-between-denonth-and-elias-van-ootegem) – user123_456 Oct 22 '12 at 20:38
-1
var flightPlanCoordinates = <?php echo json_encode($coordinates); ?>
-1
<script>  
  var coordinates = new Array();
    <?php
        foreach($coordinates as $key => $value) {
    ?>
        coordinates[<?php echo $key; ?>] = [<?php echo $value; ?>];
    <?php
         }
    ?>
</script>

This pass the array from php to javascript

Baronth
  • 981
  • 7
  • 13