Reputation: 653
I am using wordpress as my cms and I am devloping a voting system. I want this code to run only on click event but it runs on every page load
How can i only make it run on click even
<script>
function addvote(){
alert("<?PHP hello(); ?>");
}
< /script>
<?PHP
FUNCTION hello(){
$postid="79";
$current_votes = get_post_meta($postid, "votes", true);
$new_votes = intval($current_votes) - 1;
update_post_meta($postid, "votes", $new_votes);
$return = $new_votes>1 ? $new_votes." votes" : $new_votes." vote";
echo $return;
}
?>
<button onclick="addvote()">Vote Now</button>
Upvotes: 0
Views: 164
Reputation: 816
when you request this page PHP parser will encounter with hello()
function, and it will run it and therefore it will print the return value of hello()
function in the javascript alert()
function, so the output wil be, (assuming return value be 1):
<script>
alert('1');
</script>
as @lethal-guitar mentioned you need to call the hello()
function with an AJAX request.
Upvotes: 0
Reputation: 4519
You cannot invoke PHP from JavaScript like that. You need AJAX: http://en.wikipedia.org/wiki/Ajax
Also, use unobtrusive JavaScript - attach event handlers in your Script code, not in the HTML. Basic example how to implement what you probably want, using jQuery:
// In your HTML page:
<scipt type="text/javascript">
$(document).ready(function() {
$('button').click(function() {
$.get("/hello.php", function(data) {
alert(data);
});
});
});
</script>
// In hello.php:
<?php
function hello() {
// ...
echo $return;
}
hello();
?>
You need to understand the distinction between server- and client-side processing. All your PHP code is executed on the server on each page request. The results are then sent to your browser, which displays them. Now there can be JavaScript code in your page, which is executed by the browser after the page is loaded. In order to invoke PHP code on a button click (or similar), this client-side code needs to make a new HTTP request to the server - this is what AJAX is for. This new request will trigger the execution of another PHP script. The results are transferred back to the JavaScript function after it finishes, and can then be used to do something, like adding additional content to your page.
Upvotes: 3