how to execute php function on html button click - php

Hello I want to execute bb() function on button click.
I tried following code but it did not work.
echo "<div class ='i2' id=".$x.">";
echo "<button type='button' style='display: none;' id='i' name='delete' onclick='document.body.removeChild(this.parentNode)'>";
echo"</button>";
echo "</div>";
<?php
function bb()
{
echo "hello";
}
if (isset($_GET['delete'])) {
bb();
}
?>

Your button is HTML and your function is PHP. They look like together because they are in the same file, but they are not together. PHP exists only on the server. HTML only works on the client (browser). When you see the button on your browser, the PHP is gone, you only have HTML.
To make a HTML button to call a PHP function, you will have to move your function to a PHP file, then make your button to call it with Ajax. Example:
bb1.html : contains button that uses Ajax to call PHP function.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'bb2.php', // <=== CALL THE PHP FUNCTION HERE.
success: function ( data ) {
alert( data ); // <=== VALUE RETURNED FROM FUNCTION.
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
</head>
<body>
<button onclick="myAjax()">Click here</button> <!-- BUTTON CALL PHP FUNCTION -->
</body>
</html>
bb2.php : contains function that returns "hello".
<?php
function bb()
{
echo "hello"; // VALUE RETURNED.
}
bb();
?>
Create two text files with the given names, copy-paste this codes, open your browser and run "localhost/bb1.html".
This is how a button calls a PHP function : Ajax does all the magic.

Related

How to call php code from button onclick with Ajax?

I'm new into php and I am trying to call code from another file.
I try to use ajax to so, because later I would like to add parameters. But unfortunattely for me nothing appen when I click on my button.
I have a button in my file admin.php that is written like this:
<button onclick="clickMe()"> Click </button>
And in the same file I have my ajax code in script balise:
<script>
function clickMe() {
$.ajax( {
url: 'delete.php',
type: "POST",
success: test() {
alert('ok');
}
error : test(){
alert("error");
}
});
}
</script>
And here is the code that I'm trying to call in my ajax, the function test in the file delete.php:
<?php
function test() {
echo "Hello the World! ";
}
?>
I wondering if I maybe need to put the code in delete.php in a function ?
Do you think I need to post the entirety of my admin.php file, even thought a lot of the code is not related to the question ?
EDIT: I forgot to mention; i have require delete file in my admin one:
require 'delete.php';
I don't know jQuery, but I think your code should look something like this:
<?php
// delete.php
// make somthing
return 'Helo Word';
<script>
function clickMe() {
$.ajax( {
url: 'delete.php',
type: "POST",
success: response => {
alert(reponse);
},
error: error => {
alert(error);
}
});
}
</script>
let's assume that your js code is working(i'm bad with JQuery). The JS code and the PHP code are living in different worlds but can connect by HTTP requests(XML-AJAX) and some others.
You can do a request to a PHP page like my-domain.com/the-page.php?get_param_1=value(GET method), and you can pass the same params(and a little more) by POST method. GET and POST params are looking like :
param_name=param_value&param_name=param_value&param_name=param_value
You can't call directly PHP function(like var_dump('123);), but you can do this request with JS my-domain.com/the-page.php?call_func=myFunc123&printIt=HelloMate
to php page
<?php
function myFunc123($printText) { echo $printText; }
if (array_key_exists('call_func', $_GET)) {
$param_callFunc = $_GET['call_func'];
if ($param_callFunc == 'myFunc123') { myFunc123($_GET['printIt']); }
}
?>
Yes, you can pass any existing function name and call it, but it's not safe in future usage. Above, i use "page" word because you should do a request, not php file read or access.
Here is how I finally did it :
I gived an id to my button:
<button id="<?php echo $rows['id']; ?>" onclick ="deletedata(this.id)">Delete</button>
I give in deletedata the parameter this.id, it's a way to give the id of the button as parameter, then I use Ajax to call delete:
<script type="text/javascript">
// Function
function deletedata(id){
$.ajax({
// Action
url: 'admin',
// Method
type: 'POST',
data: {
// Get value
id: id,
action: "delete"
},
success:function(response){
}
});
};
</script>
Here is the tricky thing, I didn't use a fonction as I thought I needed. Instead I did this :
if (isset($_POST["action"])) {
echo "Hello the World! ";
// Choose a function depends on value of $_POST["action"]
if($_POST["action"] == "delete"){
mysqli_query($conn, "DELETE FROM bdd_sites WHERE id = " . $_POST['id'].";");
}
header('Location: '.$_SERVER['REQUEST_URI']);
}
?>

Call functions from iframe

