Resetting json file with button click - javascript

I have a todo list program and I want it to be reset to a predefined set of json within the json file once a button is clicked. For example, if the json file was full with data and someone clicked the button I want it to edit the json file to just say:
[{"completed":false,"task":"Kitchen - Sweep Floor","important":false}]
This is on cpanel latest using the latest stable php version. I've tried fwrite and file_put_contents but can't seem to get it working.
This is what I've tried already:
<html>
<h2>Click</h2>
<form action="" method="post">
<button name="click" class="click">Click me!</button>
</form>
<?php
if(isset($_POST['click']))
{
echo file_put_contents("test.json","[{"completed":false,"task":"Kitchen - Sweep Floor","important":false}]");
}
?>
</html>
When clicking the button nothing happens, no errors or anything?

You haven't assigned an action to the form, for this to work you should add the URL of the current page (so it redirects to itsself). Only then the post request is sent.
PHP won't run anything asynchronous: stuff only happens on page load.

You have syntax errors in your script - you have to escape the quotes in the string. Always look at the webserver error log or enable error display during development.
Here is the fixed code:
echo file_put_contents("test.json","[{\"completed\":false,\"task\":\"Kitchen - Sweep Floor\",\"important\":false}]");
You should use something like json_decode. Don't build json by hand:
$data = array(
"completed"=>false,
"task"=>"Kitchen - Sweep Floor",
"important"=>false
);
echo file_put_contents("test.json",json_encode($data));

Related

How to run a PHP function due to a button click (with button 'data' passed)?

