Execute PHP function with onclick - javascript

I am searching for a simple solution to call a PHP function only when a-tag is clicked.
PHP:
function removeday() { ... }
HTML:
Delete
UPDATE: the html and PHP code are in the same PHP file

First, understand that you have three languages working together:
PHP: It only runs by the server and responds to requests like clicking on a link (GET) or submitting a form (POST).
HTML & JavaScript: It only runs in someone's browser (excluding NodeJS).
I'm assuming your file looks something like:
<!DOCTYPE HTML>
<html>
<?php
function runMyFunction() {
echo 'I just ran a php function';
}
if (isset($_GET['hello'])) {
runMyFunction();
}
?>
Hello there!
<a href='index.php?hello=true'>Run PHP Function</a>
</html>
Because PHP only responds to requests (GET, POST, PUT, PATCH, and DELETE via $_REQUEST), this is how you have to run a PHP function even though they're in the same file. This gives you a level of security, "Should I run this script for this user or not?".
If you don't want to refresh the page, you can make a request to PHP without refreshing via a method called Asynchronous JavaScript and XML (AJAX).
That is something you can look up on YouTube though. Just search "jquery ajax"
I recommend Laravel to anyone new to start off right: http://laravel.com/

In javascript, make an ajax function,
function myAjax() {
$.ajax({
type: "POST",
url: 'your_url/ajax.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
}
Then call from html,
Delete
And in your ajax.php,
if($_POST['action'] == 'call_this') {
// call removeday() here
}

It can be done and with rather simple php
if this is your button
<input type="submit" name="submit>
and this is your php code
if(isset($_POST["submit"])) { php code here }
the code get's called when submit get's posted which happens when the button is clicked.

You will have to do this via AJAX. I HEAVILY reccommend you use jQuery to make this easier for you....
$("#idOfElement").on('click', function(){
$.ajax({
url: 'pathToPhpFile.php',
dataType: 'json',
success: function(data){
//data returned from php
}
});
)};
http://api.jquery.com/jQuery.ajax/

Solution without page reload
<?php
function removeday() { echo 'Day removed'; }
if (isset($_GET['remove'])) { return removeday(); }
?>
<!DOCTYPE html><html><title>Days</title><body>
Delete
<script>
async function removeday(e) {
e.preventDefault();
document.body.innerHTML+= '<br>'+ await(await fetch('?remove=1')).text();
}
</script>
</body></html>

Here´s an alternative with AJAX but no jQuery, just regular JavaScript:
Add this to first/main php page, where you want to call the action from, but change it from a potential a tag (hyperlink) to a button element, so it does not get clicked by any bots or malicious apps (or whatever).
<head>
<script>
// function invoking ajax with pure javascript, no jquery required.
function myFunction(value_myfunction) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("results").innerHTML += this.responseText;
// note '+=', adds result to the existing paragraph, remove the '+' to replace.
}
};
xmlhttp.open("GET", "ajax-php-page.php?sendValue=" + value_myfunction, true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php $sendingValue = "thevalue"; // value to send to ajax php page. ?>
<!-- using button instead of hyperlink (a) -->
<button type="button" onclick="value_myfunction('<?php echo $sendingValue; ?>');">Click to send value</button>
<h4>Responses from ajax-php-page.php:</h4>
<p id="results"></p> <!-- the ajax javascript enters returned GET values here -->
</body>
When the button is clicked, onclick uses the the head´s javascript function to send $sendingValue via ajax to another php-page, like many examples before this one. The other page, ajax-php-page.php, checks for the GET value and returns with print_r:
<?php
$incoming = $_GET['sendValue'];
if( isset( $incoming ) ) {
print_r("ajax-php-page.php recieved this: " . "$incoming" . "<br>");
} else {
print_r("The request didn´t pass correctly through the GET...");
}
?>
The response from print_r is then returned and displayed with
document.getElementById("results").innerHTML += this.responseText;
The += populates and adds to existing html elements, removing the + just updates and replaces the existing contents of the html p element "results".

Try to do something like this:
<!--Include jQuery-->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("somepage.php");
return false;
}
</script>
Click Me!

This is the easiest possible way. If form is posted via post, do php function. Note that if you want to perform function asynchronously (without the need to reload the page), then you'll need AJAX.
<form method="post">
<button name="test">test</button>
</form>
<?php
if(isset($_POST['test'])){
//do php stuff
}
?>

Try this it will work fine.
This will work without form tags and button tag.
<div onclick="window.location='?hello=true';">
<?php
if(isset($_GET['hello'])) {
hello();
}
function hello()
{
echo "hello world";
}
?>

Related

Javascript generated in PHP is not executing

