Ajax date return behavior

Asked

Viewed 3,265 times

2

My doubt is technical.

I’d like to understand more about what happened. I spent a few days trying to solve a problem in my code. I found that the functions of ajax or of php were wrong. Two functions of PHP were very similar, however, one worked and the other did not. Both should return a variable $resposta, with an HTML code to be inserted on the page. Ex:

$resposta = '<span>Alô mundo!</span>';

At the end, I noticed that the one that worked had the lines of code:

echo $resposta;
return $resposta;

and the one that didn’t work had only

return $resposta

Turns out the echo command was what was really working. So my question is: if the ajax function said:

function chamaM(id_chamado){ //-------> Estava funcionando
    $.ajax({
        type: 'POST',
        url: 'scriptPHP3.php',
        data: 'id=' + id_chamado,
        success: function(data){
            $('#teste').html(data);
        }
   });
}

function chamaTb(id_chamado, id_m){ //-------> NÃO estava funcionando
    $.ajax({
        type: 'POST',
        url: 'scriptPHP3.php',
        data: { id: id_chamado, ind_m: id_m },
        success: function(data){
            $('#teste').html(data);
        }
   });
}

Why is 'Success' returning 'echo' and not 'Return'? I wonder why I only put echo to see if the function was working. Otherwise, I would be trying to understand the error so far. I am immensely grateful for the answer. If you need to, here’s the relevant code in HTML and PHP:

.HTML

    <div id="menu-container">
        <a id="m1" class="ativo">m1</a>
        <a id="m2">m2</a>
        <a id="m3">m3</a>
    </div><!-- #menu-container -->

    <div id="teste">/*DIV ONDE SERÁ POSTO O CONTEÚDO PROCESSADO*/</div>


.PHP

if (isset( $_POST["ind_m"] ) && isset( $_POST["id"] ) ) {
    cliqueTb( $_POST["id"], $_POST["ind_m"] );
} elseif (isset ($_POST["id"] ) ) {
    cliqueM( $_POST["id"] );
 }

function cliqueTb( x, y ) { //-------> NÃO estava funcionando
    PROCESSAMENTO;
    return $resposta;
}

function cliqueM( x ) { //-------> Estava funcionando
    PROCESSAMENTO;
    echo $resposta;     //-------> 'echo' retorna o valor e não o 'return'
    return $resposta;
}
  • Dude, I don’t know if it helps, but I believe you have to convert the data to JSON first. Thus: date: JSON.stringify({ id: id_called, ind_m: id_m }),

  • Vlw @Ericosouza I will find out more about JSON

2 answers

3


Your technical question has a very, very simple answer.

AJAX is a technique to be requested contents a "behind the scenes" address. This content is output that the server sent to the browser in response.

And how does an application send content? Echoing / "printing" something in the program. When the request is completed, that content will be shown to anyone who requested it, be it a person, be it a programmatic routine.

Return does not produce content, it shifts the program execution flow from the local scope of a function to the global/external:

$name = 'Bruno Augusto';

$age = getAge();

function getAge() {
    return 26;
}

echo 'Nome: ', $name, ' .Idade: ', $age; // Nome; bruno Augusto. Idade: 26

While defining variables, we are in the global/external scope. Hence we have a PHP function that has its own, local, independent scope. And then there’s the echo, back to the global scope, which shows the phrase.

Without the Return code execution would enter the function when it was invoked ($acts), but I would never leave her.

What if Return does not produce content, there will be no Response Body. And if it has no body, it has nothing to work with AJAX.

  • in case, what would be better? 1)put an echo out of function, receiving the 'Return $answer' from it. 2)or leave echo inside the function, without using Return. From what I understand, it is not good practice to make the second option.

  • The really ideal is for you to have at most two Excerpts throughout THE ENTIRE Application. But as this involves Object Orientation and a lot of unnecessary complication to the scope of the question, ALWAYS prefer a return inside a function because that way you can control the output as needed, either by simply positioning the element in HTML, or by interacting with CSS/JS.

  • Thank you @Bruno and everyone. You helped me a lot! I will improve my code according to what you taught me.

1

Your Javascript/jQuery code makes an HTTP request to the server. PHP receives, handles, and responds to this request. The two languages (Javascript and PHP) do not talk directly, only via requests and HTTP responses.

In the case of an HTML, an HTTP response is basically text, containing its HTML. The command echo PHP writes to the output of the program, which is what goes to the HTTP response. The return does not write on the output, only makes the function return a value to the caller (in PHP itself). And the call that did not work was on this line:

cliqueTb( $_POST["id"], $_POST["ind_m"] );

The line does nothing with the return of function. It could write the value returned in the program output, which would be another way to make the content appear in the HTTP response:

echo cliqueTb( $_POST["id"], $_POST["ind_m"] );

Browser other questions tagged

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