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

I have created a page called functioncalling.php that contains two buttons, Submit and Insert.
I want to test which function is executed when a button gets clicked. I want the output to appear on the same page. So, I created two functions, one for each button.
<form action="functioncalling.php">
<input type="text" name="txt" />
<input type="submit" name="insert" value="insert" onclick="insert()" />
<input type="submit" name="select" value="select" onclick="select()" />
</form>
<?php
function select(){
echo "The select function is called.";
}
function insert(){
echo "The insert function is called.";
}
?>
The problem here is that I don't get any output after any of the buttons are clicked.
Where exactly am I going wrong?

Yes, you need Ajax here. Please refer to the code below for more details.
Change your markup like this
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
jQuery:
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
In ajax.php
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
case 'select':
select();
break;
}
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>

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
}
?>

You should make the button call the same page and in a PHP section check if the button was pressed:
HTML:
<form action="theSamePage.php" method="post">
<input type="submit" name="someAction" value="GO" />
</form>
PHP:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['someAction']))
{
func();
}
function func()
{
// do stuff
}
?>

You cannot call PHP functions like clicking on a button from HTML. Because HTML is on the client side while PHP runs server side.
Either you need to use some Ajax or do it like as in the code snippet below.
<?php
if ($_GET) {
if (isset($_GET['insert'])) {
insert();
} elseif (isset($_GET['select'])) {
select();
}
}
function select()
{
echo "The select function is called.";
}
function insert()
{
echo "The insert function is called.";
}
?>
You have to post your form data and then check for appropriate button that is clicked.

To show $message in your input:
<?php
if(isset($_POST['insert'])){
$message= "The insert function is called.";
}
if(isset($_POST['select'])){
$message="The select function is called.";
}
?>
<form method="post">
<input type="text" name="txt" value="<?php if(isset($message)){ echo $message;}?>" >
<input type="submit" name="insert" value="insert">
<input type="submit" name="select" value="select" >
</form>
To use functioncalling.php as an external file you have to include it somehow in your HTML document.

Try this:
if($_POST['select'] and $_SERVER['REQUEST_METHOD'] == "POST"){
select();
}
if($_POST['insert'] and $_SERVER['REQUEST_METHOD'] == "POST"){
insert();
}

