Get return of a PHP function in JS

2

I'm starting now and my question is simple, I have a function created inside a class in a php file, and I want to get the return of that function in another javascript file, how do I do this? has something to do with ajax request?.

Php file, the function is something like this

public function minhaFunção()
{
[..]
        if($data!=0)
        {
            $prerollModel->prerollCount();

            $TemId = true;      
        }
        else
        {
            $TemId = false;     
        }

        return $TemId;
}

js file

var retorno = o retorno da função;
    
asked by anonymous 28.07.2016 / 17:22

1 answer

1

For this you can do a get through a simple ajax with jquery:

$.get("arquivo.php", function(data) {
  alert("Retorno: " +data);
});

For this I put "arquivo.php" put the path to your php script and change the return $TemId; of this to:

echo $TemId;

If you want to keep return $TempId then trace if the request came from ajax, if you do echo instead of return :

if (strtolower(filter_input(INPUT_SERVER, 'HTTP_X_REQUESTED_WITH')) === 'xmlhttprequest') {
   echo $TemId; // é ajax
}
else {
   return $TempId;
}

Functional example:

$.get("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty", function(data) {
  alert( "Retorno: " +data[0]); // [0] é só para este exemplo no seu não precisa do [0]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
28.07.2016 / 17:49