-10

I can't call PHP-function in Javascript. My code:

function clearDatabase(){
$str_sql_query = "TRUNCATE TABLE categories";
if (!$result = mysql_query($str_sql_query, $link))
{
    echo "<br>Bad request<br>";
    exit();
}
echo "All deleted!";
}

echo "<script type=\"text/javascript\">
 function clickClearButton()
 {
     <?php clearDatabase(); ?> //This function don't call
 }
 </script>";

I already tried "<?php clearDatabase(); ?>", \"<?php clearDatabase(); ?>\". clearDatabase();. What i doing wrong? Thank you.

Svyatoslav
  • 1,350
  • 12
  • 19
  • PHP is a server side language and Javascript in a client side one. You can right Javascript in PHP code, but you can't access PHP functions in Javascript. You should really try to learn some more regarding web application development. – Rolando Isidoro Apr 25 '13 at 21:59
  • Take a look at [this question+answer](http://stackoverflow.com/questions/557778/how-to-dynamically-call-a-php-function-in-javascript?rq=1) to understand more of what you need to do. – Chris Forrence Apr 25 '13 at 22:02

2 Answers2

1

PHP is run on server side and not Client side like JavaScript, you need to dynamically load the php to do this. (preferably with ajax)

A simple solution would be to put the php code into a new file called X.js then create an empty <script id="loadscript" src="#"> tag then change the src with javascript document.getElementbyId("loadscript").src="x.js"; would run the code

Iesus Sonesson
  • 854
  • 6
  • 12
0

You can't do this, it won't work. Put that function in another page and then make an AJAX call to it from JavaScript.

Cezary Wojcik
  • 21,745
  • 6
  • 36
  • 36