user5077994
user5077994

Reputation:

Parsed data PHP JSON to Ajax - have I missed something?

I have a issue with my code and I don't know what the problem is. I'm trying to move markers in a map with coordinates of the bus fleet. My method is to generate JSON with PHP and an Oracle database, then in JavaScript use the data to print a move of the markers...but I think the information is not getting through to the web map.

Please help.

The php (marks.php):

query oracle....

while (($row = oci_fetch_array($result, OCI_BOTH)) != false) {
  header('Content-Type: application/json');
  $data = array($row);
  echo json_encode($data);  
}  

The result:

{"0":"10\/07\/15","MAX(OP.TELEGRAMDATE)":"10\/07\/15","1":"12115","BUSNUMBER":"12115","2":"511031","STOPID":"511031","3":"-765320567","GPSX":"-765320567","4":"33334550","GPSY":"33334550","5":"A11","SHORTNAME":"A11"}

The JavaScript:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Real time</title>
<style>
      html, body, #map {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
 <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=true&amp;libraries=places&amp;language=es">
</script>
<script src="http://190.216.202.35/prueba/js/mapmark.js"></script>
</head>
  <body >
    <div id="map"></div>
  </body>




<script>
    var map;

        map = new google.maps.Map(document.getElementById("map"), {
            center : new google.maps.LatLng(3.4404103,-76.5077627),
            zoom : 13,
            mapTypeId : 'roadmap'
        });


  $.ajax({                
          type: "POST",
          dataType: "json",
          url: "marks.php",                  
          cache: false,
          success: function(data){
            alert(data[0]); //expected to return value1, but it returns undefined instead.
          }                 
        });

        </script>


</html>

I'm trying to at least alert data but nothing happened. Please help me to see what my problem is.

Upvotes: 0

Views: 130

Answers (1)

Marc B
Marc B

Reputation: 360592

You're fetching in a loop, and outputting JSON on every iteration. That's invalid. You're essentially producing this:

 {...}{...}{...}etc...

which is illegal JSON. You need to build an array inside the loop, then encode it AFTER the loop finishes:

$data = array();
while($row = fetch...) {
   $data[] = $row;
}
echo json_encode($data);

Since your JSON is illegal, javascript isn't decoding it at all (well, starts to decode it, then aborts once it hits the syntax errors).

Upvotes: 2

Related Questions