Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are integers becoming strings when I POST using jquery.ajax to a PHP script

I have spent the last hour attempting to figure this out to no avail. There are many posts on SO about jQuery and ajax(), but I haven't been able to find one that deals with my specific issue.

The basics of my code:

On the client:

var data = {"id": 1};
j.ajax({
  type: "POST",
  url: "postTestingResult.php",
  data: {'data': data},
  dataType: "json",
  success: ajaxSuccess,
  error: ajaxError
});

On the server using PHP:

$data = $_POST['data'];
echo $data; //{"id": "1"}

Why is the integer value becoming a string? How do I prevent this? I really don't want to have to create a custom function to loop through my data object (which in reality is quite complex) to convert all the values.

Many thanks!

like image 747
Matthew Herbst Avatar asked Apr 01 '14 07:04

Matthew Herbst


2 Answers

When parameters are sent through $_GET or $_POST , They are interpreted as strings.

You may need to cast them appropriately to make them suit how it works for you.

like image 182
Shankar Narayana Damodaran Avatar answered Oct 05 '22 10:10

Shankar Narayana Damodaran


In your case, you need to json_decode the data you received. Then you will have variables in their the type you sent via Ajax.

$data = json_decode($_POST['data'], true);
// $data['id'] is now int

$_POST['data'] is a string as explained in other answers, but when you decode it you can inner elements get their proper types.

like image 26
mesutozer Avatar answered Oct 05 '22 11:10

mesutozer