Page 1 of 1

Using PHP in a Javascript function?

Posted: Sat Aug 07, 2010 1:29 pm
by VanderAlexander
I'm assuming this is a pretty basic question, but is the code that I posted going to work properly? I just inerted a mysql query into a javasdcript function. The function is called by an onClick event handler.

Code: Select all

function countdown(link2) {
$(link2).removeAttr('onclick');


time--;


<?php
$time = time();
$insert_query2 = "INSERT INTO test_user_timestamp (username,building,timestamp_built) VALUES ('Patrick','Kristallmiene',$time)"; 
mysql_query($insert_query2) or die("Error, insert query failed");
?>


if (time <= 0) {
text = 'Countdown finished';
} 
else {

hour=Math.floor(time/(60*60));
rest=time%(60*60);
min=Math.floor(rest/60);
rest=rest%60;
text = hour + ":" + min + ":" + rest;
window.setTimeout('countdown()', 1000);

}

document.getElementById('time2_div').firstChild.data = text;

}

Edit:
As for the context, this is supposed to be a countdown and I want to insert the current timestamp into my database when the function is called.

My problem is that the timestamp is inserted into the database whether the function is called or not. So, the php part runs as soon as the page is loaded. How can I change this?

Re: Using PHP in a Javascript function?

Posted: Sat Aug 07, 2010 3:18 pm
by PHPHorizons
Hello VanderAlexander,

Unfortunately, the answer is no. The problem here is that you will be sending this php code to the user's computer and it will not be parsed as php, but as syntactically incorrect javascript. What you probably need is to use ajax at that point in the javascript where you want to make an ajax call to your server which will then cause a php script to execute.

Cheers

Re: Using PHP in a Javascript function?

Posted: Sat Aug 07, 2010 10:21 pm
by califdon
Yes, PHPHorizons is exactly correct. Just to say it in a different way, which sometimes helps people understand a new concept, Javascript is a language that is interpreted in the client browser, PHP is a language that is interpreted in the web server. Once the web server sends a page to the browser, PHP is no longer part of the picture, unless another request is sent back to the server. "AJAX" is a way for Javascript to send an "asynchronous" request to the server, which can have a PHP script that sends data (not a whole new page) back to be processed further by the Javascript function, when it receives the data.

Bottom line, yes, you can do what you want if you use AJAX and write another script to handle the request on the server, but NO, you cannot mix PHP code in with Javascript, because the browser would not be able to recognize it.

Re: Using PHP in a Javascript function?

Posted: Sun Aug 08, 2010 7:38 pm
by VanderAlexander
That makes perfectly sense. Thanks! I'm going to be studying some AJAX then, I hope it is not too complicated to do what I wanted.