I have following function. I want to call this function when user click on Hyperlink (unactivate my account). what is the best way to call function on href click? thanks
function deleteUserMeta($userID) {
delete_usermeta($userID, 'subscription_id');
delete_usermeta($userID, 'ref_id');
delete_usermeta($userID, 'users_name');
delete_usermeta($userID, 'trans_key');
}
As Thorben mentioned, you can’t execute PHP functions on browser events, since the language is server-side and not client-side. However, there are a couple of ways to address this:
1. SERVER-SIDE (PHP)
You can’t call a PHP function on a browser event (link click, for example), but you can call it first thing on the page that’s loaded when you click though the hyperlink — let’s call it ‘next.php’. To do this, call your function
deleteUserMeta()conditionally, at the very top of ‘next.php’. The catch is you’ll need to pass some variables to this page so that you can check the condition, and execute the function. Use GET to pass a variable through the hyperlink like this:How you want to pass the userId is up to you. In the above example it’s hard-coded, but you might also somehow set it with PHP like so:
Now on ‘next.php’, use a condition to assess that variable:
2. CLIENT-SIDE (AJAX)
The other way to perform this operation is to do it client-side with some AJAX. If you’re not familiar with Javascript/jQuery/AJAX I would probably stick to the other solution, as it’s probably easier to implement. If you’re using jQuery already though, this shouldn’t be too hard. With jQuery, you can bind this function to the actual click event of your hyperlink. This way, this entire operation can happen without refreshing the page:
Now you’ll need two things:
1. The same PHP file “next.php” that was required for the first solution just contains a call to your function,
deleteUserMeta($userId)2. A javascript function called
ajaxDeleteUserMeta(), so create one in your JS like this: (since this is a named function, it doesn’t need to go insidejQuery(document).ready(function(){});like most anonymous jQuery functions do.)Long-winded, but I hope some of that makes a little sense.