How do I trigger a php function on onclick event? - php

For instance I have a php function
<?php
function SayHi($msg){
return $msg;
}
?>
The following part triggers the onclick event
Click
How can I merge the two such that when I click on Click, the php function is invoked..?

You can not. PHP is executed serverside, while javascript is executed clientside.
THe generic solution for this is to use asynchronous Javascript (ajax) to call on your webserver, which in turn can invoke PHP code to do various things.
jQuery is a very nice library to handle this, and much more.

There are many ways to do this, most are complicated.
One easier way is:
<?php
function myFunc() { die('yay'); }
if (isset($_REQUEST['myButton'])) myFunc();
?>
<form><button name="myButton">Click Me</button></form>

Whaaat? PHP is server-side you cannot invoke a php function from javascript. However you can do this with ajax.
AJAX

You'll want to use AJAX. You need to call a server-side resource from the JavaScript code, and jQuery has a very handy function for making the call to the server. But making the call from the JavaScript is only half the story, you'll also need something on the server listening for that call. It would essentially be another PHP script which acts as a page in and of itself, but would return data in the form of (most likely) JSON instead of HTML. It's not meant to be human-readable, but rather to be a sort of web service for your JavaScript code to use.
You can find a simple example here.

please get involved with the basics of PHP: http://tut.php-quake.net/en/

Related

Pass a php function instead of a file to jquery $post method

i started to learn jquery yesterday so i'm not so good.
I've a question:
as title there's a way to pass a php function instead of a file to jquery $.post method?
Here's an example of what i would to do:
function send(str)
{
$.post
(
"<?php PHPfunction(); ?>",
{send:str},
function(data)
{
$("#output-text").html(data.reply);
},
"json"
);
}
there's a way to do that? or i need always to pass a file to the first parameter?
Just another question:
how can i pass more than 1 row from php to jquery in the ajax reply?
You'll want to use AJAX to make a request for that function. For more information, see http://api.jquery.com/jQuery.ajax/. Google can also provide you a ton of examples because what you're asking is a fairly common problem with plenty of good solutions.
PHP is run on the server before the page is fully loaded, so you can't call a PHP function on the fly like that. Javascript runs within the browser afterwards, on the clients machine. They are two separate environments, code wise.
You're better off calling a page that uses the function, using Ajax or something.

Ajax call does not execute PHP function

I have written a very basic PHP pagination class and I'm trying to load the content with jQuery Ajax $.post requests. My class has two functions, one displays the content and the other one the pagination. If I don't use jQuery, but only PHP, everything works fine. Once I try to use jQuery, my displayContent() function never gets called, but the createNav() one does its job just fine(I mean the page numbers are loaded).
Here is my js.
http://goo.gl/BUZH1
And here is my PHP:
if($action=='displayArticles') displayArticles();
function displayArticles()
{
$content=new createPages(5,10);
$content->displayContent();
$content->createNav();
}
And here is the PHP class I just created. It was too large to add it in here, but I saved the code in text format.
http://goo.gl/Lv9Wl
Try dumping $_POST['action'], then check the output in the $.post response. It's pretty obvious that your if statement is resolving to false. :)
You can also try dumping $action, then checking that in the response. Good luck!
You can not call PHP functions after the page has been loaded. PHP is server side script, so you need AJAX to load a separate page, where your displayArticles function will be defined.

function running automatically instead of a click

