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 ?
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.
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.
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”);
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".
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 ..
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
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