1
I am building an application using ajax (jquery) and php, when returning a json by php, jquery only takes the value if I have given an ECHO, if I return json through Return (I am using a function in php) jquery takes nothing.
jquery:
$.ajax({
url: BASE_URL+action,
data: $(this).serialize(),
type: "POST",
dataType: 'json',
success: function(result){
if(result.sucesso && !result.redireciona){
sucesso(result.mensagem);
}
if(!result.sucesso && !result.redireciona){
erro(result.mensagem);
}
if(result.redireciona)
{
location.href = result.link;
}else {
botao.prop("disabled", false).val(textBotao).css('opacity', '1');
}
},
error: function(){
botao.prop("disabled", false).val(textBotao).css('opacity', '1');
}
});
php:
public static function draw(){
$return = ["sucesso" => false, "redireciona" => false, "mensagem" => "Dados incorretos"];
return json_encode($return);
}
if I replace Return json_encode($Return) with echo json_encode($Return) works normally
Can anyone tell me if this should really happen? Thank you
For a file to be considered a
json
, its contents must contain a formatting patternjson
. When you make aecho
you are writing in the file, a Return is just returning a value that can be saved and used somewhere (saved in a variable for example). In short, theecho
will fill out the file, thejson_encode
will leave the data you are using to fill the file in a formatjson
. Theecho
is used to write to the file, thereturn
nay..– RickPariz
@Rickpariz but I’ve seen applications that use Return to return the values of the ajax request and work normally, so I’m surprised.
– Everton Neri
Depending on the structure (if it is a Framework I know there), you give only a Return and at the end of everything the structure calls some method to print on the screen.. I don’t know.. I’ve never particularly used and never seen Return used to return data for an ajax request.
– RickPariz
Oh I get it, it’s probably happening so thank you!
– Everton Neri
The Return does not display the values, for example, if you use the Laravel, you have to use a function to return the json
return response()->json($return);
– twsouza