How do I convert formdata to json?

5

I have the following code:

var form = new FormData();
form.append('user',$("#user").val());
form.append('password',$("#password").val());
var data = JSON.stringify($(form).serialize());

but the var 'date' is getting null, look at the example: link

The intention is to send this data using $ .ajax:

$.ajax({
    url: "http://localhost:29199/default.aspx?tipo=autenticar",
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    xhr: function () {
        var myXhr = $.ajaxSettings.xhr();
        if (myXhr.upload) {
            myXhr.upload.addEventListener('progress', function (s) {
                console.log('PROGRESSO', s); 
            }, false);
        }
        return myXhr;
    },
    success: function (a, b, c) {
        console.log('SUCESSO', a, b, c);
    },
    error: function (a) { console.log('ERROR', a); }
});

On the server side I already have a structure to receive json and deserializes it into an object.

    
asked by anonymous 16.05.2017 / 15:56

1 answer

1

The idea of FormData is to be impervious to data manipulation attempts on the of the customer.

That is, when you insert something inside you can not take it. If this is enough, use FormData , this ensures that the browser only talks to the server without undesired looks.

If you are using base64, you have to use something to do a string with the input data. You can use jQuery ( .serialize() or .serialize() ) and in this case you have to give attribute name to the elements / inputs, and passing the DOM element instead of FormData.

With FormData:

var Dados = new FormData(); 
Dados.append('user', $("#user").val());
Dados.append('password', $("#password").val()); 

// ou passando o <form> diretamente:

var Dados = new FormData(document.querySelector('form')); 

$.ajax({
  url: "http://localhost:29199/default.aspx?tipo=autenticar",
  data: Dados,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
    alert(data);
  }
});

With jQuery (I leave the base64 conversion at your will, because there are several libraries to choose from):

var Dados = $(this).serialize(); 

// ou:

var Dados = JSON.stringify($(this).serializeArray()); 

$.ajax({
  url: "http://localhost:29199/default.aspx?tipo=autenticar",
  data: Dados,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
    alert(data);
  }
});

jsFiddle : link

Note : Base 64 on MDN < sup> In English

    
16.05.2017 / 16:50