MEX
MEX

Reputation: 119

Javascript Function with PHP IF

Hi there I want to ask something very simple , unfortunately I run out of ideas , I want a function when is being $GET to do a JavaScript function straight away, but I just want to make sure that's how you do it...

<script>
function watch()
document.getElementById("home").style.display="none"; 
document.getElementById("watch").style.display="block";
</script>	


<a href="index.php?id=8">8</a>

<?PHP
if(isset($_GET['id'])) {
watch ()  <<<ISSUE
//run that function if ittselts GET
}
?>

Upvotes: 1

Views: 200

Answers (4)

Replace the line with the issue with:

    echo "<script>watch() </script>";

Because watch is a Javascript function, and you are calling it like a PHP function.

Upvotes: 1

Shahzad Barkati
Shahzad Barkati

Reputation: 2526

Simply use like below:

<a href="index.php?id=8">8</a>
 <?PHP
   if(isset($_GET['id'])) {
     echo "<script> myFunction () {
                 ...........
          }
       </script>";
 ?>

Upvotes: 1

Prakhar Thakur
Prakhar Thakur

Reputation: 1229

There are two problems in your code

  1. you cannot name your function "function" since it is a keyword

  2. you'll need to echo the JavaScript function call with php so that it is printed on the document sent to client.

Upvotes: 1

Skatox
Skatox

Reputation: 4284

Is easy, just do the following:

<a href="index.php?id=8">8</a>

<script>
var myFunction = function() {  
 ...
};

<?php
if(isset($_GET['id'])) {
   echo 'myFunction();';
}
?>
</script>

When you receive the id parameter, it will print the code to run the JS function, just put this <script> tags just before </body> so it can be executed after the DOM has been lodaded.

Upvotes: 3

Related Questions