FormData sends boolean as string to server FormData sends boolean as string to server angularjs angularjs

FormData sends boolean as string to server


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, toofd.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


You could send each "checked item" as a string (which results in true) and not send the "unchecked items" (which could default to false on the server side.) For example:

Client Side (js/jquery)

var fd = new FormData();var foo = $('[name="foo"]').prop('checked');var bar = $('[name="bar"]').prop('checked');var is_active = $('[name="is_active"]').prop('checked');if (foo) fd.append('foo',foo);if (bar) fd.append('bar', bar);if (is_active) fd.append('is_active', is_active') 

Server Side (php/laravel)

$foobar = new FooBar();$foobar->foo = $request->foo ? true : false;$foobar->bar = $request->bar ? true : false;$foobar->is_active = $request->is_active ? true : false;

The ternary statements above will return false on null in php.