Extract arrays and objects from JSON returned with jQuery

Question:

I'm making a request to a Web Service using jQuery like this:

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

jQuery.ajax({
     type: "POST",
     url: "http://meusite.com/test",
     data: dados,
     success: function( data )
     {
         // quero exibir os dados que estão dentro de data
      }
});

The return JSON is exactly that when the user login is WRONG.

{
    "error": true,
    "message": "Login failed. Incorrect credentials"
}

If the authentication is CORRECT, the result is this:

{
    "error": false,
    "user": [
        {
            "id": 2,
            "fullname": "Romero Brito",
            "email": "romerobrito@gmail.com",
            "created_at": "2017-01-20 01:03:48"
        }
    ]
}

How do I extract arrays and objects from JSON returned with jQuery? How do I display the message that is inside the message and those through the data ?

EDIT

At first the data can be listed simply in an alert() or even just in console.log() .

Answer:

Goodnight,

if you specify in the options object sent to the .ajax method the key dataType , you tell what type of data you are expecting from the server. In your case, it would be something like this:

jQuery.ajax({
     /* ... */
     dataType: 'json',
     /*... */
})

However , by default , jQuery tries to guess – Intelligent Guess – the format of the received data (xml, script, json…) from the server's response. So this parameter above would only need to be informed if jQuery could not understand that the response is a JSON (usually it is due to a badly formatted message by the server), or you want to make sure that the result will always be this (in this case , if jQuery fails to parse, it will invoke the callback error ).

That said, then your callback- success function will be invoked with the first parameter containing the formatted data ( parsed ) (in your case, a JavaScript object). And you can manipulate it as if you were manipulating a JavaScript object normally. Something like:

jQuery.ajax({
    /* ... */ 
    success: function(data, textStatus, jqXHR )
     {
         /* seu dado já deve estar no parâmetro data */
         console.log("Login com sucesso? ", !data.error);
         if (!data.error) {
            var user = data.user[0]; //seu user é um array, então pego o primeiro elemento dessa array, por exemplo
            console.log("Nome completo do usuário: ", user.fullname);
         }
     }
});

The code above is for debugging purposes only as it will write to the browser console.

I don't know if this was your question (about how to handle the data received).

If you want to display a simple message, you can call the alert method. This will bring up a dialog with the message (very simple).

Or, if you want to insert this message into the body of the page in some way, or do element interactions, that involves manipulations in the DOM, and can be easily done by jQuery . A very simple example:

jQuery.ajax({
    /* ... */ 
    success: function(data, textStatus, jqXHR )
    {
        var textMessage;
        if (data.error) {
            textMessage = "Ocorreu um erro ao relizar o login: " + data.message;
        } else {
            textMessage = "Login realizado com sucesso! Bem vindo, " + data.user[0].fullname + "!";
        }
        $("body").append( $("<p></p>", { text: textMessage }) );
    }
});

The example above just adds to the <body> a <p> (paragraph) with a message.

Scroll to Top