Ajax only returns if I put an "echo" instead of "return" in php

1

I'm 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 the json through the return (I'm using a function in php ) jquery does not catch anything.

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 really should happen? Thank you

    
asked by anonymous 08.01.2018 / 01:28

3 answers

2

To communicate from PHP to javascript you have to do it through a text output (echo / print) or other functions (remember http is a text-based protocol). The most correct is to leave the return at the end of the method and at the time of calling draw() add echo.

You can simplify the method for:

public static function draw(){
    return  json_encode(["sucesso" => false, "redireciona" => false, "mensagem" => "Dados incorretos"]);
}

At the time of calling:

echo classe::draw();
    
08.01.2018 / 12:50
2

Well, the ajax call reads the response from the server and this response must be processed as some kind of readable data, such as application/jsonou or text/html .

To write this data, you need echo of the server with PHP.

The return statement does not write data, it simply returns at the server level.

answered on the site in English

    
08.01.2018 / 12:47
2

According to link return is a control structure of the PHP language, so use -a exclusively in PHP for return values or return to the next execution point.

echo , according to link is characterized as a string function (although not behave as a function). What it does is write the strings in the output buffer.

In your case jQuery calls PHP through its HTTP server waiting for json output from this HTTP server. And to do this you should write to the output buffer, so this justifies why echo works and return does not.

    
08.01.2018 / 12:55