Can I make a Javascript call through PHP?

Asked

Viewed 786 times

4

I’m in a doubt ... I have a PHP code, and when it reaches the "end of it" I would like to call a Javascript!

Ex:

<?
   ....
   sucesso('$a','$b');
?>

<script language="javascript">

function sucesso(a,b){
...
}
</script>
  • What do you mean by "call a javascript"? What behavior do you want to get?

  • Not possible. You can make javascript perform an asynchronous call to PHP via Ajax to get the parameters.

  • @Fábiolemoselizandro as demonstrated by my example, I would like php' to "execute" javascript when it is at the end!

  • @Beet as you say it is not possible to accomplish such a way. How should I perform the method you mentioned?

  • 2

    @Bruno the ideal would be to know what you want to do, to know what to use, if it is an AJAX call or if gives to solve everything with JS or other means...

  • What seems to be happening is a mess of technologies. As pointed out by @Inkeliz, Javascript is run by the client; PHP, by the server. If your PHP script has critical situations (validation of entries, possibility of releasing exceptions, unavailability of other servers/services, etc...), that is, there is no certainty about the result of the process, enclose the block that calls Javascript in an if (as Inkeliz did) because, when the user receives the client-side page, this script will only run if the process has resulted in success.

  • On the other hand, if it was the client side that requested the execution of PHP (via "AJAX" or similar) and this server script does not provide HTML as a return (i.e., the answer is given through XML, JSON, plain text or any other format), all it takes is for the PHP response to explain the result (echo "<sucesso />" or similar) and that Javascript, upon receiving the AJAX response, verify for itself (in an if on that client) that the server response was successful, and then arrange the call to the function.

  • @Ruipimentel the server can easily provide HTML for an AJAX request. I think what’s missing from this question is a little grounding, objective. What he wants to do we know is not possible, but we can help if we know why

  • 1

    Since you don’t explain the real problem you’re trying to solve (not the code bug), each answer offers a different alternative. Recommended: What is the "XY problem"?

Show 4 more comments

5 answers

2

Tried to:

<?php

   ...

   echo '<script language="javascript">';
   echo '    alert("fim");';
   echo '</script>';

I’m sorry, but I can’t think of anything more "elegant".

2

<script language="javascript">
function sucesso(a,b){
alert(a+b);
}
</script>

<?php
    $a = 2; 
    $b = 3;
    echo "<script>";
    echo "sucesso(".$a.",".$b.");";
    echo "</script>";
?>
  • Why did they vote against it? Okay, there is no explanation or proper warnings that doing this is probably a bad way, but it is the only answer that brings a solution applied to the example of the question...

  • 1

    @bfavaretto, exact, the only one. I couldn’t do the parse of the author’s goal, <loop> he speaks of X but I only see Y </warning>

  • No doubt the question has this problem, @brasofilo

1

You can use:

<? 
if($a and $b){ //se A e B
?>

<script>
alert('hello');//javascript
</script>

<?
} //fim se
?>

But, Alert (or any command) will be issued on the client side, and not by PHP. You can use "echo", but I think it’s better the way above.

1

In Wordpress, values are passed from PHP pro Javascript using "localization", which is to print on <head> of the document a PHP->JS object, and the scripts called after the location will use this object to rescue the values. Follow a basic example.

PHP/HTML in the file teste.php:

<?php
$a = 'valor 1';
$b = 'valor 2';
?><!doctype html>
<html lang="en">
<head>
    <title>Teste PHP/JS</title>
    <script language="javascript" type="text/javascript">
    var teste_obj = {
        'a': '<?php echo $a; ?>', 
        'b': '<?php echo $b; ?>' 
    };
    </script>
</head>
<body>
    <a href="#"id="play" onclick="teste_func();">Valor do objeto</a>
    <script src="teste.js"></script>
</body>
</html>

And the JS in the file teste.js:

function teste_func() {
    alert( 'A:' + teste_obj.a + '\r\nB: ' + teste_obj.b );
}
  • Well, I don’t answer exactly to which author asked, but as missed explain the problem you were trying to solve, appeared this fruit salad of different answers; stay there as alternatives to future visitors who are looking for something similar.

  • 1

    very well placed... If we cannot help the author, at least we will help all the other people in the universe :) hahahah!

  • 1

    @Ruipimentel, just now I was at Soen looking for some things, and the answers that helped me were the ones that were there by the middle of the field (in posts of 2, 3 years ago) :)

0

I do not know how far in technical terms, logic and security this is recommended but I do it myself a lot just to give an Alert and sometimes redirect the script even because of headers errors that I decide not to treat. An example:

<?php

header('Content-Type: text/html; charset=utf-8');

$logout = TRUE;

if($logout == FALSE){

    echo "<script type='text/javascript'>";
    echo "alert('Você foi deslogado com sucesso');";
    echo "location.href='http://google.com';";
    echo "</script>";

} else {

    echo "<script type='text/javascript'>";
    echo "alert('Você foi deslogado com sucesso');";
    echo "location.href='/questions/32062/tem-como-fazer-uma-chamada-javascript-pelo-php#32062';";
    echo "</script>";

}

?>

See link example of the script. Regardless of the type of work you have to do it is always possible to pull javascript, jquery or any javascript extension within PHP code.

  • Milestones, some users with enough score to view deleted answers pointed out that their answer is good and could contribute to the question, only pointing out that the errors with the header is because it probably has some content being written before, and the header should be the first thing to run on the server. You would not like to undo the exclusion?

  • 1

    This is a very interesting approach, however, the example was not the best, but worth +1

  • 1

    @Marcos Vinicius Nasc. Pereira, your 2 ifs generate an alert "You were successfully deployed", I think you forgot to change the text.

Browser other questions tagged

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