<SCRIPT language="Javascript">
function vote()
{
<?php
$date = date("Y-m-d");
//$vote = mysql_num_rows(mysql_query("SELECT * FROM funny_thumbs WHERE ip='$ip' AND date='$date' AND id='$p'"));
if (mysql_num_rows(mysql_query("SELECT * FROM funny_thumbs WHERE ip='$ip' AND date='$date' AND id='$p'")) < 1)
{
mysql_query("INSERT INTO funny_thumbs SET ip='$ip', type='1', date='$date', id='$p'");
}
if (mysql_num_rows(mysql_query("SELECT * FROM funny_thumbs WHERE ip='$ip' AND date='$date' AND id='$p'")) >= 1)
{
?>
alert("Jus jau balsavote !");
<?php
}
?>
}
</SCRIPT>
<td>
<a href="#">
<img src="img/thumbs_up.png" alt="LIKE" onclick="vote(); return false;"/>
</a>
</td>
I already set $ip and $p. When i refresh page, it insert string without clicking on the link. Why ?
You're trying to call PHP on an onclick event. PHP gets executed when the page is loaded (before you even see the HTML) and therefore it inserts the string. Then it displays the website to the user with a vote function that alerts the weird character string and does nothing else.
There seems to be a bit of misunderstanding of the fundamentals of how PHP and Javascript work.
PHP is a server sided scripting language. That means, that it is only executed on the webserver, before the page is delivered to the client. When the page is delivered to the client, it consists of markup (HTML), client-sided scripts (Javascript), as well as other things such as flash objects etc...
Here is process:
Once the process finishes #2, you can no longer speak with the server and execute server sided code (such as PHP). In order to execute more PHP you must either reload the page completely, or utilize AJAX.
Looks like php is behaving the way you programmed.
The javascript corresponding to the like button shall be
function vote(){
alert("Jūs jau balsavote !");
}
if the vote has been casted and
function vote(){
}
if it has not been. You need to use AJAX or reload the page when the like button is pressed.