How to Call a PHP Function on the Click of a Button

How to call a PHP function on the click of a button

Button clicks are client side whereas PHP is executed server side, but you can achieve this by using Ajax:

$('.button').click(function() {
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});

In your PHP file:

<?php
function abc($name){
// Your code here
}
?>

Run php function on button click

I tried the code of William, Thanks brother.

but it's not working as a simple button I have to add form with method="post". Also I have to write submit instead of button.

here is my code below..

<form method="post">
<input type="submit" name="test" id="test" value="RUN" /><br/>
</form>

<?php

function testfun()
{
echo "Your test function on button click is working";
}

if(array_key_exists('test',$_POST)){
testfun();
}

?>

how to call a PHP function with HTML button click?

Like this?

<?php
if (isset($_POST['submit'])) {
someFunction();
}
function someFunction() {
echo 'HI';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="" method="POST">
<input type="submit" name="submit">
</form>
</body>
</html>

Although quite weird, this will work, you can use $_GET if you want

Exectue PHP Function from <button onclick=>

already answered here :-
Run php function on button click

one more example from my side:-



How to call PHP function
on the click of a Button ?

<h1 style="color:green;"> 
GeeksforGeeks
</h1>

<h4>
How to call PHP function
on the click of a Button ?
</h4>

<?php
if(array_key_exists('button1', $_POST)) {
button1();
}
else if(array_key_exists('button2', $_POST)) {
button2();
}
function button1() {
echo "This is Button1 that is selected";
}
function button2() {
echo "This is Button2 that is selected";
}
?>

<form method="post">
<input type="submit" name="button1"
class="button" value="Button1" />

<input type="submit" name="button2"
class="button" value="Button2" />
</form>

source:-https://www.geeksforgeeks.org/how-to-call-php-function-on-the-click-of-a-button/

Calling PHP function when clicking <button type=submit>

You can make use of jQuery Ajax to perform this operation.
Add a button with some id.

<button id="click-button"></button>

Inside your script tag.

$(document).read(function(){
$("#click-button").click(function(){
$.ajax({
url: "remote-file.php",
method:"POST",
data:"token=buttonclick",
success: function(result){
if(result != "fail"){
//Perform actions with the results...
}
}});
});
});

In you PHP remote-file.php

<?php
if(isSet($_POST['token']) && $_POST['token'] == 'buttonclick'){
$result = myFunction();
echo $result;
}else{
echo "fail";
}

function myFunction(){
// Perform your DB actions...
return true; //Return your data
}
?>

Calling a PHP function on button click?

You cannot directly call a php function using a button click.But you can call Js functions on button click event.
And then you can implement Ajax to call php functions.

You are using wordpress so you can use wp functions or custom coding to achieve this.

Php is server-side scripting language.
Which will run only on server.

Call php function when click a button

Finally, I found out the way.It works for me. Now, I do not understand the code , I am trying to read and get it clearly.
Thanks all for your comments.


    $to="";
$from="";
$show_order_statuses = 0;
$orserstatus = "";

$result_order = 0;

//var_dump($results);

//return;
if(!empty($_REQUEST['filter_type']))
{

$orders_row = array();
$filter_type = $_REQUEST['filter_type'];

$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = " SELECT * FROM pricelistitem where pricelist_code='".$filter_type."' ";


// $query = 'SELECT * FROM pricelistheader1';
$results = $readConnection->fetchAll($query);
foreach ($results as $rowid)
{
$result_order=10;
$orders_row[]=array($rowid['pricelist_code'],$rowid['product_code'],number_format( $rowid['unitprice'],2),$rowid['UOM']);
// $orders_row[]=array(1,1,1,1,1);
}

}

?>

<div id="anchor-content" class="middle">
<div id="page:main-container">
<div class="content-header">
<table cellspacing="0">
<tbody>
<tr>
<td style="width:50%;"><h3 class="icon-head head-report-sales-sales"><?php echo $this->__("Price List");?></h3></td>
<td class="form-buttons"><button style="" onclick="filterFormSubmit.submit()" class="scalable " type="button" id="id_<?php echo Mage::getSingleton('core/session')->getFormKey() ?>"><span>Show Report</span></button></td>
</tr>
</tbody>
</table>
</div>
<div>
<div class="entry-edit">
<form method="get" action="<?php echo Mage::helper('core/url')->getCurrentUrl();?>" id="filter_form">
<?php /*?><input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" /><?php */?>
<div class="entry-edit-head">
<h4 class="icon-head head-edit-form fieldset-legend">Filter</h4>
<div class="form-buttons"></div>
</div>
<div id="sales_report_base_fieldset" class="fieldset">
<div class="hor-scroll">
<table cellspacing="0" class="form-list">
<tbody>
<tr>
<td class="label"><label for="sales_report_filter_type">Filter By <span class="required">*</span></label></td>
<td class="value">
<select class="required-entry select" name="filter_type" id="sales_report_filter_type" onchange="myFunction();">
<?php
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = " SELECT * FROM pricelistheader ";

$results = $readConnection->fetchAll($query);
$so=1;
foreach ($results as $row)
{
$selected='';
if ($filter_type==$row[pricelist_code])
$selected= ' selected=selected';
else
$selected='';

echo '<option value="' . $row[pricelist_code]. '" '.$selected.' >' . $row[pricelist_name].' '. $row[pricelist_code] . '</option>';

}
?>
</select>
</tr>
<tr>
<td class="label"><label for="effect_from">Effect From </label></td>
<td class="value">
<?php
foreach ($results as $row)
{

if ($filter_type==$row[pricelist_code])
echo $row[pricelist_fromdate];

}
?>
</td>
</tr>

<tr>
<td class="label"><label for="effect_from">Effect To </label></td>
<td class="value">
<?php
foreach ($results as $row)
{

if ($filter_type==$row[pricelist_code])
echo $row[pricelist_todate];

}
?>
</td>
</tr>
</tbody>
<script>
function myFunction() {
// document.getElementById("tbdata").deleteRow(1);
var rowCount = tbdata.rows.length;
for (var i = rowCount - 1; i > 0; i--) {
tbdata.deleteRow(i);
}
srt.value=pricelist.options[pricelist.selectedIndex].value;
";
//$('#tbdata').empty();
}
</script>
</table>
</div>
</div>
</form>
</div>
<script type="text/javascript">
//<![CDATA[
var filterFormSubmit = new varienForm('filter_form');

//]]>
</script>
<script type="text/javascript"> new FormElementDependenceController({"sales_report_order_statuses":{"sales_report_show_order_statuses":"1"}}); </script>
<style type="text/css">
.no-display{display:none;}
</style>
</div>



<div>
<?php if($result_order>0){?>
<table cellspacing="0" class="actions">
<tbody>
<tr>
<td class="pager"> </td>
<td class="export a-right">
<form method="post" action="<?php echo $this->getUrl('*/*/exportCsv')?>" id="csv_form_customer">
<input name="form_key_customer" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" />


</form>
<script type="text/javascript">
//<![CDATA[
var csvFormSubmitcustomer = new varienForm('csv_form_customer');
//]]>
</script>
</td>
<td class="filter-actions a-right">
<img class="v-middle" alt="Sample Image" src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);?>skin/adminhtml/default/default/images/icon_export.gif">  Export to:
<select style="width:8em;" id="sales_order_grid_export_customer" name="sales_order_grid_export_customer">
<option value="<?php echo $this->getUrl('*/*/exportCsv')?>">CSV</option>
</select>
<button onclick="csvFormSubmitcustomer.submit()" class="scalable task" type="button"><span>Export</span></button>
</td>
</tr>
</tbody>
</table>
<?php } ?>
<div id="id_customer<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" class="print_customer<?php echo Mage::getSingleton('core/session')->getFormKey() ?>">
<div class="grid">
<div class="hor-scroll">
<table cellspacing="0" id="id_customer<?php echo Mage::getSingleton('core/session')->getFormKey() ?>_table" class="data">
<colgroup>
<col>
<col>
</colgroup>
<thead>
<tr class="headings">
<th class=" no-link"><span class="nobr">Price List Code</span></th>
<th class=" no-link"><span class="nobr">Cust Code</span></th>
<th class=" no-link"><span class="nobr">Cust Name</span></th>
</tr>
</thead>
<tbody id="">
<?php

