Reputation: 32003
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!
Upvotes: 9
Views: 7899
Reputation: 68526
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.
Upvotes: 6
Reputation: 2859
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.
Upvotes: 4