1

Possible Duplicate:
How do I programatically set the value of a select box element using javascript?

I'm trying to update a table with the results of a query when a select option has changed. The following test code works fine. But when I try to update the query, it doesn't work. I'm guessing it has to do with the 'echo', but I cant get figure it out. Thanks.

<script type="text/javascript">
  function ChangeText(value)
  {
    document.getElementById("p1").innerHTML=value;
  }
</script>

<select onchange="ChangeText(value)">
  <option value="ONE">one</option>
  <option value="TWO">two</option>
  <option value="THREE">three</option>
  <option value="FOUR">four</option>
</select>

<?php
  $variable1 = '<p id="p1">place holder</p>';
  echo $variable1; 
?>

what doesn't work:

document.getElementById("country").innerHTML=value;

$country = '<p id="country">United States</p>'

$result = mysql_query("SELECT * FROM statistics WHERE (Country='$country')");

The result of that is a blank table when the page loads, I would have expected 'United States' to be the default value. And when I select something from the pulldown, it does nothing.

Community
  • 1
  • 1
topofsteel
  • 1,267
  • 6
  • 16
  • 25

2 Answers2

1

PHP is executed on the server-side, before the user ever sees the page. So once the user is looking at the page, PHP is done executing.

So you can't "update a PHP variable with Javascript, because Javascript runs on the client-side, which happens after PHP has completely finished executing.

You should look into AJAX.

Travesty3
  • 14,351
  • 6
  • 61
  • 98
  • I am aware of that. But what is going on in my test code that I'm able to update $variable1 with the select value and echo it without reloading the page? I was hopeful I could apply that to my query. – topofsteel Sep 17 '12 at 16:48
  • In order for Javascript to interact *in any way* with PHP, it will have to make a call back to the server. PHP only exists on the server, not on the client. So AJAX will allow you to take the value of the dropdown and send it back to a PHP script on the server so that you can do your query, without reloading the page. Trust me...look into AJAX. It's exactly what you need, it's not incredibly complicated, and I believe that almost every single web developer uses it at some point, and often. – Travesty3 Sep 17 '12 at 16:58
0

I think you have some confusion about how server-side scripting vs javascripting works. PHP code does not run on the client side. PHP code is executed by your server, and the results (everything echoed + HTML markup) is sent to the client's browser. If you want to dynamically update a page you would have to use a form and reload the page, or use AJAX.

thatidiotguy
  • 8,701
  • 13
  • 60
  • 105