I the following code:
<? $test = new com("Soundclass.Soundrec"); ?>
<? $test->startrec ?>
<script>
function stop(){
var stop_record = "<?=$test->stoprec;?>";
}
</script>
and I am running the stop function in a button click. But the php function seems to run without the click.
The purpose of this is to stop the recording on that button click.
You have a little logical error:
PHP is server-side and gets executed on the server when the document is called.
Javascript is client-side and gets called dynamically, it can't re-execute any php-code again.
See the source code in your browser and you'll understand!
But you could make an ajax call to the class and execute the stoprec() method with a (defined in your script) get/post variable. But as this still won't give you a handle on the same instance of the object, so unfortunately you probably have to rethink your whole script!
What you are trying to do is fundamentally impossible: You are mixing up PHP (which runs on server side) and JavaScript (which runs on client side).
You would have to build a second PHP script that stops the recording, and have that called from JavaScript using Ajax.
Calling $test->stoprec will probably stop recording (don't know Soundclass.Soundrec that specifically myself).
As you call it even before the page has been delivered, pressing the stop button later won't make a change here.
You need to execute the PHP later (after button click), however you have the general problem here that the com object in $test won't survive that (it would be a new one).
The only solution I see here is that you create a daemon that manages sound recording for you. This would work with AJAX, but is not trivial. So the short (and sad) answer is: Not easily possible.

Is it okay to use PHP inside a jQuery script?

For example:
$(document).ready(function(){
$('.selector').click(function(){
<?php
// php code goes here
?>
});
});
Will this cause issues or slow down the page? Is this bad practice? Is there anything important that I should know related to this?
Thanks!
If you are trying to bound some PHP code with the click event then this is impossible in the way you are trying and PHP code will be executed as soon as page load without waiting for a click event.
If you are trying to generate final javascript or jquery code using PHP then this is okay.
It won't slow down the page; the PHP runs on the server and emits text which is sent to the browser, as on any PHP page. Is it bad practice? I wouldn't say "bad" necessarily, but not great. It makes for messy code - in the event where I need to do something like this, I usually try to break it up, as in:
<script>
var stuff = <?php print $stuff; ?>;
var blah = "<?php print $blah; ?>";
// Do things in JS with stuff and blah here, no more PHP mixed in
</script>
PHP is executed on the server, and then the javascript will be executed on the client. So what you'd be doing here is using php to generate javascript that will become the function body. If that's what you were trying to do then there's nothing wrong with doing it.
If you thought you were going to invoke some PHP code from javascript, then you're on the wrong track. You'd need to put the PHP code in a separate page and use an ajax request to get the result.
Sure, as long as you keep in mind that PHP code will be executed by the server before the page is sent out. Other than that, have fun.
PHP is a "backend" language and javascript is a "frontend" language. In short, as long as the PHP code is loaded through a web server that understands PHP - the downside is that you have to inline the JS, losing caching ability (there are workarounds to parse php in .js files but you shouldn't really do this). To the user it will just look like javascript and HTML. Here's the server order:
User requests page.
Apache (or equivalent) notices this
is a php file. It then renders all
the php that are between php tags.
Apache sends the page to the user.
User's browser sees the JavaScript
and executes it.
Just be sure the PHP is outputting valid JavaScript.
you have a better choice to use ajax that runs the php script when you are handling a click event
$(document).ready(function(){
$('.selector').click(function(){
$.ajax({url:"phpfile.php",type:"POST",
data:"datastring="+value+"&datastring2="othervalue,
,success:function(data){
//get the result from the php file after it's executed on server
}
});
});
});
No it's not. Just as long as you know that the JS is executed after the PHP page is parsed.

Calling JavaScript with PHP

I want to call a PHP function when pressing on a button, sort of like:
<?php
function output(){
// do something
}
?>
<input type="button" value="Enter" onclick="output()"/>
I tried to make something like:
<input type="button" value="Enter" onclick="test.php?execute=1"/>
where test.php is current page and then by php
<? if(isset(&execute)){ echo "Hello"; } ?>
but it doesn't work.
Since PHP runs on the webserver, and buttons (and JavaScript in this case) appear on the client, you have to make an HTTP request to the server.
The easiest way to do this is to use a form. No JavaScript is required. You can add JavaScript (although it should be layered on top of a working non-JS version). Using JavaScript to make an HTTP request without leaving the page is known as Ajax, and generally achieved with the XMLHttpRequest object. There are various libraries such as YUI and jQuery that can do some of the heavy lifting for you.
I think using an AJAX call would do sort of what you are asking. I don't know PHP very well but you can use the following example, and add another variable with the data you are passing in to the server to indicate which function you want to call on the server. On the server you can add some "IF" statements that will call a certain function based on the name passed in and return the result.
Here is what you could use on in your javascript client using the jQuery library as a helper to do the AJAX call:
<input type="button" value="Enter" onclick="output()"/>
<script type="text/javascript">
function output(){
$.ajax({
type: "POST",
url: "submit_data.php",
data: "username=" + "SomeUser"
+ "&email=" + "someEmail#google.com"
+ "&functionName=" + "theFunction1",
success: function(html){
alert('sucess! Result is:' + html);
}
});
}
</script>
and you can use code such as this to catch the data your javascript is passing in. In this example you would want to call this file name as "submit_data.php" to match the javascript above:
<?php
// Variables
$Username = $_POST['username'];
$Email = $_POST['email'];
$FunctionName = $_POST['functionName'];
//Add code here to choose what function to call and echo the result
// If $FunctionName equals 'theFunction1' then execute theFunction1
// If $FunctionName equals 'theFunction2' then execute theFunction2
echo "You called A Page!";
?>
Here I am doing nothing with the "username" and "email" simply grabbing it and storing them into holding variables. But you can easily add extra functionality here, such as checking for a name of a function that you want to run.
PHP is server side and javascript is client side. So I'm not sure if that is really what you want to be doing??
Perhaps you could explain why you want to specifically call a php function?
I googled PHP function from button and found this question on webdeveloper.com
It doesn't use Javascript.
This is PHP you're talking about, not ASP.NET. In PHP, there is no such thing as a button click event. PHP runs entirely on the server and has absolutely no knowledge of client-side events.
Your first try won't work because the PHP code only runs when the page first loads. It does not run when you call a JavaScript function. Your second example won't work because JavaScript and PHP can't talk directly to eachother like that. Trying to directly call a PHP function from JavaScript just doens't make sense. Remember, PHP only runs on the server. By the time you get to the point where JavaScript can run, the PHP code has long since completed its work.
If you want to do something when a button is clicked, you have to explicitly make a request back to the server. You can do this by just POSTing the form as CTphpnwb suggested. Just be aware that this will reload the page and you will have to manually save and restore the page state, e.g. repopulate input boxes. There is no built-in magic that will do this for you.
Alternatively, you can get all AJAXy and do the POST in JavaScript. However, you will have to write the JavaScript to send the request and process the response, and write the server-side PHP code to handle the request. This gets a little awkward to do in a single page.
From : http://www.dreamincode.net/forums/showtopic72353.htm
You cannot directly invoke a PHP function from Javascript this way :
PHP code is executed on the server
HTML / Javascript are interpreted on the client-side.
One the HTML page has been generated and sent to the client (the browser), there is nothing more PHP can do.
One solution would be to use an Ajax request :
Your onclick event would call a Javascript function
This Javascript function would launch an Ajax request : a request sent to the server
The server would then execute some PHP code
And, then, return the result of that execution to the client
And you'd be able to get that result in your Javascript code, and act depending on what was returned by the server.
There are plenty of solutions to do an Ajax request :
You can re-invent the wheel ; not that complex, I should say -- but see the next point
If already using a Javascript framework, like jQuery, Prototype, ... Those provide classes/methods/functions to do Ajax requests
Googling a bit will get you lots of tutorials/examples, about that ;-)

Categories