Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormData sends boolean as string to server

I have the following input which is a toggle returns true , false

<input id="{{event.id}}" ng-model="event.is_active" type="checkbox" value="true" class="block__input" ng-class="{'input__toggle--active' :  event.is_active}">

and when I send it like this

 var formData = new FormData();
            console.log(scope.event.is_active);
            formData.append('is_active', scope.event.is_active);

In the server I receive false and true as strings 'true', 'false'

How to solve this problem ?

like image 612
user2099451 Avatar asked Nov 10 '15 07:11

user2099451


People also ask

Does all form data gets sent to the server as strings?

FormData will always be sent as strings. One way to solve the problem is to use JSON. Simply encode your values with JSON. stringify on the clientside.

How do you append boolean to form data?

append accepts only a USVString or a Blob . S you will have to convert your data to string and then parse it later on the backend. You can use JSON. stringify to convert your form object to a string.

How can we send Boolean value in FormData in Postman?

So even if you send a parameter like “active=true”, it is still a string, this is how the HTTP protocol works. Hope this helps clarify the mystery. var bflag = Boolean(“true”); var bflag1 = Boolean(“false”);

Can we convert string to boolean in Java?

To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".


2 Answers

FormData will always be sent as strings. One way to solve the problem is to use JSON. Simply encode your values with JSON.stringify on the clientside. On serverside you simply decode the values.

Clientside

var fd = new FormData;
var data = {
    name: 'john doe',
    active: true,
    count: 42
};
var prop;
for(prop in data){
    fd.append(prop, JSON.stringify(data[prop]));
}

// if you want to upload files, too
fd.append('file', file);

$http({
    method: 'post',
    url: '/api/upload',
    data: fd,
    transformRequest: angular.identity,
    headers:{ 'Content-Type': undefined }
});

Serverside (PHP, simplified)

$data = [];
foreach($_POST as $prop => $value){
    $data[$prop] = json_decode($value);
}
// $data contains the correct values now ..
like image 169
rckd Avatar answered Sep 25 '22 16:09

rckd


If you have a problem with boolean you need to send 0 or 1.

Example:

let data = new FormData()
data.append('type', '0')
data.append('typeSend', '1')

In many cases, the server will understand that this is a bool value: false = 0, true = 1

like image 35
JLomaka Avatar answered Sep 21 '22 16:09

JLomaka