-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.

2
  • 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. Commented Apr 25, 2013 at 21:59
  • Take a look at this question+answer to understand more of what you need to do. Commented Apr 25, 2013 at 22:02

2 Answers 2

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

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.