I'm trying to create a roulette system, which should work as follows: The user clicks on a submit button, which is then checked on the opening_case_handler.php file to see whether the user has sufficient funds in his account or not, and if he does it will echo javascript code which will create the animation for the roulette and will also come out with the winning prize. For security purposes I am executing the js code in php so the user has no access to it since it is executed in the server side.
The issue here is that the js and jquery code do not get executed once this line of code has been reached:
var gw = $(".gift").outerWidth(true);
in the opening_case_handler.php.
You will notice that there are two alerts before and after the previous line code I have just mentioned. If I uncomment alert("TEST1") it will get executed and an alert message will appear however the rest of the code will no be executed. Also if I uncomment only the alert("TEST2") it will not be executed and nothing will happen.
To make sure that the javascript code actually works. I previously tested it in a javascript file and sourced it in the index.php file and it worked perfectly.
index.php
This page contains the roulette with all the different images of each item. The submit button is at the bottom. This is the button that users will click to be able to spin the roulette.
<div class='rafflebox'>
<div class='pointer'></div>
<div class='boxwrapper'>
<ul class='giftwrapper'>
<div class="gift item bg-size2 box-bg3">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
<div class="gift item bg-size2 box-bg2">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
<div class="gift item bg-size2 box-bg3">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
<div class="gift item bg-size2 box-bg4">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
</ul>
</div>
</div>
<form method="post">
<button type="submit" name="opening_case" class="btn open-box-btn btn-openbox-font button"><img id="lock" src="graphics/iconos/Candado Cerrado Black.png">ABRIR CAJA</button>
</form>
</div>
opening_case_handler.php
<?php
session_start ();
if(isset($_POST['opening_case']))
{
opening_case ();
}
function opening_case ()
{
if ($_SESSION['balance'] >= $_SESSION['box price'])
{
echo '
<script>
//alert("TEST1");
var giftamount = 10;
var gw = $(".gift").outerWidth(true);
//alert("TEST2");
var giftcenter = gw/2;
var cycle = 7;
var containercenter = $(".boxwrapper").outerWidth(true)/2;
for(var i = 0; i <=5; i++)
{
var giftduplicate = $(".giftwrapper").children().clone(true,true);
$(".giftwrapper").append(giftduplicate);
}
$(".button").click(function()
{
alert("You DO have sufficient funds");
var btn = $(this);
btn.hide();
var randomgift = Math.floor(Math.random() * 4) + 1;
var dev = Math.random()*(giftcenter+1);
var distance = giftamount * cycle * gw + (randomgift*gw) - containercenter -24 +dev;
console.log(distance);
$( ".giftwrapper" ).css({left: "0"});
$(".giftwrapper").animate({left: "-="+distance},10000,function()
{
alert("You Won Gift" + randomgift);
btn.show();
});
});
</script>';
} else {
//to be done
}
}
?>
Please feel free to express your ideas on how this type of system should be better built. I am open to all suggestions, I am fairly new to this.
Thank you!!
Try using Heredoc string quoting example for printing your JavaScript:
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
Heredoc text behaves just like a double-quoted string, without the
double quotes. This means that quotes in a heredoc do not need to be
escaped, but the escape codes listed above can still be used.
Variables are expanded, but the same care must be taken when
expressing complex variables inside a heredoc as with strings.
If it is just a php code file. You can try some below.
<?php
echo "some stuff here"
if ($condition){ ?>
<script>
alert("condition true");
</script>
<?php } else { ?>
<script>
alert("condition false");
</script>
<?php }?>
When a form gets submitted it redirects you to the PHP page (ie when you click submit in index.php you will get redirected to opening_case_handler.php ) and then the PHP page will send you back to the index page with the new info. Thus, your javascript code gets printed in the opening_case_handler.php which is why your javascript did not get executed. Also, your javascript code will always be visible unless if you do something really creative so if you are trying to handle any sensitive information do it in PHP or any backend framework you are using.
There are ways to fix this issue but I would recommend a different approach to solve this issue. You can use an AJAX request which basically works in the following manner:
You send a request to your PHP server with the data you want to send.
Your PHP server will process the request and send it back to you
Your Javascript code will process the result and show the animations
or whatever you want to do.
This way your algorithm is not shown and your client ( the javascript side ) only handles information entered by the user and the results came from the server.
In your case, we can do that using the following changes
Index.php (which can be changed to index.html now)
<button type="submit" id="opening_case" name="opening_case" class="btn open-box-btn btn-openbox-font button"><img id="lock" src="graphics/iconos/Candado Cerrado Black.png">ABRIR CAJA</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#opening_case").on("click", ()=>{
// $.get( "opening_case_handler.php?opening_case=true", function( data ) {
// console.log(data.funds)
// });
$.ajax({
url: "opening_case_handler.php?opening_case=true",
success: (data)=>{
if(data.funds) {
alert("You DO have sufficient funds")
} else {
("You don't have sufficient funds")
}
},
dataType: "JSON"
});
})
</script>
opening_case_handler.php
<?php
if(isset($_GET['opening_case'])) {
$result = [
"funds" => true,
];
$ResultsInJSON= json_encode($result);
echo $ResultsInJSON;
}
?>
The index.php will send the request when the button is clicked using AJAX which you can read about it here https://api.jquery.com/jquery.get/ then your PHP will receive the request and response with a JSON code which can be processed using the data.whatever as shown in the example above.
Note: I am not a PHP expert but I believe this will be a better method to use in this case.
Note2: You don't need Jquery for Ajax but it's easier! Here is how you do it without Jquery https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp

