Javascript generated in PHP is not executing - javascript

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

Related

Php code to modify a document element

I am trying to build a PHP webpage with the following behaviour:
1- A client access the webpage (that contains some buttons);
2- When the webpage is loaded, the PHP script opens a file stored on the server and, based on the information in this file, enables/disables some of the buttons, so that the client can see the webpage with the correct buttons enabled or disabled.
To enable/disable buttons, I know I can use javascript, while to read the file on the server I use PHP as stated above.
How do I put the two things together? Or should I use a PHP code equivalent to the following javascript line:
<script>document.getElementById("button1").disabled = true;</script>
At first I thought that inserting this line in the PHP code was the solution, but then I found out that this can't work for obvious reasons.
Thanks for the help!
Is it correct if I add the following javascript function in the head section of my webpage?
<script>
function enableButtons() {
<?php
if($state=="state1") {
echo 'document.getElementById("button1").disabled = true;';
}
else if($state=="state2") {
echo 'document.getElementById("button2").disabled = true;';
}
?>
}
</script>
I call the enableButtons() function when loading the page by using
<body onload="enableButtons()">
The php code above is just an example, the number of states and buttons is higher, that's why I would like to use this solution.
The common thing to do is to have php read the settings file, and echo the "disabled" attribute on the buttons before sending the output to the user browser. You can get more info about the attribute here here.
You do not need javascript.
Do something like this:
<button type="button" <?php if($state === 'state1') echo 'disabled'; ?>>Button text</button>
Usually you send to the client the buttons already disabled and use js to respond to any event that happens after sending the page, like selecting a combo box value..
You can omit the code, using an if sentence, or hide them using css. First approach is preferred.
Script
<script>
function isValid(f){
if(f.test.value==''){
alert('please enter name');
return false;
}else{
$(".bbutton").html("Processing please wait");
return true;
}
}
</script>
HTML
<form method="post" onsubmit="return isValid(this);">
<input type="hidden" name="te">
<input type="text" name="test">
<div class="bbutton">
<input type="submit" value="send">
</div>
</form>
When you submit the form then it will automatically hide the submit button to avoid pressing again and again, and you can redirect it to other page. May be this idea helpful.

Auto filling a form and submitting based on a ajax search answer

