Reputation: 2904
I just started learning PHP and was wondering if there is a way to trigger a portion (a function really) of a php script when a user clicks on a link/button without redirecting the user to a new php script page?.
Basically, is there a way to invoke php functions through client side user actions like you have in javascript?.
Upvotes: 1
Views: 84
Reputation: 77966
Here's how you can do it with JQuery using $.ajax()
[Docs]
$('#my-button').click(function(){
$.ajax({
url: 'my_php_page.php?route=my_preferred_function',
data: 'foo=bar',
type: 'post',
dataType: 'json',
success: function(data){
alert('Response = ' + data);
}
});
});
Most MVC frameworks - one example being CodeIgniter allow you to execute specific functions in the controller via the URL: http://domain.com/mycontroller/myfunc
. If your function takes two arguments, for example:
public function foobar($foo,$bar){
// do something
}
You can access it via http://domain.com/mycontroller/foobar/abc/123
making your ajax calls super easy.
Upvotes: 0
Reputation: 76898
PHP is not client side. It simply generates a page and sends it to the user's browser.
You would need to incorporate javascript into the page you are returning for client side actions. The most common approach is having javascript make AJAX calls to php scripts on the backend.
Upvotes: 1