Good night,
if you specify in the options object sent to the method .ajax
the key dataType
, you tell what kind of data you are expecting from the server. In your case, it would be something like this:
jQuery.ajax({
/* ... */
dataType: 'json',
/*... */
})
However, as a standard (default), jQuery tries to guess - Intelligent Guess -, the received data format (xml, script, json...) from the server response. So this above parameter would only need to be informed if jQuery could not understand that the answer is a JSON (usually 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 cannot parse, it will invoke callback error
).
That said, then, its function-callback success
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 this:
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 above code is for the purpose of debug, as you will write to your browser console.
I do not know if this was your doubt (on how to manipulate the received data).
If you want to display a simple message, you can call the method alert
. This will show a dialog box with the message (very simple).
Or, if you want to insert this message into the body of the page in some way, or make interactions of elements, this involves manipulations in the DOM, and can be done easily 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 above example just adds to the <body>
one <p>
(paragraph) with a message.
Where do you want to show this data? in a table? in an Alert?
– Sergio
You want to get the property
user
?– Marconi
@Sergio at first would not have a specific location, only in
log
or even in aalert()
.– viana
@Marconi wants to get the elements returned from JSON from within the
data
. Not only theuser
, but other objects.– viana
@Acklay Would go through the properties without knowing what is coming? More or less that? http://answall.com/questions/127924/percorrer-um-array-sem-saber-seus-indices/127926#127926
– Marconi