Decoding JSON data from the PHP page using Jquery

advertisements

I want to take data from database and save it in an array. Like this

 var locations = [ ['Current', 18.53515053, 73.87944794, 2],

  ['VimanNagar', 18.5670762, 73.9084194, 1]
];

First of all I have created a php page

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "citytrans";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM driver_location";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
       echo json_encode($row);
    }
} else {
    echo "0 results";
}
$conn->close();
?>

which gives me below result

{"driver_id":"1","driver_lat":"18.53515053","driver_lng":"73.87944794","driver_code":"122"}{"driver_id":"2","driver_lat":"18.53640175","driver_lng":"73.88206482","driver_code":"133"}

Now I want to convert this into an array using Jquery (I want to decode it ), I just want drivers_lat and drivers_lng value from my jSON data fetched form the database show above.

I am using below code to parse the data form json

jQuery.ajax({
    url: baseurl +  "getdriverlocation.php",
    type: "JSON",
    async: false,
    success: function(data){
           var myArray = JSON.parse(data);
                console.log(myArray.driver_lat)
    }
});

but it is giving me error (shown below)

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 92 of the JSON data

I just want the two values from json data and save it in an array variable

Please help


Use this one..

jQuery.ajax({
url: baseurl +  "getdriverlocation.php",
type: "JSON",
async: false,
success: function(data){
       var myArray = jQuery.parseJSON(data);// instead of JSON.parse(data)
       jQuery(myArray).each(function( index, element ) {
         console.log(element.driver_lat)
       });
}
});