You can write like this in JavaScript or jQuery Ajax and call the file
$('#btn').click(function(){
$.ajax({
url:'test.php?call=true',
type:'GET',
success:function(data){
body.append(data);
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<form method='get' >
<input type="button" id="btn" value="click">
</form>
<?php
if(isset($_GET['call'])){
function anyfunction(){
echo "added";
// Your funtion code
}
}
?>

The onclick attribute in HTML calls JavaScript functions, not PHP functions.

I was stuck in this and I solved it with a hidden field:
<form method="post" action="test.php">
<input type="hidden" name="ID" value"">
</form>
In value you can add whatever you want to add.
In test.php you can retrieve the value through $_Post[ID].

Use a recursive call where the form action calls itself. Then add PHP code in the same form to catch it. In foo.php your form will call foo.php on post
<html>
<body>
<form action="foo.php" method="post">
Once the form has been submitted it will call itself (foo.php) and you can catch it via the PHP predefined variable $_SERVER as shown in the code below
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "caught post";
}
?>
</form>
</body>
</html>

Here is an example which you could use:
<html>
<body>
<form action="btnclick.php" method="get">
<input type="submit" name="on" value="on">
<input type="submit" name="off" value="off">
</form>
</body>
</html>
<?php
if(isset($_GET['on'])) {
onFunc();
}
if(isset($_GET['off'])) {
offFunc();
}
function onFunc(){
echo "Button on Clicked";
}
function offFunc(){
echo "Button off clicked";
}
?>

Calling a PHP function using the HTML button: Create an HTML form document which contains the HTML button. When the button is clicked the method POST is called. The POST method describes how to send data to the server. After clicking the button, the array_key_exists() function called.
<?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: geeksforgeeks.org

You can simply do this. In php, you can determine button click by use of
if(isset($_Post['button_tag_name']){
echo "Button Clicked";
}
Therefore you should modify you code as follows:
<?php
if(isset($_Post['select']){
echo "select button clicked and select method should be executed";
}
if(isset($_Post['insert']){
echo "insert button clicked and insert method should be executed";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<form action="functioncalling.php">
<input type="text" name="txt" />
<input type="submit" name="insert" value="insert" onclick="insert()" />
<input type="submit" name="select" value="select" onclick="select()" />
</form>
<script>
//This will be processed on the client side
function insert(){
window.alert("You click insert button");
}
function select(){
window.alert("You click insert button");
}
</script>
</body>
</html>

Related

posing an array from jQuery to php

I posted a smaller to this yesterday and was shown how to do this but it doesn't work and the user never got back to me and I have been working on the same problem for hours.
I am trying to post a checkbox array from jQuery to php, when I run my code nothing seems to happen and when I try var_dump($_POST) this is all I get
Using this question as a reference, it seems that jQuery doesn't handle arrays too well. You can use to snippet from the accepted answer and it should work just fine.
serialize().replace(/%5B%5D/g, '[]')
Change the submit to a button or better use the form's submit event
why data-type html?
Your php does not seem to react to the serialised data but returns a button...
try my code here: http://plungjan.name/SO/sport.php
I am not unravelling the check box array - that is up to you
<?PHP
if (isset($_POST['saved'])) {
echo "saved"; exit(0);
}
else if (isset($_POST['Submit'])) {
echo var_dump($_POST["sport"]); exit(0);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Sports quiz</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function() {
$('#myForm').on("submit", function(ev) {
ev.preventDefault(); // cancel submit
var $form = $(this);
if ($("[type=checkbox]:checked").length ==0) {
alert("Please check one or more");
return false;
}
var formData = $form.serializeArray();
formData.push({name:"Submit",value:"submit"}); // note I changed the name from submit to Submit
$.post('sport.php',formData, function(data) {
console.log("Data",data);
if (confirm('You want to save \n' + data + ' as your sport?')) {
formData = $form.serializeArray();
formData.push({name:"saved",value:"saved"});
$.post('sport.php',formData,function(data) {
console.log("Saved Data",data);
});
}
});
});
});
</script>
</head>
<body>
<form id="myForm">
<input type="checkbox" name="sport[]" value="Football">Football<br>
<input type="checkbox" name="sport[]" value="Rugby">Rugby<br>
<input type="checkbox" name="sport[]" value="Golf">Golf<br>
<input type="checkbox" name="sport[]" value="Basketball">Basketball<br>
<br> <input type="submit" class="btn btn-info" name="Submit" value="submit">
</form>
</body>
</html>

Php, codeigniter, ajax, mysql

I want to update record in the database with ajax without reloading the page.
//Here is my controller.
Public function changeid()
{
$this->view->('admin/change_id');
}
Public function ajax_changeid()
{
$old_id =$_POST[studentid];
$newid =$_POST[new_id];
If(isset($_POST[`new_id')){
$data =array(
'student_id'=>trim($newid));
$this->db->where('student_id', $old_id);
$this->db->update('student');
echo "info submited";
}
echo json_encode($data);
}
My view form change_id
<form id='formajax' method='post' name='form'>
<input type="text" id="studentid"
name="studentid" readonly="readonly"
value="<? php echo $row- >student_id; ?>" />
<input type="text" name="new_id" id="new_id" >
<input type="submit" id="btnsubmit"
value="Update" class="button success"
onclick="myFunction()" />
<\form>
// Ajax script
<script>
//ajaxForm({
//function myFunction(){
(document).ready(function(){
$("#btnsubmit").click(function(event){
event.preventDefault();
var stud_id =
document.getElementById("new_id").value;
var studentid =
document.getElementById("studentid").value;
var dataString = 'new_id1=' + new_id +
'$studentid1=' + studentid;
$.ajax({
type:"POST",
url:"<?php echo base_url()?
>"+"index.php/school_settings/ajax_changeid",
data:dataString,
cache:false,
success:function(html){
//alert(html);
alert('im working');
}
});
return false;
});
});
</script>
The challenge is the page keep reloading every time.
i click submit button without doing anything.
i want to be able to change id and get a success
message displayed without reloading d page.
You have some issues in your code, use this modified code:
Controller:
public function changeid()
{
$this->load->view('admin/change_id');
}
public function ajax_changeid()
{
$old_id = $_POST['studentid'];
$newid =$_POST['new_id'];
if(isset($_POST['new_id']))
{
$data =array(
'student_id'=>trim($newid));
$this->db->where('student_id', $old_id);
$this->db->update('student');
echo "info submited";
}
echo json_encode($data);
}
View:
<form id='formajax' method='post' name='form'>
<input type="text" id="studentid" name="studentid" readonly="readonly" value="<?php echo $row->student_id;?>"/>
<input type="text" name="new_id" id="new_id">
<input type="submit" id="btnsubmit" value="Update" class="button success" onclick="myFunction()"/>
</form>
What i have changed?
Change load view function as $this->load->view('admin/change_id'); instead of $this->view->('admin/change_id');
Change isset chekcing isset($_POST[`new_id') as isset($_POST['new_id']), you have missed the ending ] bracket and also using backticks (Dont know why)
Correct form ending tag <\form> as </form>
Remove onclick="myFunction()" event from button, because you are using button id for onclick event in ajax.

submit should not redirect to another page in HTML form

I have a HTML form which reads some data and saves in the text file with help of PHP. The form's HTML code looks like below.
What is happening now:
1. once i click on submit button it redirects to the 'myprocessing.php'
2. successfully saving in data.txt
The help i required on
1. when i click on submit it shouldn't redirect me to the php page, it should stay on the HTML form page
2. it should show the php file's output on the same HTML page
In simple words, I want to stay on the HTML page itself. Since I'm pretty new to HTML and PHP, struggling much to do these. Thanks in advance :-)
<html>
<head>
<title></title>
</head>
<body>
<form action="myprocessing.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Show data</a>
</body>
</html>
This is my data prcoessing PHP file.
<?php
echo "starting...";
if(isset($_POST['myTextBox']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
echo "Ended...";
}
else {
die('no post data to process');
}
?>
Try below. Call refresh_div() on button click :-
<div class="result"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function refresh_div() {
jQuery.ajax({
url:'YOUR PHP page url',
type:'POST',
success:function(results) {
jQuery(".result").html(results);
}
});
}
</script>
Write php code in same html file and use isset() function to check for $_POST data
Try this
<?php
if(isset($_POST['field1']) && isset($_POST['field2']))
{
echo "starting...";
if(isset($_POST['myTextBox']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
echo "Ended...";
}
else {
die('no post data to process');
}
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form action="current_page.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Show data</a>
</body>
</html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="POST" name="testForm" id="testForm">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Show data</a>
<div class="result"></div>
</body>
</html>
add the name and id for form tag. if you keep action as blank, it will submit your form to current page itself.
You need a ajax call to perform as per your requirement.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$( "#testForm" ).on( "submit", function( event )
{
$.ajax({
url:'myprocessing.php',
type:'POST',
data: $("#testForm").serialize()
success:function(results) {
jQuery(".result").html(results);
}
});
return false;
});
</script>
Dont forget to put a return false at the end. If we dont put return false, it will submit your form after the ajax call.

jQuery post cannot get $_POST in php

I have a form with an onkeyup event.
I try to send a variable to my php script and show result in a div.
Thanks to this forum I got my test function to half work:
jQuery.post(the_ajax_script.ajaxurl,
If I continue with:
1) jQuery("#theForm").serialize(),
I get response text which is "Hello World"
If I try to pass a variable:
2) { name: "p" },
I get: -1
JavaScript
function submit_me(){
jQuery.post(
the_ajax_script.ajaxurl,
{ name: "p" },
function(response_from_the_action_function){
jQuery("#txtHint").html(response_from_the_action_function);
}
);
}
PHP
<?php
function the_action_function(){
$name = $_POST['name'];
echo "Hello World, " . $name;
die();
}
?>
FORM
<form id="theForm">
<input type="text" name="user">
<input name="action" type="hidden" value="the_ajax_hook">
<input id="submit_button" value = "Click This" type="button" onkeyup="submit_me()">
<form>
I actually want onkeyup="submit_me(this.value, 0)"
I am doing this on a WordPress through their admin-ajax.php file.
Where is the problem in this?
EDIT
Apparently I had to add action to data
{ action:'the_ajax_hook', name:"p" }
I guess its WP requirement, rather than jQuery, because I saw examples as this:
$.post("test.php", { name: "John", time: "2pm" }
everywhere.
Something like this should work:
<html>
<head>
<script>
$(document).ready(function() {
$("#my_form").submit(function(event) {
event.preventDefault() // to prevent natural form submit action
$.post(
"processing.php",
{ name: "p" },
function(data) {
var response = jQuery.parseJSON(data);
$("#txtHint").html(response.hello_world);
}
);
});
});
</script>
</head>
<body>
<form id="my_form" action="/" method="post">
<input type="text" name="user" />
<input name="action" type="hidden" value="the_ajax_hook" />
<input type="button" name="submit" value = "Click This" />
</form>
<div id="txtHint"></div>
</body>
</html>
And then in processing.php:
<?php
$name = $_POST['name'];
$response['hello_world'] = "Hello World, " . $name;
echo json_encode($response);
?>

How to POST to 2 pages by help of button or link in HTML?

Hey Friends
i am having one forms and two button, and some text fields,what i need it if i click button 1 then the details in the text box should be POST to Page1.php if i click Button2 the details in the text box should be POST to Page2.php, i am having 8 text boxes to do the in form, how can i do that?
Let's suppose your button one id is btn1 and second has btn2 and form name is frm, you can do something like this:
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
btn1.onclick = function(){
document.forms['frm'].action = 'page1.php'
document.forms['frm'].submit(); // submit the form
};
btn2.onclick = function(){
document.forms['frm'].action = 'page2.php'
document.forms['frm'].submit(); // submit the form
};
A PHP solution would be:
<form action='' method='post'>
<input name='inputText' /><br />
<button value='1' name='whichOption'></button><br />
<button value='2' name='whichOption'></button><br />
</form>
At the top of the page this form is in, put this:
<?php
if(isset($_POST['whichOption']) {
switch($_POST['whichOption']) {
case 1: /* do something */ break;
case 2: /* do something else */ break;
}
}
?>
"something" is an include, a session variable set, or whatever you like.
Try this:
<input type="button" value="page1" onclick="this.form.action='Page1.php'; this.form.submit();" />
<input type="button" value="page2" onclick="this.form.action='Page2.php'; this.form.submit();" />
Why not just use the same page? When I need multiple submit alternatives I simply use submit buttons with different names:
<input type="submit" name="submit-save" value="Save" />
<input type="submit" name="submit-delete" value="Delete" />
When I need to know what action it is, I just check which data is sent:
if(isset($_POST['submit-save']))
{
//Do something
}
elseif(isset($_POST['submit-delete']))
{
//Do something else
}
Html:
<input id="Button1" value="Button1" type="button" /><br />
<input id="Button2" value="Button2" type="button" /><br />
<textarea id="TextBox1" cols="40" rows="5"><br />
<textarea id="TextBox2" cols="40" rows="5">
jQuery:
function PostToPage(DOOMid,uri) {
var vDOOMEl = $("#" + DOOMid);
$.ajax({
type: 'POST',
url: uri,
data: ({text : vDOOMEl.innerHTML}),
success: function() {},
dataType: "html"
});
}
function init() {
$('#Button1').click(function(e){
PostToPage('TextBox1','Page1.php');
});
$('#Button2').click(function(e){
PostToPage('TextBox2','Page2.php');
});
}
window.onload=init;
PHP:
<?php
//do something with $_POST['text'];
?>
You must download jQuery, and use it for this solution

Categories