I know that AJAX could solve my issue. I need help how I can solve it in my specific case however. I manage some sortiment items on a page, they get displayed with a PHP script (checks the database, if the item is available, and if so, it gets displayed). I now want an admin page where I can kind of "toggle" via a sortiment table to display or not display an item (set it as available or non available.
What I need is: if the button is clicked, I would like to start a php-skript. There should be an value passed to that script (the button id). The script itself should open an SQL connection, change a DB value based on the passed ID of the button. Then close the connection. Optionally also refresh the table (or one value) from where the button was clicked.
Can someone help me, at least telling me what I need to do this? (jQuery, Ajax?). The passing of the ID would be important, else I'd need to do function for every button.
An table entry looks like this:
<tr>
<td>Himbeerhonig</td>
<td id="himbeerhonig">Ja</td>
<td><button type="button" id="himbeerhonig" onclick="function()">press me to execute function</button></td>
</tr>```
(possible PHP pseudocode)
open SQL connection
look for database entry based on the passed ID
change the value of the found entry (!currentValue)
close SQL connection
*optionally*
refresh the <td id="himbeerhonig"> with the updated value.
I appreciate any help very much! Just need some hints as to how to do it properly. It's just a concept that currenty is hard to grasp for me so far.
1- If you want to do this with ajax (without browser refresh), you should create a separate php file, and put your php scripts in there. it's called api (api has special format for output, so search create api in php if you want to do this). then on javascript, you should do an ajax call to that php address, on onclick event of button. and then javascript will return data and you can create elements based on that data.
2- however you can do this without ajax(it will refresh browser). just write your inline phps as you wrote :
<html>
<!-- your html codes-->
<?php
if($_GET['buttonClicked']){
//put your php codes here to run when button clicked
?>
<!-- you can even put html here, even it can be on php loop. -->
<?
}
<!-- your html codes-->
<!-- turn your button to a form-->
<form action="/" method="get">
<input name="buttonClicked" hidden value='1'>
<input type="submit" value="Submit">
</form>
</html>
it's as easy as this. when button clicked, a get request will send to current page, and php will handle it, for example it will render additional html elements to the page.

Google reCaptcha v3 returns success as false

I am testing my user login/registration system. I finally finished the form and I have been testing the form for a while now. It was working before I got the form finished and it works perfectly fine on another page however, it won't work on my page for registration. It keeps sending the success as false. My other page is a contact form and it's not that different from my registration page. It has all the same files inside.
My error code keeps showing me that I'm a bot when I'm clearly not a bot and I'm just testing out my own code.
I thought before there was a problem with where the code was stored in the directory at first, so I tried that.
Then, I thought that if I changed the keys, then maybe I would manage to get the system to work again. That didn't work.
Finally, I tried rearranging my html code to get it to work and that didn't work either.
Now, the crazy part, I'm still getting a score of 0.9 (checked on recaptcha site), which is enough for me to pass as a human but, it's still giving me that error within the JSON.
It worked fine before but, as soon as I started to test my input validation for my registration form, it began to call my response a false.
This is the error I keep getting. I wasn't too sure about formatting a JSON. This was returned with the php function var_dump. It was technically just one line.
object(stdClass)#13 (2)
{
["success"]=> bool(false)
["error-codes"]=> array(1)
{
[0]=> string(22) "missing-input-response"
}
}
This is the script I have in a file called recaptcha.php
<script src='https://www.google.com/recaptcha/api.js?render=<?php echo SITE_KEY; ?>'></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('<?php echo SITE_KEY; ?>', {action: 'homepage'}).then(function(token) {
document.getElementById('g-recaptcha-response').value=token;
});
});
</script>
EDIT/
Added some additional code.
A php function. The constant SECRET_KEY is defined as a global variable in another file.
function getCaptcha($secretKey) {
$response =
file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . SECRET_KEY . "&response={$secretKey}");
$reCaptcha = json_decode($response);
return $reCaptcha;
}
This is included where I verify the recaptcha.
$reCaptcha = getCaptcha($_REQUEST['g-recaptcha-response']);
var_dump($reCaptcha);
If that helps.
I'm expecting it to turn into ["success"]=> bool(true) but, I don't even have the slightest clue what's wrong. I'm ready to get Google on the phone just to solve this issue. Can anyone help?
This error means that you're not passing in the site 'secret' param to the POST request to:
https://www.google.com/recaptcha/api/siteverify
Check that the 'secret' param (called SECRET KEY in the settings screen of the admin area), is correct and is being sent in the POST request.
Okay, so after looking at a few things, I found out why it kept returning as a "missing-input" error.
I had a page with two forms and only one recaptcha.
<form>
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response" />
</form>
<form>
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response" />
</form>
Because there were two of them, the API didn't know which to distinguish and instead of assigning the same value to both, it assigned no value to either. So, in-order to fix this I changed my javascript to this:
<script src='https://www.google.com/recaptcha/api.js?render=<?php echo SITE_KEY; ?>'></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('<?php echo SITE_KEY; ?>', {action: 'homepage'}).then(function(token) {
document.getElementById('g-recaptcha-response').value=token;
document.getElementById('g-recaptcha-response2').value=token;
});
});
</script>
And my input form looked something like this:
<form>
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response" />
</form>
<form>
<input type="hidden" id="g-recaptcha-response2" name="g-recaptcha-response2" />
</form>
The same value but, put into two separate fields. Even if you are using the second field for just one page, it's okay to leave it in there because it won't affect a page with just one recaptcha. As long as the first field is used to store the token and is reference in your html. I also changed this in the php.
$reCaptcha = getCaptcha($_REQUEST['g-recaptcha-response2']);
var_dump($reCaptcha);
I guess for anyone building a page with multiple forms, if you want to use recaptcha, you will need to distinguish two different input fields to receive the token. After spending nearly a day on this, I can't believe it took me that long to figure out something so simple. This will solve the missing-input error as well as the invalid-input error.

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.

Can I redirect to a new php file while posting a form input?

I have a html web page which I use to get some user input. This input is then posted using jquery to a php script which in turn sends a get request to a REST API to receive json data.
My question really is: is it possible to change my php file into another webpage with embedded php and redirect to this while posting the variables to the same script, so I could display the json results in a table on a new page simultaneously.
I already receive the json in the javascript file and I know I could use this to create a table, I was just interested if I could in fact do it all in one go on the php page as I already have script written to populate a table using the json data.
I have included some basic fragments of my code to help explain what I am doing.
HTML:
<head>
<script type="text/javascript" src="collect_User_Input.js"></script>
</head>
<p> What is the unique id of the beacon? </p>
<form> <input type="text" id="uniqueId" /> </form>
<button onclick="collect_User_Input();" >Send Request</button>
JS:
var uniqueId = document.getElementById('uniqueId');
$.post("send_Request.php", { uniqueId: uniqueId.value },function(result) {
alert(result);
PHP:
$uniqueId = $_POST["uniqueId"];
(GET request using curl)
echo ($uniqueId);
I tried skipping the javascript step and submitting the form directly, but this always gave me forbidden error messages. as you may have guessed I am very new to this so any advice is welcome.
In your PHP you will most likely want to return some JSON using json_encode:
http://php.net/manual/en/function.json-encode.php
Within your JSON, you could return a success value - then depending on the value of that you can redirect using:
window.location
You could even have a second attribute that returns what page you want the user redirected to if it isn't the same as the uniqueID:
{"success":true,"location":"/your/path/here.html"}
The flip side being, if there is an error you can return this to your page with a relevant message:
{"success":false,"message":"ID not found"}
I use this process to check something is valid on the server before doing the redirect, which sounds more or less the same as what you want to do?

command to print a page in php without prompt

I am using following code in php, html and javascript to print a html page and redirect to another page. It displays a prompt. I need that page to be printed without showing printing prompt/screen and automatically redirect to new php page.
<input type="button" value="Print & Do New Transaction" class="button" id="payout_print" onclick="window.print();window.location.href='transaction/admin/new_transaction'">
I have gogled it, but didn't get any useful answer that I am looking for. How to do this?
For redirect a page you need to do:
<?
header("Location: destination_page.php");
exit;
?>
Remember to don't print any html code before this code because you'll get an error

Categories

Resources