ajax with jquery - data format

3

A doubt. In this example:

This is just a test where the api-clients-edit.php page receives the data, saves it and returns the status.

var dados = $("#editarClientes").serialize();
dados += "&id="+meuID;

console.log(dados);

$.ajax({
  type: "POST",
  url: "../api/api-clientes-editar.php",
  data: dados,
  dataType: 'json',
  success: function(retorno,status){

    console.log(retorno);
    console.log(status);
  },

  error: function(retorno,status){
    console.log(retorno); 
    console.log(status);
  }

});

When the data is serialized, viewing the console.log, using "serialize" is in the format:

campo1=dado1&campo2=dado2&campo3=dado3

Now, if we use "serializeArray" the data is in the format:

campo1 : dado1, campo2: dado2, campo3: dado3

It is well known that we can pass on the hand too, without using the serialize. But this makes it easier:)

Question: When would it be useful to use one format or another?

Another thing. I needed to add the ID in the "data" string. That's why I used serialize. But if it was in the serializeArray format, how would you add this information?

    
asked by anonymous 24.12.2018 / 18:25

1 answer

2

serializeArray creates an array ( array ) (not a "json array" - there is no such thing); You can test this yourself with console.log($("#myform").serializeArray()) . On the other hand, serialize creates a string query that is part of an HTTP request. Both representations are equivalent in the sense that by using appropriate code you can convert one to the other without any ambiguity.

The reason both versions are available is serialize is most convenient when you just want to make an HTTP query (just put the result in the query string) while serializeArray is more convenient if you want to process the results yourself.

The jQuery AJAX methods do not care if you give them one or the other because they detect the type of the parameter and convert it to a string query if it is not already one, so that by the point that the request is made the outside observers can not tell what the original format of the parameters was.

  

Source: SOen - What's the difference between .serialize () and .serializeArray ()?

Complementing :

dados = 'campo1=dado1&campo2=dado2&campo3=dado3'; // String

dados = {campo1 : dado1, campo2: dado2, campo3: dado3} // Array
  

I needed to add the ID in the "data" string.

As string ( serialize() ): dados = dados+'&id=1234';

As array ( serializeArray() ): dados['id'] = 1234;

    
24.12.2018 / 18:40