0

User clicks on my site's url with a GET parameter like so:

www.mywebsite.com/index.php?name=Mark

Let's say index.php looks like that:

if(isset($_GET['param'])){
     MyPhpClass::staticFunction();
     exit();
}
include 'index.html';

Let's make index.html look like this:

<html>
<head></head>
<body><div id='greetings'>Hello</div></body>
</html>

What I want is to do is replace Hello with Hi there using the PHP staticFunction. Note: this is just a toy example. In reality I would like to simulate calling a Javascript function from a PHP function either by calling directly or having some global variable accessible for both.

I have tried something like this:

public static function staticFunction(){
     echo "<script type='text/javascript'>$('#greetings').innerHTML = 'Hi there'</script>";
}

But it doesn't seem to work which makes sense. Another thing that I've tried is setting a global variable in PHP and then trying to access it from JavaScript like so:

public static function staticFunction() {
    $GLOBALS['myglobalvariable'] = 'HiThere';
}

And then including a Javascript inside index.html:

var myglobalvariable = <?php echo $GLOBALS['myglobalvariable']; ?>;
if(myglobalvariable == 'HiThere') {
    $('#greetings').innerHTML = 'Hi there';
}

I suspect that I could make it work using one of the solutions I've mentioned (there might be some bugs there) but I would be very grateful for a suggestion for an elegant solution to the problem I described.

I by no means expect a full solution - a push in the right direction will be great. Thanks!

tsotsi
  • 683
  • 2
  • 8
  • 20
  • -------sry forget that, you ahve to keep in mind a html tag must define before it can acssesed via js. And dont forget to load jQuery and escape vars in js with single quotes – JOUM Sep 11 '16 at 20:57
  • I think that you can just define a variable in your index.php script and reference that in your html, e.g. $greeting = 'hi there', and then instead of 'Hello', enter . – Craig Sep 11 '16 at 20:59
  • Yes, those are the things that I've tried before coming here. Wasn't happy about them either :) – tsotsi Sep 11 '16 at 21:00
  • I would however like keep the default option in case the url is accessed without the GET request. Also, this is just a toy example, in reality I would like to simulate 'calling a Javascript function from a PHP function either by calling directly or having some global variable accessible for both' (see edit) – tsotsi Sep 11 '16 at 21:03
  • Just keep in mind how and in witch order the content is parsed via php. Then it should work. But if you want to talk about that questions you have to write down full functional code, dont now how much you can... – JOUM Sep 11 '16 at 21:05
  • And the `exit();` make the code not working – JOUM Sep 11 '16 at 21:07
  • 1
    http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming?rq=1 – JOUM Sep 11 '16 at 21:10

0 Answers0