Is It possible to call a JavaScript function when I assign a value to a PHP variable?

时间:2016-02-12 19:44:11

标签: javascript php

As soon as I assign a value to my PHP variable $msg...

$msg = 'Some message'; 

... I want to call a JS function like this :

function showSuccess() { 
    alert('success')
}

Is it possible ?

3 个答案:

答案 0 :(得分:1)

If I understand you correctly, this will be the answer for your question.

$msg = 'some value your are going to assign';

if($msg) //checking $msg variable has some value or not
{
   print '<script type="text/javascript">showSuccess()</script>'; 

   /* or */

   print '<script type="text/javascript">alert("succeess")</script>'; 
}

答案 1 :(得分:0)

From what I understood, I think you would like to display a JS alert box when a desirable value is assigned to $msg. The following code may help.

<?php
$msg="Hello";  
  /*this is just to give you an idea 
  and so I am considering value of 
  $msg as hardcoded*/

if($msg!="")
/*may vary with the variable type,for
example if($msg!=0) in case of int*/
{
echo "<script>alert('successfull');</script>"
  /*echo adds stuff to the html
  document on the go*/
  /*the above JS code will be added to
  the HTML document and executed
  to display an alert box*/
}
?>

The basic structure remains the same even if the value of $msg is not hardcoded in your case. Only the condition in if may vary depending on the variable type.

You could also use if($msg). This simply checks if $msg has been assigned a value or not.

 if($msg!)
 //universal-checks if value is assigned
 {
 echo "<script>alert('successfull');</script>"
 }

答案 2 :(得分:0)

Maybe something in DOM like this, to keep php and javascript separate:

std::forward<T>(obj)