AJAX解析错误

I recently updated my PHP and code that used to work to parse my PHP to Ajax has stopped working. I changed my PHP to use PDO and had to change my return statement from using jsoncallback to simply json encode:

    <?php
    header('Content-type: application/json');


   $con  = new PDO('mysql:host=localhost;dbname=db;charset=utf8mb4;''root', 'pass', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));


   $sql = "SELECT idlocations, name, latitude, longitude FROM `locations`";
   $con->query("SET NAMES utf8");
   $result = $con->query($sql);


   $records = array();

   if($result !== false)
   {
         $records = $result->fetchAll(PDO::FETCH_ASSOC);

         print_r($records);
        //$_GET['jsoncallback'] . '(' . json_encode($records) . ');';

        echo json_encode($records);
   }
   else
   {
        print_r($con->errorInfo());
   }
  ?>

The code above will return the following:

    Array
    (
         [0] => Array
         (
               [idlocations] => 1
               [name] => BierMarkt
               [latitude] => -79.3708
               [longitude] => 43.6473
          )

         [1] => Array
         (
               [idlocations] => 2
               [name] => jacks
               [latitude] => -79.4200
               [longitude] => 43.6555
          )

  )
      [{"idlocations":"1","name":"BierMarkt","latitude":"-79.3708","longitude":"43.6473"},{"idlocations":"2","name":"jacks","latitude":"-79.4200","longitude":"43.6555"}]

However, when I try to use an ajax call from javascript, I receive the following error:

[object Object] : parsererrorSyntaxError: Unexpected token A in JSON at position 0

JS:

    function populateLocations()
    {   
        console.log("inside populate");
       //Get other locations from the DB
       $.ajax({
                url:'http://localhost/VibeSetter/services/getlocations.php',
                type: 'POST',
                dataType: "json",   
                timeout: 5000,
        success: function(data, status)
        {
            console.log("inside success");
            $.each(data, function(i,item)
            { 
                console.log("inside index");
                console.log("item.longitude");
                //pass to function to fill array
                populateLocationsArray(i+1,item.name, item.longitude, item.latitude);

            });
        },

        error: function(e, ts, et) { console.log(e + " : " + ts + et) }
    });
    }

      function populateLocationsArray(i, name, long, lat)
      {
            locations[i] = new Array(); 
            locations[i][0] = name;
            locations[i][1] = long;
           locations[i][2] = lat; 
      }

Can someone please help me understand why I cannot properly parse the output from my php? I have tried many different methods including removing 'dataType: "json"' and using JSON.parse on the results.

Thanks in advance

There are few errors in your code, such as:

  • See the following line,

    $con  = new PDO('mysql:host=localhost;dbname=db;charset=utf8mb4;''root', 'pass', ...
                                                                     ^ missing comma
    

    It should be,

    $con  = new PDO('mysql:host=localhost;dbname=db;charset=utf8mb4;','root', 'pass', ...
    
  • Remove this statement print_r($records); from your code.

  • See this statement,

    print_r($con->errorInfo());
    

    Since you're expecting a json object as response from the server, you have to encode the error information array. It should be,

    echo json_encode($con->errorInfo());
    

So your code should be like this:

<?php
    header('Content-type: application/json');

    $con  = new PDO('mysql:host=localhost;dbname=db;charset=utf8mb4;','root','pass', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

    $sql = "SELECT idlocations, name, latitude, longitude FROM `locations`";
    $con->query("SET NAMES utf8");
    $result = $con->query($sql);


    $records = array();
    if($result !== false){
        $records = $result->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($records);
    }else{
        echo json_encode($con->errorInfo());
    }
?>