This problem has been frustrating me for a few days, and as I have found some help here for other problems on my project, it seems that someone could provide insight that I am overlooking.
I admit I am very new to sql, javascript, jquery, ajax, css, and php. I did 3 years of Computer science in college (15 years ago) While coding and logic don't change much, its syntax and handshakes, and where the computing is happening that I have either forgotten, overlooked, or am ignorant.
I have completed an ajax based search submission.
this search displays the target php in a div labeled .Admin
this works excellently.
Its answer is a display of a tree and the nodes above and below the searched node.
I want to make each node in the tree a clickable link to the search results for its own node.
In the php result I coded it to write in a html call to a javascript function and it generates a unique id for each , as well as its own function call. (whether or not that is a good idea its what i tried) I would think that it is then easy to get javascript to fill out the form with the created link using information it knows and resubmit as no refresh is needed to search again. I tried having the php write this script so that it is developed with the page, and I have tried writing the script and including it in the parent page, so that it is already loaded... I'm not sure where it should go or how it should be written.
I may be missing an integral part, or I'm trying to do more than I am supposed to with the code or not completely grasping where the operation is happening and need to rethink it entirely.
I will try to include all relevant code, if its not enough, I will happily add. Thanks in advance.
CallSearch.js
$(document).ready(function() {
$('#Search').submit(function(event) {
$.ajax({
type : 'POST',
url : 'MenuSearch.php',
data : $( this ).serialize()
})
.done(function(results) {
$(".Admin").html(results);
});
event.preventDefault();
});
});
Menu.php (where my search form is)
<script src="/JS/CallSearch.js"></script>
...
<li><a>Search</a> <input type= "text" name="Search" id="search_name" class="search-group">
<ul>
<li><input type="radio" name="Table" id="TableRegion" value="R" class="search-group" checked><label for="TableRegion">Region</label></li>
<li><input type="radio" name="Table" id="TableGrape" value="G" class="search-group"><label for="TableGrape">Grape</label></li>
<li><input type="radio" name="Table" id="TableWine" value="W" class="search-group"><label for="TableWine">Wine</label></li>
<li><button type="submit" id="SubmitSearch">Submit</button></li>
</ul>
</li>
</form>
...
MenuSearch.php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'Webpage');
define('DB_PASSWORD', 'Guest');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
...
$sqlp ="SELECT * FROM region a JOIN Regionclosure b ON a.idregion=b.parent WHERE b.child= $idReg ORDER BY b.Depth DESC;";
...
$resultp = mysqli_query($db, $sqlp);
$string ="";
while($row = mysqli_fetch_assoc($resultp)){
$Reg = $row["RegName"];
$Parent= $row["Parent"];
echo $string . "|___";
if($_SESSION["Level"] == 'A' or $_SESSION["Level"] == 'C')
echo $Parent . " - ";
echo "<a href='#' id='$Reg'>" . $Reg . "</a><br>";
echo "
<Script>
$('#$Reg').click(function(){ searchforReg('$Reg'); return false; });
</script>";
$string .= " ";
};
I have tried multiple iterations of a function for "searchforReg('$Reg'); to no avail... i feel like it should be something like :
function "searchforReg(Region){
SearchData= "Table=R&Search="+$(Region).val;
(function() {
$.ajax({
type : 'POST',
url : 'MenuSearch.php',
data : SearchData
})
.done(function(results) {
$(".Admin").html(results);
});
event.preventDefault();
});
});
This however results in activating the "action" search failing to send the answer to the and opens the php (with no CSS... gasp.. its just not pretty) I feel like a simple javascript should be able to handle it, but i tried all of the different ways i could think of (or look up) to make it work to no avail.
I realize I am playing in the "deep end," and I'm in my "water wings" so if you could have mercy and push me to the edge, I would appreciate it.
First, the process of printing a click handler for each link is overkill. Instead, just give each link a class and set up a single handler for any link of that class. In menusearch.php:
echo "<a href='#' id='$Reg' class='reg_link'> $Reg </a><br>";
$string .= " ";
Side note - in PHP, if you echo with "double" quotes, variables will be rendered, so no need to concatenate. That's why $Reg is just hanging out. If you echo with 'single' quotes, the string is interpreted literally.
Then in menu.php, we have a bit of javascript:
<script>
/* This is a non-standard listener, bound to the body so that any
dynamically added elements pulled in via ajax, but not in the original document can still be found.
Also, this can be shortened to a single line, but I split it up for clarity.
The single-line version is commented out. */
$(document.body).on('click', '.reg_link', function(){
//searchforReg($(this).attr('id'));
var id = $(this).attr('id'); //get the id of clicked element
searchforReg(id); //trigger function
});
function searchforReg(Region){
var SearchData= "Table=R&Search="+Region;
//If you're not familiar with console.log, it's a huge help in debugging
//console.log('searchData = ', SearchData);
$.ajax({
type : 'POST',
url : 'MenuSearch.php',
data : SearchData
})
.done(function(results) {
$(".Admin").html(results);
});
}
</script>
Finally, I'm guessing you have some $_POST handling in MenuSearch.php for that data, but I don't see that above so I'll assume it's working...

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?

Execute PHP function with onclick

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

rating button, one click to pass parameters and execute php

I'm somehow stuck when I'm working on:
I want to pass a parameter to a php file and execute it when we rate something. php file is finished, but don't know how to code js part.
In detail,
user rates a passage, js gets the rating;
------ get parameters, store them in function Rate(), finished
when user submits it;
------ don't know how to check if the button is clicked, add DomListener in Rate()?
js calls the php file meanwhile passing the rating parameter to it;
------ php part finished
execute the php file without opening it in a new window.
----- don't know what to do.
HTML
<div>
<form id="rateform" action="php/rate.php" enctype="text/form-data" method="POST">
<input id="rating" type="text" />
<input id="sbm" type="button" />
</form>
</div>
JS
function Rate(){
var rate = document.getElementById("rating").value;
var sbm = document.getElementById("sbm");
// don't know how to do...
//if(sbm is clicked) {
// execute rate.php...
//}
}
thx in advance.
Here's how I'd do it in jQuery (better than dealing with an XMLHttpRequest object):
$('#sbm').click(function() {
var rating = $('#rating').val();
/* Send request to PHP script. */
$.post('/url/to/script', { rating: rating }, function(resp) {
console.log('Response:', resp);
});
});
And your php script could be something like:
<?php echo 'Hey, I got this rating ' . $_POST['rating']; ?>
I'm not a PHP guy, though!

Categories

Resources