Get return of a PHP function in JS

Asked

Viewed 1,616 times

2

I’m starting now and my question is simple, I have a function created within a class in a php file, and I want to get the return of that function in another javascript file, how do I do that? has something to see 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;

1 answer

1


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

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

This is where I put the "arquivo.php" put the path to your php script and change the return $TemId; this time:

echo $TemId;

If you want to keep the return $TempId then track if the request came by ajax, if it comes 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>

Browser other questions tagged

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