user3682153
user3682153

Reputation: 21

How can I call a javascript function located in my html file from my php file?

In my index.html I have:

<head>
  <link rel="stylesheet" href="css/messi.min.css" />
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script src="js/messi.min.js"></script>
  <script type="text/javascript">
    function failureFunction(){
      new Messi('There was an error sending your message.', {title: 'Failure'});
    };      
    function successFunction(){
      new Messi('Success sending email', {title: 'Success'});
    };
  </script>
</head>
<body>
  <form class="form" id="form1" method="post" action="contactengine.php">
  ...
  </form>
</body>

And then in my contactengine.php I have:

$success = mail($EmailTo, $Subject, $Body, $Headers);

// redirect to success page 
if ($success){
  echo "<script type='text/javascript'>successFunction();</script>"; 
  print "<meta http-equiv=\"refresh\" content=\"0;URL=index.html\">";
}
else{
 echo "<script type='text/javascript'>failureFunction();</script>";
 print "<meta http-equiv=\"refresh\" content=\"0;URL=index.html\">";
}

My echo ... won't call the successFunction() though. I know the $success var is true because if I put an alert there it calls the alert and I know that my successFunction() works because I can call it from my index.html file with no problems. The messi library is located here for reference.

How can I correctly call the successFuntion() from my php file?

Upvotes: 1

Views: 483

Answers (1)

Ash
Ash

Reputation: 2605

May be you can move your JS functions inside a javascript file and include that file in the PHP or HTML pages where you need to call those functions.

js/customMessi.js

function failureFunction(){
  new Messi('There was an error sending your message.', {title: 'Failure'});
};      
function successFunction(){
  new Messi('Success sending email', {title: 'Success'});
};

and in your HTML file :

<head>
 <link rel="stylesheet" href="css/messi.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">   </script>
 <script src="js/messi.min.js"></script>
 <script src="js/customMessi.js"></script>
 </head>
<body>
 <form class="form" id="form1" method="post" action="contactengine.php">
   ...
  </form>
</body>

and in your contactengine.php file as well:

echo "<script type='text/javascript' src='js/customMessi.js'></script>";
...
$success = mail($EmailTo, $Subject, $Body, $Headers);

// redirect to success page 
if ($success){
  echo "<script type='text/javascript'>successFunction();</script>"; 
  print "<meta http-equiv=\"refresh\" content=\"0;URL=index.html\">";
}
else{
 echo "<script type='text/javascript'>failureFunction();</script>";
 print "<meta http-equiv=\"refresh\" content=\"0;URL=index.html\">";
}

Upvotes: 3

Related Questions