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.
-
2I'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.Rob W– Rob W2011年10月06日 20:36:33 +00:00Commented Oct 6, 2011 at 20:36
-
Missing at least the HTML opening tagNettogrof– Nettogrof2011年10月06日 20:38:08 +00:00Commented Oct 6, 2011 at 20:38
-
maybe this is what you are looking for : stackoverflow.com/questions/6786640/…tereško– tereško2011年10月06日 20:47:43 +00:00Commented Oct 6, 2011 at 20:47
1 Answer 1
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