0

I'm passing an object through ajax to a PHP file for processing like this:

var Obj = {id:1, name:"John", value:12.1};

$.ajax({
        url : "myfile.php",
        type : 'POST',
        data : Obj,
        success : function(data) {
            console.log(data);
});

My issue is when I receive the parameters on my $_POST variable everything is a string like id => "1" or value => "12.1". I would like these to be kept like an Int and a Float for example without additional conversions on the PHP side.

Is there an easy way to maintain the variable types?

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Carlos Alves Jorge
  • 1,919
  • 1
  • 13
  • 29
  • 4
    When PHP receives values from a submit, they will always be strings. You will need to cast them in PHP. The data in your `Obj` will be sent to the server like this: `id=1&name=John&value:12.1"`. As you can see, there's no way for PHP to know what type it should be. – M. Eriksson Jul 03 '19 at 15:33
  • 2
    If you want to retain type information then you should pass the data as a JSON string to your server and PHP can use `json_decode()` to retain variable types. – MonkeyZeus Jul 03 '19 at 15:34
  • You also need to FIX the syntax error in that javascript. Missing `}` in the `success` method – RiggsFolly Jul 03 '19 at 15:35

2 Answers2

1

You need to convert the values on PHP because PHP receives values as a string :

$data = $_POST['data'] ; 

$int = (int)$data['id']; // or   intval($data['id'])
$float = (float)$data['value']; // or  floatval($data['value'])
0

Is there an easy way to maintain the variable types?

Not really. The data format used to send the data doesn't carry any kind of type hinting.

You could use JSON instead.

You'd have to encode the data as JSON when you send it, and then explicitly decode it in PHP.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335