View Full Version : how to send onclick event true to php?

02-19-2012, 02:22 AM
I wish to know how to send input button onclick event to php so then I could assign function and return result depending on this event.
I know just two ways:
1- with onclick ="javascript: function dosomething();"
2- with jquery $(".selector").click(function(){do something}
but neither give me handle this as variable inside php.

02-19-2012, 03:23 AM
if you are wanting to retrieve database information via javascript through PHP you will need to do some research on using some Ajax and the HttpRequestObject

02-19-2012, 04:23 AM
It's a general question, so here's a general answer and in pretty much the simplest terms -

On the sending page (some.htm):

<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
url: 'process.php',
type: 'POST',
data: 'picnum=' + ($('#picnum').val() || 0),
success: function(result){
Pick a Number, Any Number: <input type="text" id="picnum">
<input type="button" id="mybut" value="Go!">

On the receiving page (process.php):

$picnum = isset($_POST['picnum'])? $_POST['picnum'] : 0;
echo "The picnum was set to $picnum.";

Obviously you could do a lot more on either or both pages depending upon your objectives.

02-19-2012, 07:50 AM
As a background note, it is important to understand how PHP works. PHP is executed on the server and its output is sent to the browser as HTML (and CSS and Javascript). Therefore, when Javascript is running in the browser, PHP is already done and cannot be used again.

So mixing JS and PHP is impossible.

Using Ajax is a method to get around this, but you're still not really using PHP and JS at the same time on the same page-- you're essentially loading a separate page in a hidden way (via JS, in the background).

Understanding that premise is helpful.

That said, you can use Ajax (though it is difficult in some cases) to pretend that JS has access to PHP.