ajax with jquery - data format

Asked

Viewed 150 times

3

A doubt. In this example:

This is just a test where the api-clients-edit.php page receives the data, saves 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" are 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 known that we can pass in the hand also, without using the serialize. But so it facilitates :)

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

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

1 answer

2


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

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

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

Source (free translation): 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 had to add the ID in the string "data".

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

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

  • I had already seen this original post. It says it’s useful when I want to process the results myself. I just didn’t understand. As an example of "process results"?

Browser other questions tagged

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