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 }),
– Erico Souza
Vlw @Ericosouza I will find out more about JSON
– Dtag