How to send correct data types using ajax?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How to send correct data types using ajax?



I want send correct data types to server using ajax, I mean, I want server received boolean as boolean, integer as integer (not string) and so on...



I tried this, but server receives empty array when I check $_POST.


$_POST


params = "firts_step":true;

$.ajax(

contentType: "application/json",
type: "POST",
url: "url_here",
data: JSON.stringify(params),
success: function(msg)



);



if try this:


params = "firts_step":true;

$.ajax(

type: "POST",
url: "url_here",
data: params,
success: function(msg)



);



then there is data in $_POST array, though all values have string data type.


$_POST





All query strings are strings. If you want to send JSON to php, iirc, you have to read it off the body and parse it yourself.
– Taplar
Aug 6 at 16:47





Possible duplicate of Receive JSON POST with PHP
– Taplar
Aug 6 at 16:48




4 Answers
4



I don't know why you add two data objects to the ajax call. Remove the one without json.stringify and try this from the php side,


data


json.stringify


$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["firts_step"];





two data objects was just typo. I edited question, and this works fine, thank you.
– RIKI
Aug 6 at 17:07






@RIKI Glad to hear.
– Lasitha
Aug 6 at 17:07



If you select JSON as your content type, you will only be able to send data with the types specified by the JSON documentation. Also, before parsing your JSON make sure your object has the correct data types.



Because HTTP is a text protocol with no concept of booleans or integers everything must be stringified



for booleans test this


params = "firts_step":true ? 1 : 0;



and in php


$x = ($_POST['firts_step'] == 1 ) ? true : false;



or


params "firts_step":"TRUE" ;



and in php


$x = ($_POST['firts_step'] == "TRUE" ) ? true : false;



good luck



In php for boolean you can use the filter_var



example:


$params['first_step'] = filter_var( $params['first_step'], FILTER_VALIDATE_BOOLEAN);



here the manual: http://php.net/manual/en/function.filter-var.php





Why the downvote?
– Mike Aron
Aug 7 at 16:45






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS