How can I call a PHP Function inside a Javascript Function? This is what I have so far, but I don't think I'm doing it the right way.
Any suggestions?

<?php
function phpQuery(){

     $query = mysql_query("INSERT INTO mytable VALUES('','name','email')");

}
?>
<script type="text/javascript">
function delayQueries()
{
  timeoutID = window.setTimeout(doQueries, 2000);
}

function doQueries()
{
  var runQuery = "<?php phpQuery(); ?>";    
}
</script>

Recommended Answers

All 4 Replies

Eg.

<?php
$var=$_POST['check'];
if($check=="yes"){
/////************/////////////
}
?>
...
<script type="text/javascript">
function sub(){
document.form.check.value="yes"
document.form.submit();
}
</script>
<form action="" method="post" name="form">
<input type="hidden" name="check">
</form>
<input type="button" onclick="sub()" value="OK">

or with ajax!
Content of some file (sf.php)

<?php
////*************/////////
//query......
echo "OK";
?>

javascript/ajax

<script type="text/javascript">
function do(){
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=f(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//result (of "echo" in sf.php; "OK")
//in div element will write "OK"
document.getElementById('res').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","sf.php",true);
xmlhttp.send();
}
</script>
<div id='res'></div>
<input type="button" value="Do" onclick="Do">

Hey thanks for the examples. I am looking through trying to understand. I currently have the code on a couple test files. When clicking the button, nothing happens. I created the sf.php file and types what you have above. You can see it here:
http://www.sheetmusichaven.com/testinterval.php

I'll keep working at it until you are able to reply. Thanks

Edit:

I noticed the Function name: function do(){
was not capitalized like it was in the input tag. I changed that but still not displaying "OK".

Solution:
content of document that contains javascript/ajax...

<html>
<script type="text/javascript">
function da(){
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function f(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById('res').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","sf.php",true);
xmlhttp.send();
}
</script>
<body>
<input type="button" value="da" onclick="da()">
<div id='res'></div>
</body>
</html>

Checked!

Fixed. Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.