1

I execute a simple AJAX Request, where i select some data from a mysql database. When i pass my Array back to Javascript, it always converts all Values in my Array into String, doesn't matter if its datatype was integer or boolean in my database.

EDIT:

I just found out, that MySQLi always converts datatypes to string, so I guess thats the problem. json_encode works fine.. https://stackoverflow.com/a/5323169/4720149

SQL Statement

   function getAll()
   {
        // Get all  buildings
        $db = new db();

        $sql = "SELECT * FROM building";
        $result = $db->runQuery($sql);

        $rows = array();
        while($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }     

        return $rows;
   }  

PHP Controller File

function getBuildings(){

  $bu_db = new Building_Model();
  $buildings = $bu_db->getAll();

  echo json_encode($buildings);
}

Javascript file

var data = {
  action: "getBuildings"
};

$.ajax({
  type: "POST",
  dataType: "json",
  url: "controller/Building.php",
  data: data,
  success: function(data) {
    console.log(data);
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
     console.log("Error in AJAX Request: " + textStatus + ", " + errorThrown);
  }
});

Instead of keeping the original datatypes from the database, it turns all values into Strings:

Output

[Object, Object, Object, Object, Obje...]
>0: Object
>1: Object
>2: Object
>3: Object
   ActiveCost: "20"
   BuildEfc: "0"
   BuildSfx: "0"
   BuildingEfc: "0"
   BuildingID: "1"
   Name: "Vogtei I"
   ResidentLvLNeeded: "0"
   ...

Does anybody know this problem?

Thanks in Advance.

Community
  • 1
  • 1
Bluesight
  • 754
  • 1
  • 11
  • 29

2 Answers2

0

What PHP version do you use?

Try:

echo json_encode($buildings, JSON_NUMERIC_CHECK );

MrSimpleMind
  • 7,890
  • 3
  • 40
  • 45
  • I use PHP Version 5.5.8. I could do that, but there are some values who are really strings and look like integer and I don't want to convert them to integer. Isn't there a way to keep the original datatype? (String, Integer, also NULL) – Bluesight Mar 27 '15 at 10:33
0

Javascript has dynamic data types. So there is no specific data type for int string etc. same var object can hold all the data types. It will dynamically identify the type based on the operations you do on those variables.

Andromeda
  • 12,659
  • 20
  • 77
  • 103
  • I totally agree with that, but have a look at the php manual page: http://php.net/manual/en/function.json-encode.php in the example section, there are no quotes added to integer values. – Bluesight Mar 27 '15 at 10:36