$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = " SELECT * FROM " . $resource->getTableName('catalog/product');;
$customercount=0;
$customerresults = $readConnection->fetchAll($query);

$customerresults = Mage::getModel('customer/customer')
->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('erp_pricelistcode_1', $filter_type)
// ->addFieldToSelect (array('created_at','customer_id','increment_id','updated_at','status','entity_id','state'))
;

// ->addAttributeToFilter('erp_pricelistcode_1','00')->load();
$so=1;
foreach ($customerresults as $row) {

$customercount++;
}
// var_dump(@$customerresults);
if($customercount>0){
foreach($customerresults as $singlerows){
$cot=0;
{
echo "<tr>";
{
$cot++;
?>
<td>
<?php
echo $singlerows->getData('erp_pricelistcode_1');
?>
</td>
<td>
<?php
echo $singlerows->getFirstname();
?>
</td>
<td>
<?php
echo $singlerows->getName();
?>
</td>
<?php
}
echo "</tr>";
}
}
}else{
?>
<tr class="even">
<td colspan="13" class="empty-text a-center">No records found.</td>
</tr>
<?php } ?>
</tbody>

</table>

</div>
</div>

<div>
<?php if($result_order>0){?>
<table cellspacing="0" class="actions">
<tbody>
<tr>
<td class="pager"> </td>
<td class="export a-right">
<form method="post" action="<?php echo $this->getUrl('*/*/exportCsv')?>" id="csv_form">
<input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" />


</form>
<script type="text/javascript">
//<![CDATA[
var csvFormSubmit = new varienForm('csv_form');
//]]>
</script>
</td>
<td class="filter-actions a-right">
<img class="v-middle" alt="Sample Image" src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);?>skin/adminhtml/default/default/images/icon_export.gif">  Export to:
<select style="width:8em;" id="sales_order_grid_export" name="sales_order_grid_export">
<option value="<?php echo $this->getUrl('*/*/exportCsv')?>">CSV</option>
</select>
<button onclick="csvFormSubmit.submit()" class="scalable task" type="button"><span>Export</span></button>
</td>
</tr>
</tbody>
</table>
<?php } ?>
<div id="id_<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" class="print_<?php echo Mage::getSingleton('core/session')->getFormKey() ?>">
<div class="grid">
<div class="hor-scroll">
<table cellspacing="0" id="id_<?php echo Mage::getSingleton('core/session')->getFormKey() ?>_table" class="data">
<colgroup>
<col>
<col>
<col>
<col>

