-2

I have the following code:

  private function html_Headers()
    {
        $data = '
        <!DOCTYPE HTML>
        <head>
    <script type="text/javascript">
    function getOptions(chosen){
    var selbox = document.myform.selectport;
  selbox.options.length = 0;
  if (chosen == "1") {
    selbox.options[selbox.options.length] = new Option("-----------------","0");
    }


    }
    </script>

    </head>';

I'm trying to run some php mysql queries within the getOptions() JS function. I tried writing tags but it didn't work. Does anyone see the problem here? Note that this is within a PHP class file.

3
  • 2
    I've spotted the problem: Your code is incomplete. Also.. You cannot directly run any serverside code (PHP) within a HTML document (JS), without sending a request to the server. Commented Oct 6, 2011 at 20:36
  • Missing at least the HTML opening tag Commented Oct 6, 2011 at 20:38
  • maybe this is what you are looking for : stackoverflow.com/questions/6786640/… Commented Oct 6, 2011 at 20:47

1 Answer 1

3

JavaScript is executed on the client, while PHP is interpreted on the server. That means: when the javascript is executed, your code is running already on the client side and PHP - Code is going to be pretty useless.

What you can do, is calling an PHP-file with a function over an AJAX-Call and parse the result back to the client. After this, you can do anything with the returned data, but you'll have to do it within JavaScript.

For AJAX-Calls, I usually use jQuery, because the calls are easy and browser differences are handled already for you.

$.ajax({
  type: "POST",         // POST or GET
  url: "query.php",     // the php-file, including your mysql query
  data: "name=John&location=Boston",  //data sent to the server (in this case as post-param)
  success: function(data){
    //function executed, when the call succeeds. variable data is the data returned from your php
  }
});

Of course, you can make AJAX-Calls without using jQuery, maybe you should have a look at quirksmode.org

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.