Can I make a JavaScript call through PHP?

4

I'm in a doubt ... I have a PHP code, and when it gets to the "end of it" I would call a JavaScript!

Ex:

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

<script language="javascript">

function sucesso(a,b){
...
}
</script>
    
asked by anonymous 10.09.2014 / 16:18

5 answers

2

Tried:

<?php

   ...

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

Sorry, but I can not think of anything more "elegant."

    
10.09.2014 / 17:15
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>";
?>
    
10.09.2014 / 23:06
1

You can use:

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

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

<?
} //fim se
?>

But the alert (or any command) will be issued on the client side, not PHP. You can use echo, but I think it's better as above.

    
10.09.2014 / 18:14
1

In WordPress, values are passed from PHP pro javascript using "location", which is to print in% document% a PHP-> JS object, and the scripts called after the location will use that object to retrieve the values . Here's a basic example.

PHP / HTML in the file <head> :

<?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.php :

function teste_func() {
    alert( 'A:' + teste_obj.a + '\r\nB: ' + teste_obj.b );
}
    
10.09.2014 / 22:51
0

I do not know how technically, logic and security this is, but I do a lot of it myself to give an alert and sometimes to 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.br';";
    echo "</script>";

} else {

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

}

?>

View link script example. 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.

    
10.09.2014 / 16:29