Help me understand

-1

I use this script to send information to the JsonPlaceholder api. I would like to understand why the following excerpts:

Why should I serialize before using stringify?

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

Why in success do I have to put the 'date' inside the function?

success: function(data) {
                    alert("Sucesso!")
                }

Follow the complete code and thank you for the answers!

        $(document).ready(function() {
        $("#formPost").submit(function() {
            var dados = $(this).serialize();
            console.log(dados);
            $.ajax({
                type: 'POST',
                url: 'https://jsonplaceholder.typicode.com/posts',
                data: JSON.stringify(dados),
                success: function(data) {
                    alert("Sucesso!")
                }
            });
            return false;
        });
    });
    
asked by anonymous 23.05.2018 / 16:27

1 answer

1

"Why should I serialize before using stringify?"

In order to make the call Ajax you would need to mount each value it will send, either in an object:

var parametros = {
   nome: 'fulano',
   idade: 18
};

or a querystring :

?nome=fulano&idade=ide

And serialize will set this up for you. The stringify will transform an object into a JSON string, for example:

JSON.stringify({ idade: 20 });     // vai retornar '{"idade":20}'

In your example this is not necessary.

Because the call Ajax , on success, will return something, a result, an object, and this has to be put into a variable, so success: function(data) Of course data can be any name, and this variable will receive the callback to https://jsonplaceholder.typicode.com/posts

EDIT was still editing the question when @ dont-panic made the comment, which is correct, so this example is not necessary

    
23.05.2018 / 16:35