1

I have the following problem,

I'm sending a json_encoded data array from PHP to javascript. The actual JSON I'm receiving from PHP is shown below,

{
    "route": "1(M)A",
    "startSignal": "AN1",
    "startX": 100,
    "startY": 320,
    "direction": "down",
    "endSignal": "AN3",
    "endX": 1100,
    "endY": 320,
    "1AT": {
        "length": "100",
        "xStart": 100,
        "yStart": 320,
        "xFinish": 133.33333333333,
        "yFinish": 320
    },
    "1BT": {
        "length": "100",
        "xStart": 133.33333333333,
        "yStart": 320,
        "xFinish": 166.66666666667,
        "yFinish": 320
    },
    "1CT": {
        "length": "100",
        "xStart": 166.66666666667,
        "yStart": 320,
        "xFinish": 200,
        "yFinish": 320
    },
    "1DT": {
        "length": "100",
        "xStart": 200,
        "yStart": 320,
        "xFinish": 233.33333333333,
        "yFinish": 320
    }
}

In my .JS file, I'm getting the "echo json_encode($dataArray)" as follows,

$.ajax({                              
    url: "visualiser/visualiser_RouteList.php",
    data: "JSON",
    async: false,
    success: function(data){
        console.log(data);
    } 
});

The problem is that for some reason ajax reads the json in the following manner..(every character in JSON is stored as an array element.. so I can't retrieve a particular value of an associated name for example, getting "1(M)A" String value from associated name "route"..

data[0] = "{"
data[1] = " \" "
data[2] = "r" 
data[3] = "o" 

where am I going wrong?

============================================================================

further edit after receiving the comments,

Thanks everyone, I did change the data to 'dataType = "json"' but it still doesn't work..I really wanted to see [object, object....] when I do 'console.log(data) but nothing is printing out so there must be something wrong with my $array in the PHP source, not sure if anyone's willing do have look but I'm posting my php source here..(Sorry for being a total noob at PHP..I can't seem to be doing anything but pulling my hair out)

=============================================================================

    <?php 
    // Route registration form processing php
    // accepts a serialized data from myRoute.js
    //header('Content-Type: application/json');
    include_once ("dbConnect.php");

    //$sql="SELECT * FROM route";

    $routeStarts = "SELECT id, idSignal, km, line_name, direction, route.type
                    FROM route
                    JOIN signals
                    ON startSignal = idSignal";

    $routeEnds = "SELECT id, idSignal, km, line_name, direction, route.type
                    FROM route
                    JOIN signals
                    ON endSignal = idSignal";

    $routeTracks = "SELECT idRoute, signalName, routeTrack.idTrack, length, firstTrack, pointTrack, prevTrack 
                    FROM routeTrack
                    JOIN track
                    ON routeTrack.idTrack = track.idTrack";
                    /*ORDER BY idRoute";*/      
    $pointTracks = "SELECT idRoute, routeTrack.idTrack, aLocation, bLocation, aLine, bLine, aTrack, bTrack, type 
                    FROM routeTrack
                    JOIN points
                    ON routeTrack.idTrack = aTrack";                                        


    $sqlMax = "SELECT MAX(km) FROM signals";
    $sqlMin = "SELECT MIN(km) FROM signals";

    $max = mysqli_query($con, $sqlMax);
    $min = mysqli_query($con, $sqlMin);
    $start = mysqli_query($con, $routeStarts);


    $rowMax = mysqli_fetch_array($max);
    $rowMin = mysqli_fetch_array($min); 
    $range = $rowMax[0] - $rowMin[0];

    // For each route picks up the start signal
    while($row1 = mysqli_fetch_array($start)){
        $resultArray = array();

        $routeName = $row1['id'];
        $startSig = $row1['idSignal'];
        $startX = ((($row1['km'] - $rowMin[0]) / $range)*1000)+100;
        $startY = getYcoordinate($row1['line_name']);
        $direction = $row1['direction'];

        $resultArray['route'] = $routeName; 
        $resultArray['startSignal'] = $startSig; 
        $resultArray['startX'] = $startX;
        $resultArray['startY'] = $startY;
        $resultArray['direction'] = $direction;

        //picking up the end signal for the same route
        $end = mysqli_query($con, $routeEnds);
        while($row2 = mysqli_fetch_array($end)){
            if ($row2['id'] == $routeName){
                $endSignal = $row2['idSignal'];
                $endX = ((($row2['km'] - $rowMin[0]) / $range)*1000)+100;
                $endY = getYcoordinate($row2['line_name']);

                $resultArray['endSignal'] = $endSignal; 
                $resultArray['endX'] = $endX;
                $resultArray['endY'] = $endY;
            }
        }
        //now filtering out the track for the particular route , non-point
        if ($resultArray['startY'] == $resultArray['endY']){
            $tracks = mysqli_query($con, $routeTracks);
            while($row3 = mysqli_fetch_array($tracks)){
                if ($row3['idRoute'] == $routeName && $row3['firstTrack'] == 1 ){
                    $xFinish = getXfinish($range, $row3['length']);
                    $resultArray[$row3['idTrack']] = ['length'=>$row3['length'], 
                                                      'xStart'=>$startX, 
                                                      'yStart'=>$startY,   
                                                      'xFinish'=>$startX + $xFinish,
                                                      'yFinish'=>$startY ];

                } else if ($row3['idRoute'] == $routeName && $row3['firstTrack'] != 1 ){
                    foreach ($resultArray as $key => $value) {
                        if ($row3['prevTrack'] == $key){
                            $prevXstart = $resultArray[$key]['xFinish'];
                            $prevYstart = $resultArray[$key]['yFinish'];
                        }
                    }
                    $xFinish = getXfinish($range, $row3['length']);
                    $resultArray[$row3['idTrack']] = ['length'=>$row3['length'], 
                                                      'xStart'=>$prevXstart, 
                                                      'yStart'=>$prevYstart,   
                                                      'xFinish'=>$prevXstart + $xFinish,
                                                      'yFinish'=>$prevYstart
                                                      ];
                }

            }
        //now filtering out the track for plotting point tracks 
        } else {
            $tracks = mysqli_query($con, $routeTracks);
            while($row3 = mysqli_fetch_array($tracks)){
                if ($row3['idRoute'] == $routeName && $row3['firstTrack'] == 1 && $row3['pointTrack'] != 1){
                    $xFinish = getXfinish($range, $row3['length']);
                    $resultArray[$row3['idTrack']] = ['length'=>$row3['length'], 
                                                      'xStart'=>$startX, 
                                                      'yStart'=>$startY,   
                                                      'xFinish'=>$startX + $xFinish,
                                                      'yFinish'=>$startY ];

                } else if ($row3['idRoute'] == $routeName && $row3['firstTrack'] != 1 && $row3['pointTrack'] != 1){
                    foreach ($resultArray as $key => $value) {
                        if ($row3['prevTrack'] == $key){
                            $prevXstart = $resultArray[$key]['xFinish'];
                            $prevYstart = $resultArray[$key]['yFinish'];
                        }
                    }
                    $xFinish = getXfinish($range, $row3['length']);
                    $resultArray[$row3['idTrack']] = ['length'=>$row3['length'], 
                                                      'xStart'=>$prevXstart, 
                                                      'yStart'=>$prevYstart,   
                                                      'xFinish'=>$prevXstart + $xFinish,
                                                      'yFinish'=>$prevYstart
                                                      ];
                // first track and point track
                } else if ($row3['idRoute'] == $routeName && $row3['firstTrack'] == 1 && $row3['pointTrack'] == 1){
                    $pointTrack = mysqli_query($con, $pointTracks);


                // not first track and point track      
                } else if ($row3['idRoute'] == $routeName && $row3['firstTrack'] != 1 && $row3['pointTrack'] == 1){
                    foreach ($resultArray as $key => $value) {
                        if ($row3['prevTrack'] == $key){
                            $prevXstart = $resultArray[$key]['xFinish'];
                            $prevYstart = $resultArray[$key]['yFinish'];
                        }
                    }
                    $turnPoint = getXfinish($range, ($row3['length']/2));
                    $pointTrack = mysqli_query($con, $pointTracks);
                    while($row4 = mysqli_fetch_array($pointTrack)){ 
                        if ($row4['idTrack'] == $row3['idTrack']){
                                $yTurnEnd = getYcoordinate($row4['bLine']);
                        }
                    }                   

                    if ($row1['direction'] == 'down'){
                        $resultArray[$row3['idTrack']] = ['xStart'=>$prevXstart, 
                                                          'yStart'=>$prevYstart,
                                                          'xTurnStart'=> $prevXstart + $turnPoint,
                                                          'yTurnStart'=> $prevYstart,
                                                          'xFinish' => $prevXstart + $turnPoint + 50,
                                                          'yFinish' => $yTurnEnd
                                                          ];
                    } else {
                        $resultArray[$row3['idTrack']] = ['xStart'=>$prevXstart, 
                                                          'yStart'=>$prevYstart,
                                                          'xTurnStart'=> $prevXstart - $turnPoint,
                                                          'yTurnStart'=> $prevYstart,
                                                          'xFinish' => $prevXstart - $turnPoint -50,
                                                          'yFinish' => $yTurnEnd
                                                          ];
                    }
                }

            }
        }
        //print_r($resultArray);
        //header('Content-Type: application/json');
        echo json_encode($resultArray); 
        unset($resultArray);
    }


function getYcoordinate($line_name){
    if ($line_name == 'downSuburban'){
        $y= (800/20) * 8; // down Suburban
      } else if ($line_name == 'upSuburban'){
        $y= (800/20) * 10; // up Suburban
      } else if ($line_name =='downMain'){
        $y= (800/20) * 12; // down Main
      } else if ($line_name == 'upMain'){
        $y= (800/20) * 14; // up Main
      }
    return $y;    
}   

function getXfinish($trackRange, $trackLength){

    return ($trackLength/($trackRange*1000))*1000;
}


//  $dataArray = array();
//  $dataArray[] = array('idRoute'=>$row['id'], 'startSignal'=>$row['startSignal']);


mysqli_close($con);
?>
lukieleetronic
  • 623
  • 7
  • 10
  • 23

4 Answers4

4

You need the dataType rather the data.

$.ajax({                              
    url: "visualiser/visualiser_RouteList.php",
    dataType: "JSON",
    async: false,
    success: function(data){
        console.log(data);
    } 
});
  • I tried it out but console does not return anything when I should be expecting to see [ object, object, object...]. I think there is a problem with my php source, i think something screwy is happening with encoding 2D array.. – lukieleetronic May 24 '14 at 15:44
  • Are you properly `json_encode()` the array before echoing it? It should not produce any errors unless they're JSON errors. Can you verify it's a valid json by encoding it, then trying to decode it using [json_decode](http://www.php.net/manual/en/function.json-decode.php) and then checking with [json_last_error](http://www.php.net/manual/en/function.json-last-error.php) ? –  May 24 '14 at 16:00
  • By checking quickly your updated question, i saw that after your while loop (which is in global space rather in some function) you encode properly the array, then don't [exit](http://www.php.net/manual/en/function.exit.php) immediately? put an **exit;** after printing the json encoded array. –  May 24 '14 at 16:07
  • OMG... putting the exit after the json_encode() works!!! but...why..? – lukieleetronic May 24 '14 at 16:14
  • Because somewhere after the json_encode() you send some **whitespace** as well :) (probably). Get the habit to write an `exit;` anytime you finished with information sent back to client (or `return;`). –  May 24 '14 at 16:16
1

Your response is not being recognised as JSON, so it is not being deserialised. Presently it is being received as a string, hence why accessing by index is giving you the character of the string at that position.

You either need to set the headers in the response in PHP to JSON, or force the jQuery to deserialise it for you using dataType: 'json':

$.ajax({                              
    url: "visualiser/visualiser_RouteList.php",
    dataType: 'json',
    async: false,
    success: function(data){
        console.log(data);
    } 
});

Also, when the response is correctly deserialised to an object, you cannot access it using indexes. You need to use the keys, like this:

data.route; // = '1(M)A'
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • I did try out with dataType:'json' but then the console doesn't display anything this time like the comment I made above... so that's the reason I tried to use data instead of dataType.. when I tried to do it with a simple array it works perfectly so there must be something going on in the php source.. – lukieleetronic May 24 '14 at 15:49
0

As explained in this question & answer thread here, instead of data use dataType and instead of uppercase JSON try using lowercase json:

$.ajax({                              
    url: "visualiser/visualiser_RouteList.php",
    dataType: "json",
    async: false,
    success: function(data){
        console.log(data);
    } 
});
Community
  • 1
  • 1
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
0
$.ajax({                              
    url: "Url",
    dataType: 'JSON',//'datatype the ajax function expects',
    type: "post or get",//action type
    data:data to be posted,
    async: false,
    success: function(data){
        console.log(data);
    } 
});,

refer this for more http://api.jquery.com/jquery.ajax/

g-newa
  • 459
  • 3
  • 10