0

I am trying to populate JSON request with the data coming back from my phpsearch.php file (shown here)

<?php
include "base.php";
$name = $_GET["name"];
$query = "SELECT lat, lng FROM markers WHERE name = '".$name."'";
$result = mysql_query($query);
$json = array();
while($row = mysql_fetch_array ($result))     
{
  $bus = array(
        'lat' => $row['lat'],
        'lng' => $row['lng']
    );
    array_push($json, $bus);
}
$jsonstring = json_encode($json);
echo $jsonstring;
?>

The data shows in the console in this format:

[{"lat":"37.730267","lng":"-122.498589"}]

The route calculation function is at the bottom of the question, I previously had used an asynchronous JSON rewquest but this was causing the code to execjte before the origin value was set, now it is being set but it looks incorrect

How can I make sure my latitude and longitude results are in the correct JSON format? currently the JSON request looks like this:

 Request URL:https://maps.googleapis.com/maps/api/js/DirectionsService.Route?4b0&5m4&1m3&1m2&1dNaN&2dNaN&5m4&1m3&1m2&1d37.738029&2d-122.499481&6e1&8b1&12sen-GB&100b0&102b0&callback=_xdc_._1rqnjk&token=80599

Route calculation code:

  function calcRoute() {
        var startname = document.getElementById('start').value;
        var endname = document.getElementById('end').value;
        var waypts = [];
        var checkboxArray = document.getElementById('waypoints');
        for (var i = 0; i < checkboxArray.length; i++) {
          if (checkboxArray.options[i].selected == true) {
            waypts.push({
                location:checkboxArray[i].value,
                stopover:true});
          }
        }

$.ajax({
    url:'phpsearch2.php', 
    dataType:'html', 
    data:{name:startname},
    async:false,
    success:function (result)
{
    console.log(result)
    origin = new google.maps.LatLng(result[0].lat, result[0].lng);
}});

    var end = new google.maps.LatLng('37.738029', '-122.499481');
    var request = {
            origin: origin,
            destination: end,
            waypoints: waypts,
            optimizeWaypoints: true,
            travelMode: google.maps.DirectionsTravelMode.WALKING
        };

            directionsService.route(request, function(response, status) {
        document.write('<b>'+ origin +'</b>');
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            var route = response.routes[0];
            var summaryPanel = document.getElementById('directions_panel');
            summaryPanel.innerHTML = '';
            // For each route, display summary information.
            for (var i = 0; i < route.legs.length; i++) {
              var routeSegment = i + 1;
              summaryPanel.innerHTML += '<b>Time for a Walkabout </b><br>';
              summaryPanel.innerHTML += '<b>From ' + startname + '   </b>';
              summaryPanel.innerHTML += '<b>to ' + endname + '('+ route.legs[i].distance.text +')</b><br>';
          } 
          }
        });
     }
  • The data you return is not JSON, yet you are telling jQuery to expect JSON. Synchronous "Ajax" requests are usually not good either. – Felix Kling Apr 07 '13 at 00:36
  • Is it possible to change phpsearch.php to return in JSON format? I just tried changing the return type in the AJAX request to HTML but my JSON request still doesn't have the correct data in it. Request GET /maps/api/js/DirectionsService.Route?4b0&5m4&1m3&1m2&1dNaN&2dNaN&5m4&1m3&1m2&1d37.738029&2d-122.499481&6e1&8b1&12sen-GB&100b0&102b0&callback=_xdc_._1rqnjk&token=73614 HTTP/1.1 – Mark Harrison Apr 07 '13 at 00:37
  • Of course. In your previous question it looked like you returned JSON (even if it was build manually). Why don't you do it as suggested [in the answer to your previous question](http://stackoverflow.com/a/15857238/218196)? – Felix Kling Apr 07 '13 at 00:39
  • Even if I wrap in a function as suggested in that question the JSON request still does not populate. I opened a new question to try and figure out how to get my data into the correct format, I thought it would be too confusing to try and keep updating that question. – Mark Harrison Apr 07 '13 at 00:42
  • Ah, even in your previous question, the format was not correct (it appears you had a trailing comma). As suggested, have a look at `json_encode`: http://php.net/manual/en/function.json-encode.php. – Felix Kling Apr 07 '13 at 00:43
  • 1
    *warning** your code is vulnerable to sql injection attacks! – Daniel A. White Apr 07 '13 at 00:53
  • I've updated my phpsearch code above, I've switched to JSON_ENCODE but the data is still not being sent correctly to the JSON request (also edited above) – Mark Harrison Apr 07 '13 at 00:53
  • Not only is it vulnerable to SQL injection, it's using a deprecated extension. Please switch to mysqli or PDO. –  Apr 07 '13 at 00:55
  • Thanks guys, I intend on sorting out the injection vulnerability before this goes live, but right now it's all local so it's not high priority, I just want to get my last function working first. – Mark Harrison Apr 07 '13 at 01:00

1 Answers1

1

The LatLng constructor takes two numbers as arguments, you're passing it a JSON object. Get the latitude and longitude properties out and pass the numbers directly, like this:

function (result){
    origin = new google.maps.LatLng(result[0].latitude, result[0].longitude);
}

I'm guessing on the specific properties, you may want to console.log(result) to see the exact object structure.

  • I'm giving that a go but for some reason I'm suddenly seeing this error: Warning: array_push() expects parameter 1 to be array, null given in C:\wamp\www\WalkaboutSF\phpsearch2.php – Mark Harrison Apr 07 '13 at 01:25
  • Is there a reason you're doing the looping and array_push() stuff? You're just trying to get one latlng, right? –  Apr 07 '13 at 01:34
  • You're probably getting that error because you're never declaring `$json`. Throw in a `$json = array();` –  Apr 07 '13 at 01:48
  • Hi Nathan, thanks for all the help. The reason for the looping is once I get this working I'll have to expand it so I can get multiple latitudes and longitudes. I've made the changes you suggested and updated my original post with the code and responses, unfortunately the JSON still isn't correct. – Mark Harrison Apr 07 '13 at 02:20
  • What do you see in the console? –  Apr 07 '13 at 02:23
  • The same as I put above: [{"lat":"37.730267","lng":"-122.498589"}] – Mark Harrison Apr 07 '13 at 02:24
  • Oh. Change the ajax to `dataType: 'json'` –  Apr 07 '13 at 02:27