I am uploading files using a hidden iframe as a target...from inside this iframe I want to run a function that's on my main page.
In my target iframe.php I have
<script>
upload_completed(<?php echo $numerolinha ?>);
</script>
but I get from firebug:
ReferenceError: loading_linha_21 is not defined
parent.upload_completed();</script>
If I run upload_completed(loading_linha_21); on my main page it runs ok so I'm guessing the command to run the function on the parent page isn't working... help!
I also tried :
window.top.upload_completed(<?php echo $numerolinha ?>);
window.upload_completed(<?php echo $numerolinha ?>);
my functions :
<script >
function upload_started(id){
$(id).css("display","block");
}
function upload_completed(id){
$(id).css("display","none");
}
</script>
The best guess i can give you is that the jQuery function requires the id to be #name_of_id, so when you call the function from the iframe like so:
parent.upload_completed('#<?php echo $numerolinha ?>');
or you can change your function to do this:
function upload_started(id){
$( '#' + id).css("display","block");
}
function upload_completed( id ) {
$( '#' + id ).css("display","none");
}
Put a ' inside function like below :
<script>
upload_completed('<?php echo $numerolinha ?>');
</script>

updating div without page refresh

i have a php script that counts button clicks to a txt file. this is working just fine.
On my html page i am displaying the clicks as such :
<?php
include ('counter.php');
?>
<div class="count_right" id="one"></div>
<div class="count_left" id="two"></div>
<form action="" method="post" id="form" >
<button class="vote_right" name="clicks1" ></button>
</form>
<form action="" method="post" id="form2" >
<button class="vote_left" name="clicks2"></button>
</form>
the php
<?php
if( isset($_POST['clicks1']) ) {
incrementClickCount1();
}
function getClickCount1()
{
return (int)file_get_contents("count_files/clickcount1.txt");
}
function incrementClickCount1()
{
$count = getClickCount1() + 1;
file_put_contents("count_files/clickcount1.txt", $count);
}
if( isset($_POST['clicks2']) ) {
incrementClickCount2();
}
function getClickCount2()
{
return (int)file_get_contents("count_files/clickcount2.txt");
}
function incrementClickCount2()
{
$count2 = getClickCount2() + 1;
file_put_contents("count_files/clickcount2.txt", $count2);
}
?>
and the js (EDITED)
<script type="text/javascript">
var valueOne = "<?php echo getClickCount1(); ?>";
var valueTwo = "<?php echo getClickCount2(); ?>";
$('#one').html(valueOne);
$('#two').html(valueTwo);
$('.vote_right').click(function(){
$.ajax({
type: "POST",
url: "counter.php",
data: valueOne,
cache: false,
success: function(data)
{
$("#one").html(data);
} });
</script>
tried also adding
e.preventDefault();
but then the button wont work.
My problam is that i dont want the page to refresh when the button is clicked. insted i would like the div to refresh with the new data.
I have tried usin ajax but with no success. its either the page refreshes or the data wont update.
Any suggestions?
Use type=button to not submit the form when clicking buttons (and thus prevent page reloading).
<button type="button" class="vote_right" name="clicks1" ></button>
The below shows how to write two of the 4 api calls you need to add to your website.
Main Page:
<?php
include ('counter.php');
?>
<div class="count_right" id="one"></div>
<div class="count_left" id="two"></div>
<button class="vote_right" name="clicks1" onclick="addCount1()"></button>
<button class="vote_left" name="clicks2" onclick="addCount2()"></button>
JS:
<script type="text/javascript">
var valueOne = //use ajax (GET) to call the page for count1;
var valueTwo = //use ajax (GET) to call the page for count2;
$(document).ready(function(){
$('#one').html(valueOne);
$('#two').html(valueTwo);
});
function addCount1(){
//use ajax (POST/PUT) to call a page that adds 1 to your text file thing for count1
}
function addCount2(){
//use ajax (POST/PUT) to call a page that adds 1 to your text file thing for count2
}
</script>
New API Page (for count1):
<?php
class IntegerValue implements JsonSerializable {
public function __construct($number) {
$this->number = (integer) $number;
}
public function jsonSerialize() {
return $this->number;
}
}
echo json_encode(new IntegerValue(getClickCount1()), JSON_PRETTY_PRINT);
?>
New API page (for count2):
<?php
class IntegerValue implements JsonSerializable {
public function __construct($number) {
$this->number = (integer) $number;
}
public function jsonSerialize() {
return $this->number;
}
}
echo json_encode(new IntegerValue(getClickCount2()), JSON_PRETTY_PRINT);
?>
How PHP and JavaScript work
On initial page load:
The process flow looks like this:
Server Side code (php) -> sends data to client -> browser begins rendering and executing JS
On form Submit:
Client Executes code (javascript) -> Sends data to server -> Server gets data and processes (PHP)
Because of this if you don't want the page to "refresh" you'd have to use JavaScript and the best way of handling this is AJAX if you use a form you are going to get a refresh also known as a POST-BACK. Otherwise with AJAX you can easily just send a POST or a GET and it won't refresh.
No need to put with in form tag for ajax async request.
Use only
<?php
include ('counter.php');
?>
<div class="count_right" id="one"></div>
<div class="count_left" id="two"></div>
<button class="vote_right" name="clicks1" ></button>
<button class="vote_left" name="clicks2"></button>

PHP and JQuery: value not updating

Couple questions:
1) I'm trying to have a new random value updated each time a button is pressed. When the button is clicked, a value is generated once... but is not random. So I'm not sure if the function is being called again on click because a new value isn't generated.
2) Can I include the php code within the same file as the jquery when using a server call such as $.get() and call it as a function within that same file?
The reason is, I don't want to have to keep creating new php script files, and would rather throw the code in the same file as the calling jquery.
Meaning...
Instead of $.get("../scripts/NameGenerator2.php",
I do this: $.get("a php function within this same file",
JQuery:
<?php
if ($imgid == 1) {
?>
<button onclick="generate()">Generate</button>
<button id="generateButton">Generate</button>
<script type="text/javascript">
$(document).ready(function() {
$("#generateButton").click(function(e) {
//alert("called");
$.get("../scripts/NameGenerator2.php",
function(returned_data) {
$("#generated").html(returned_data);
}
).error(function(jqXHR, status, error) {
console.log("error in $.get")
});
});
});
</script>
<?php } ?>
<br /><span id="generated"></span><br />
PHP:
<?php
$adj = array("Happy", "Great", "Mandarin", "New", "Golden", "Ming's");
$noun = array("Dragon", "Sea", "Wok", "Fortune", "Rice", "Empire");
$place = array("Garden", "China", "Village", "Palace", "Kitchen", "Mountain");
$x = rand(0, count($adj)-1);
$y = rand(0, count($noun)-1);
$z = rand(0, count($place)-1);
echo '<p>' . $adj[$x] . " " . $noun[$y] . " " . $place[$z] . '</p>';
?>
Any thoughts? Thanks!
Updated: Only error I seem to be getting is "Object Expected" in my "myJquery.js" file, which is not the file I'm working in, and doesn't seem connected.
When I add in document ready to my function, the button onclick() call seems to break.
You can call a .php-file with jQuery. But the file should be reachable with your browser and should return qualified data.
With .get() you can define the expected data-type. It can be xml, json, script, or html.
If you want to use json (my favourite) the use the php-function json_encode to generate the output.
If you want to use the same file, create a GET-Parameter e.g. ?ajax=1. With your AJAX-request you call the file and append the GET-Parameter. And in your .php-File you can then switch between an normal call and an ajax call which returns an other output.
<?php
if (!empty($_GET) && !empty($_GET['ajax']) && $_GET['ajax'] == 1) {
// header("Content-type: application/json");
// $data = array(some_data);
// echo json_encode($data);
echo 'AJAX-call-output';
} else {
?>
<!-- [...] -->
<script type="text/javascript">
function generate() {
$.get("../scripts/NameGenerator2.php",
{ ajax: 1 }, // GET-Parameter
function(returned_data) {
//alert("test");
$("#generated").html(returned_data);
}
//, "json"
);
}
</script>
<!-- [...] -->
<?php
}
?>
You cannot get a PHP function but you can load the page and get a specific div -
$('#generated').load('../scripts/NameGenerator2.php #pagePart');
You echo out PHP with the proper id's in place, for instance -
echo '<p id="pagePart">' . $adj[$x] . " " . $noun[$x] . " " . $place[$x] . '</p>';
Without using any inline JavaScript this is what your jQuery code might look like -
<button id="generate">Generate</button>
$(document).ready(function() {
$('#generate').click(function(e){
e.preventDefault();
$('#generated').load('../scripts/NameGenerator2.php #pagePart');
});
});
Based on your update you need to move all of your jQuery functions into the document ready function.

Call function in a seperate div tagad from href link

I have two files: index.php and cart.php
In cart.php I have few three functions - products_all(), products_shirts(), products_hoodies(). Those functions get info from my database and outputs it if called.
I want each of those functions to be called by clicking on hyperlinks and then to be outputed in a div tag, so that only the div tag is being refreshed not the whole site.
I read about jQuery/AJAX function load, but I can't get it to work.
If you don't want the whole page to be refreshed, there is no way around using ajax.
But it's not that hard. When using a library like jQuery, you can do it in a few lines.
Your HTNL + javscript code:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function callFunction(yourfunction)
{
$.post('cart.php', { "function": yourfunction }, function(data) {
alert(data);
});
}
$(document).ready(function()
{
$("#functionOne").on("click", function()
{
callFunction(1)
});
$("#functionTwo").on("click", function()
{
callFunction(2)
});
});
</script>
</head>
<body>
<a id="functionOne">function one</a>
<a id="functionTwo">function two</a>
</body>
</html>
And on the server side (cart.php) something like this:
<?php
if (isset($_POST['function']))
{
switch ($_POST['function'])
{
case 1:
functionOne();
break;
case 2:
functionTwo();
break;
}
}
function functionOne()
{
echo "hi, i am func1";
}
function functionTwo()
{
echo "hi, i am func2";
}
This should get you started!

Categories