Jquery and AJAX script to run a PHP script in the background to avoid any refreshing

I have built a follow/unfollow Twitter like system using PHP. Now I would like to run the follow-unfollow PHP script in the background using AJAX/JQUERY to avoid refreshing the page when you follow/unfollow a user. To make things simpler, I will be here just using the example of “unfollow”. As you notice, I am running an iteration to output all the members in the database. I am outputting here (as well for simplicity) just the member’s name and an unfollow button to each one.
This is the code using php.
members.php
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<p class="follow_button">Unfollow</p>
<?php } ?>
unfollow.php
<?php
if($_GET['unfollow_id']){
$unfollow_id=$_GET['unfollow_id'];
$unfollow=Following::unfollow($id, $unfollow_id); //Function that will make the changes in the database.
// $id argument will be gotten from a $_SESSION.
}
I am trying to achieve the same result running unfollow.php in the background to avoid any refreshing. This is what I have come up with, as you might imagine it is not working properly. I am including the Jquery script inside the iteration which I think is the only way of obtaining the $member->id property to then assign it to the Jquery variable.
members.php THE NEW ONE THAT TRYS TO RUN THE SCRIPT WITH AJAX JQUERY
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member_name; ?></p>
<button type="button" class="unfollow_button" id="unfollow">Unfollow</button>
<script type="text/javascript">
$(document).ready(function(){
$("#unfollow").click(function(){
// Get value from input element on the page
var memberId = "<?php $member->id ?>";
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data){
// Success
});
});
});
</script>
<?php } ?>
Can you provide me any help for this to work?
Thanks in advance.
Remember, in HTML, id attributes have to be unique.
Because you're rendering multiple members on a single page, you should not use an id selector in jQuery, but a class selector (e.g. button.unfollow). If you use #unfollow, you'll run into ID conflicts between each of the members' buttons.
First, render all of your members with unfollow buttons without ids. I'm adding the member_id in the markup using a data attribute called data-member_id.
<?php foreach($members as $member) { ?>
<p class="member_name"><?=$member_name?></p>
<button type="button" class="unfollow_button" data-member_id="<?=$member->id?>">Unfollow</button>
<?php } ?>
Then add a single click handler for all button.follow buttons, which extracts the member_id from the clicked button's data-member_id attribute and sends it to the server.
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow_button").on('click', function() {
// Get value from input element on the page
var memberId = $(this).attr('data-member_id');
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data) {
// Success
});
});
});
</script>
On a side-note, you should probably look into building a RESTful service for this, to which you can post proper HTTP requests using http://api.jquery.com/jquery.ajax/.
See here for an intro on REST in PHP I wrote a while back:
Create a RESTful API in PHP?

Pass variables from HTML form -> ajax load()

