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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With