Shay Zambrovski Shay Zambrovski - 6 months ago 14
Ajax Question

Convert JSON property to int php

i have this code in javascript:

var oRows= [];
for(var i = 0 ; i < 3 ; i ++) {
var oItem = {name: "example", id: i};
oRows.push(oItem);
}
$.ajax({
url: '/savejson.php',
method: 'post',
data: { 'oRows': oRows }
}).done(function (data) {
console.log(data);
});


and code in the php:

<?php
$fp = fopen('/data/DecisionTableRows.json', 'w');
fwrite($fp, json_encode($_POST['oRows']));
fclose($fp);
?>


but in the JSON file
/data/DecisionTableRows.json
i still get the property Id as string, how i can write it as int?

Answer

The problem is that $_POST variables are always strings.

To avoid the headache of manually doing an is_numeric and casting on each one of them in PHP you can do this:

var oRows= [];
 for(var i = 0 ; i < 3 ; i ++) {
 var oItem = {name: "example", id: i};
 oRows.push(oItem);
}
 $.ajax({
   url: '/savejson.php',
   method: 'post',
   data: { 'oRows': JSON.stringify(oRows) }
 }).done(function (data) {
     console.log(data);
 });

and in PHP

<?php
        $fp = fopen('/data/DecisionTableRows.json', 'w');
        fwrite($fp, $_POST['oRows']);
        fclose($fp);
?>

This way you shift the responsibility of encoding to JSON over to JavaScript which does have the original data to work with.

Comments