Help me to understand

Asked

Viewed 58 times

-1

Use this script to send information to the Jsonplaceholder api. I would like to understand why the following snippets:

Why should I serialize before using stringify?

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

Because in sucess I must put the 'date' inside the Function?

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

Follow the full code and thank you for your 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;
        });
    });

1 answer

1


"Why should I serialize before using stringify?"

To make the call Ajax you would need to assemble each value you send, whether in an object:

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

or in a querystring:

?nome=fulano&idade=ide

And the serialize will set it up for you. The stringify will transform an object to a JSON string, for example:

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

In your example this is not necessary.

"Because in sucess I must put the 'date' inside the Function?"

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

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

  • 1

    stringify is not necessary after giving a serialize in the form, where: The serialize() method creates a text string encoded for URL.

  • Thank you and I understood your explanation very well! In the case in question, I am sending the data in Json to an api and tested it without using stringify and it worked! From what I understand, the 'date' method already mounts json automatically?

  • In fact who mounts the response json is the api, the variable data receive this json, it would be something like: var data = resuladoApi("https://jsonplaceholder.typicode.com/posts"); This is just an illustrative example

  • then the 'date' serves to 'RECEIVE' the answer and not 'SEND' the answer, correct? In the script in question, who assembles the json to send to the api?

  • That line: var dados = $(this).serialize(); in this case, this is the form (form), i.e., data receives data from form fields.

  • Thanks brother for the help!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.