What I am trying to do
I have a HTML form which looks like this:
[input text field]
[submit button].
I want the output results to display in only a small part of the page (don't want to refresh the entire page after the button is clicked).
What I have done so far
I am using jquery load() as follows:
<script type="text/javascript">
function searchresults(id) {
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
</script>
Results will appear in a div which is exactly what I want:
<div id='myStyle'></div>
The problem
The script above works just fine (I used a variation of it elsewhere). But I have 2 problems:
1-How to call the load() script from the form. I tried this but it doesn't work:
<form id="form" name="form" method="post" action="searchresults('1')">
2-If I am not able to call the load() script from the form, how do I pass what is into the input text field to the load() script so in the end it can be proceessed by the displaysearchresults.php file???
Thanks
Currently its not working since you have a typo:
function searchresult(id) {
/^ no s
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
Here:
action="searchresults('1')"> // this should be on the onsubmit
^
Since you're intention is to submit the form without reloading, you could do something like:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'displaysearchresults.php',
data: {id: 1},
type: 'POST',
success: function(response) {
$('#myStyle').html(response); // assuming the markup html is already done in PHP
}
});
});
Of course in the PHP side, just call it like a normal POST variable:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['id'];
// other stuff you have to do
// echo markup stuff
exit;
}
Ok I have been able to do what I wanted to do, i.e., displaying search results in part of the page without reloading.
Actually it is not necessary to use the ajax load() function. You can do it with the script below:
<form id="form" method="POST">
<input type="text" id="textbox" name="textbox" />
<input type="submit" name="test" />
</form>
<div id="myStyle"></div>
<p>
<script src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#form').on('submit', function(e){
e.preventDefault(); // prevent the form from reloading
$.ajax({
url: 'displaysearchresults.php',
type: 'POST',
dataType: 'html',
data: {text:$('#textbox').val()},
success: function(response) {
$('#myStyle').html(response);
}
});
});
});
</script>
So what is this doing:
It will "read" what the user entered in the textbox,
When the user click the "submit" button, it will put that into a POST variable and send it to "displaysearchresults.php" without reloading the page,
The search results will be displayed between the "mystyle" div.
Pretty nice.
Note for beginers: do not forget to copy the jquery file to your root folder otherwise ajax just won't work.

Get public function via ajax based on a custom script

I am trying to execute a public function with an ajax script with the following
In the front end, root folder from where I am trying to call the public function I have within the contents of the file
details-page.php
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function () {
$("#formaddtofav").on("submit", function (e) {
$.ajax({
type: "post",
url: "lib/execute-ajax.php",
data: $("#formaddtofav").serialize(),
success: function(){
alert("form was submitted");
}
});
e.preventDefault();
});
});
</script>
and HTML
<form id="#formaddtofav">
<input type="submit" name="addtofav" onclick="displaymessage()" id="addtofavs" class="addtofav" value="">
</form>
the public function is located in lib/details-page.inc and looks like this http://pastebin.com/U5tCxwVc
and in the file lib/execute-ajax.php I am echoing the function like I would if i would have not used ajax
<?php
include_once('detail-page.inc');
echo $objWebUser->addtofavorites();
?>
The problem is that I get a success message just that the data is not inserted in the database, what am I missing here.
Function addtofavorites() works 100%, tested with the old method of inserting data (<form action="" method="post"> and if isset).
EXPECTED OUTPUT
When i click the input submit, function should be run and do all the things I have written:
Add data into dbs, check if data is already there and print the coresponding messages.
Please help me on this. It's my first attempt on integrating ajax. It's much appreciated any help.

Calling javascript function from ajax page

I have a form where I upload a file through an ajax call containing an API call.
If the API is successful I want to update a table containing the list of files.
I was thinking of calling a javascript function inside the ajax page, but what I get back is that the function in undefined, I fixed that by putting clarifications.js before the javascript function.
Here is the form (at the top of the page I included the js file containing the javascript function):
<div class='input_table_title'>Upload file:</div>
<div style='float:left;'>
<form name='upload_my_files' action='ajax/clarifications/handle_upload.php' method='post' enctype='multipart/form-data' target='upload_target'>
<input type='file' name='file_upload' />
<input type='hidden' name='notification_id' value='<?php echo $value->NotifiNumber; ?>' />
<input type='submit' value='Upload'>
</form>
<iframe id='upload_target' name='upload_target' src='' style='width:0;height:0;border:0px solid #fff;'></iframe>
</div>
in handle_upload.php I make the API call and at the end of the page I close the php, put the clarification.js and calling the function.
<script src="(position)/clarifications.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
createTable("<?php echo $outcome ?>", "<?php echo $uploaded_filename ?>");
</script>
in the clarifications.js file I declare the function (as I said earlier I included the js file in the form page):
function createTable (result, filename) {
if (result == 'success'){
var success = document.getElementById('clarification_success');
success.style.display = "block";
success.innnerHTML = "File "+filename+" successfully uploaded.";
// Update the list of uploads
var list = document.getElementById('table_clarification');
var myElement = document.createElement("td");
myElement.innerHTML = filename;
list.appendChild(myElement);
}
return true;
}
clarification_success is a div where I want to display a success message.
table_clarification is the id of the table where I want to add the row with filename uploaded
The upload is successful but the function createTable is not defined. Edit: Solved
The other problem that I'm having is that the function can't find the id "clarification_success", I think because is looking for it in the instead of the normal page. Am I correct? If yes how can I solve it?
Note: I'm afraid I can't use jQuery, only Javascript please.
if i understood right - the iframe content should be the separate page. this page is dynamicaly constructed on server and returned to client as a post answer.
this page should probably contain <script src="(path)/clarifications.js"></script> in the header

Categories

Resources