</colgroup>
<thead>
<tr class="headings">
<th class=" no-link"><span class="nobr">Price List Code</span></th>
<th class=" no-link"><span class="nobr">Product Code</span></th>
<th class=" no-link"><span class="nobr">Unit Price</span></th>
<th class=" no-link"><span class="nobr">UOM</span></th>

</tr>
</thead>
<tbody id="">
<?php
$cot=0;
if(count($orders_row)>0){
foreach($orders_row as $singlerows){
$cot=0;
if(!empty($singlerows)){
echo "<tr>";
foreach($singlerows as $value){
$cot++;
?>
<td>
<?php
if ($cot==3 )
echo "<div style='float:right;width:30%;'>";
echo $value;
echo "</div>";
?>
</td>
<?php
}
echo "</tr>";
}
}
}else{
?>
<tr class="even">
<td colspan="13" class="empty-text a-center">No records found.</td>
</tr>
<?php } ?>
</tbody>

</table>
</div>
</div>
</div>
</div>
</div>
</div>

Calling a PHP function using a radio button

Think of your ajax call as if you're loading up a new tab in your browser. So, when you click the radio button, your call from test0.php is retrieving whatever gets responded to by test1.php, completely in isolation.

So, no need to include test1.php in your existing file- you're calling it separately! Your solution might be as simple as editing test1.php to execute the function when called, like so:

test0.php

<?php

//include "test1.php"; // no need to include this file here

echo '<input type="radio" id="1" name="rere" value="qwqw" checked onclick="testFunc();"><label for="1">radio 1</label>';
echo '<input type="radio" id="1" name="rere" value="qwqw" onclick="testFunc();"><label for="1">radio 2</label>';

echo '<div><p id="res">sdfdsfsdfsd</p></div>';

//echo condCheckedUpd(); //also no need for this function call here

?>

<script>
function testFunc() {
$.ajax(
{
url: 'test1.php',
success: function(data)
{
//alert(data);
}
});
}
</script>

test1.php

<?php
function condCheckedUpd() {
echo "works";
}
condCheckedUpd();
?>

You also asked about passing parameters along with your request, for that there's the data setting that you can include. For example, replace your javascript in test0.php above with something like:

<script>
//...^ all your existing php/html is still above
function testFunc() {
$.ajax({
url: "test0.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>

Then, in test1.php, you can get your above parameters using the $_REQUEST global variable, and pass them into your function:

<?php
$getName = $_REQUEST['name'];
$getLocation = $_REQUEST['location'];

function condCheckedUpd($getName, $getLocation) {
echo "works for ".$getName." in ".$getLocation;
}
condCheckedUpd();
?>

For your purposes, I expect you probably want to get the value of your radio buttons. For that, you might look into html/javascript's dataset attribute as an easy way to pass these along (Examples and docs here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset).

Warning! If you're accepting values this way, be careful that what comes through in your $_REQUEST variables is what you expect, and be very careful if you end up displaying these back to the screen– lots of security concerns here. A few clues: How can I sanitize user input with PHP?



Related Topics



Leave a reply



Submit