Reputation: 19
I have a web page, and I need certain PHP functions to be executed when a user clicks on a button. I plan on using jQuery for this. The problem is, for reasons I won't go into, I CANNOT use an external PHP file. All the PHP I can use must be in this file, somewhere. Every solution I've found to executing any sort of PHP code through jQuery requires an external file. But there has to be a way to just have it read off text that I give it here in this file, right? Any ideas?
Upvotes: 0
Views: 68
Reputation: 251
You can't call PHP functions with JavaScript in the way that you seem to be thinking.
When you load a PHP page, the server processes the code in the PHP file and returns only the result of that code to the browser. The browser is completely unaware of the actual code in the PHP file.
JavaScript on the other hand runs completely client-side, ie in the browser. So the server is unaware of anything happening in the browser until the browser specifically sends a request to the server.
If you want a button click to trigger a PHP function, you're going to have to make a request to the target PHP file (be it another file, or the same file).
One way is to have the button in a form, that is submitted to the same page and the page looks for the form data when generating content:
<form method="post">
<input type="submit" name="myButton" value="Click me" />
</form>
By omitting the action
attribute the form will submit to the same page.
In the PHP part at the top of the page you would then have something like this to check if the button has been clicked:
<?php
if (isset($_POST["myButton"])) {
myFunction();
}
?>
This will of course cause the page to reload. If you wish to avoid that, then look at the answers covering AJAX.
Upvotes: 0
Reputation: 128
You just need to make an ajax request to the same page
<script>
$.ajax({
type: "POST",
url: "foobar.php",
data: {foo:'bar'},
dataType: 'text',
success:function(data){
alert(data);
}
});
</script>
<?php
if($_REQUEST["foo"] == "bar") {
echo "i've been ajaxed";
call_my_func();
}
?>
Upvotes: 0
Reputation: 5760
You can send a GET or POST parameter to the page using ajax functions of JQuery ($.post for example), to specify that the request is from the code. Then simply check that parameter and if exists, do what ever you want and output something else instead of normal one.
Upvotes: 1