Execute Javascript Fetch() Request After PHP Code Executes Successfully - javascript

I have a form for resetting a user email which currently consists of a password input element, and a 'Change email address' email input.
<form method="post">
<div id="form-row-password" class="form-row">
<label for="password">Enter Password</label>
<input class="input-gateway" type="password" name="password" id="password">
</div>
<div id="form-row-email" class="form-row">
<label for="email">Change Email Address</label>
<input type="email" name="email" id="email">
</div>
<div class="form-row form-row-submit">
<input type="submit" name="update-email" id="button" value="SEND ACTIVATION LINK">
</div>
</form>
With this current form you enter your password and the email address, and then you get emailed a link to confirm your new/change of email address and it all works as desired.
The current PHP process is as follows:
Santisation and validations of inputs
PDO Prepared Statments that update the mysql database
What I Wish To Achieve
What I want to do is have it so this process is split over two stages using AJAX/fetch() in javascript.
The first step would be the user entering their password, and when verified with the database this input disappears and is replaced with the 'new email address' input element.
I've set up some test javascript that fetches this second input element using a 'test' button.
What I want to do is have this fetch() javascript code trigger when then first stage is successful in the PHP code. But I cannot work out how to do this?
The PHP that processes the inputs I will included in the HTML partials that get added and removed by the fetch() javascript so I'm not concerned about that side of things.
Will I use a 'submit' event listener or an 'onchange' event listener and how will the javascript know that the password submission has been successful when this is done in PHP?
// PSEUDO JAVASCRIPT
let button = document.getElementById('button'),
formRowPassword = document.getElementById('form-row-password'),
formRowEmail = document.getElementById('form-row-email');
var filePath = "modals/email-reset-modal.php";
// what type of event listener is best to use ??
button.addEventListener('click', function(){
fetch(filePath)
.then((response) => {
return response.text();
})
.then((data)=>{
formRowPassword = '';
formRowEmail.textContent = data;
})
.catch((error => {console.log(error)}))
})
Is there a built-in PHP function that can effectively talk to javascript so it executes once the password input (1st stage) has been successful?
Any help would be amazing.
Anna

Related

Set Input Value with Javascript - Wont POST on Submit

I'm trying to get data from an API and post it to a database, the form I have worked when you manually input data. but when you set the data from the API request - it updates on the page. Although shows blank when it posts.
I'm using
document.getElementById('Title').value = item.volumeInfo.title;
to get the "Value" in an Input.
and
<div class="form-group">
<label for="name">Authors</label>
<input class="form-control" type="text" value="" id="Author" ng-model="book.Author" required="required"/>
</div>
to attach to form.
<button class="btn btn-primary" ng-disabled="AddNewForm.$invalid ||
isUnchanged(book)" id="add-new-btn"
ng-click="New_Book(book)">Add</button>
Why is it submitting as blank?
Your form elements submit their value via their “name” attribute... does you input element generate a name attribute? If not, this is why it won’t work.
Eg
<input name=“foo” value=“bar”/>
Submits as:
?foo=bar
Your question isn't clear enough for me. But I've tried to make a quick example and make it as general as possible to let you work with your form inputs!
Here is a Live Preview
HTML
<form action="post" id="myForm">
<input type="text" id="title">
<input type="submit" value="Click To Update">
</form>
<h2 id="result"></h2>
JavaScript
// Select our main elements (form, text input, result heading)
const form = document.getElementById("myForm");
const titleInput = document.getElementById("title");
const result = document.getElementById("result");
form.onsubmit = function(e) {
// Don't refresh the page
e.preventDefault();
// Set the input value into the result heading
result.innerHTML = titleInput.value;
}
This solution allows you to write anything in your input, and after submitting your form. You can use that data elsewhere.

Hide Input Field data on Form Submit

I've got a login form with two input fields: username and password.
<form method="post" action="testPwd.html">
<p>
<input type="text" name="username" value="" placeholder="username" maxlength="30"></p>
<p>
<input type="password" name="password" value="" placeholder="password" maxlength="25"></p>
<p class="submit">
<input type="submit" name="commit" value="Enter">
</p>
</form>
Once the user submits the form, his username and password are shown in the browser's network attribute in form data section
Request URL: http://localhost:8090/test/testPwd.html
Request Method: POST
Status Code: 302 Moved Temporarily
username: admin
password: admin
I don't want his username and password to be on display.
How can I do this?
That is an expected behavior. You can always see what parameters are passed to POST method (or any method for that matter)
However, you do not want the inputs to be readable to normal human eye, you can encode the username and password before passing them to the API and decode at the server side before using them.
Below is a very simple example. It does not guarantee anything but it will make the values not readable.
var encodedUsername = window.btoa(username); // encode username
var encodedPassword= window.btoa(password); // encode a password
var decodedUsername = window.atob(encodedUsername); // decode username
var decodedPassword = window.atob(encodedPassword); // decode password

Retrieving the value of button while submitting form with javascript

I have a file index.php with a log in form comprising a field for the email address, a field for the password, a box to check, and two submit buttons:
the first button ("log_in") is for trying to log in with the current combination email/password. This button triggers a script ("check_box()") which verifies that the box has been checked.
the second button is for generating a new password for the current email address. It also triggers a script ("confirmation()") which asks the user to confirm before executing the action.
I am trying to submit the form with javascript, and to keep track of which button has been submitted in order to execute the correct action. Please see the code below.
<form id="form" name="form" method="post" action="index.php">
<input type="text" name="email" id="email" placeholder="Email address" />
<input type="password" name="password" id="password" placeholder="Password" />
<input type="radio" id="box" name="box"><label for="box">Please check this box if you want to log in.</label>
<input type="button" id="log_in" name="log_in" value="Log in" onclick="return check_box();"/>
<input type="button" id="change_password" name="change_password" value="Password forgotten?" onclick="return confirmation();"/>
</form>
function confirmation(){
if (!confirm("A new password will be generated and sent to your email address. Please make sure that your email address is written correctly, and click on Confirm to proceed.")) {
return FALSE;
}
else{
var form = document.getElementById('form');
form.submit();
}
}
function check_box(){
var success = document.querySelector("input[name=box]:checked");
if(!success){
alert("Please check the box.");
}
else{
var form = document.getElementById('form');
form.submit();
}
}
My problem is to retrieve the values of the buttons when the form is submitted. I tried
if(isset($_POST['log_in']))
to detect whether the user has been trying to log in, and
if(isset($_POST['change_password']))
to detect whether the user wants to change password. But these tests always return FALSE. Where is the mistake?
Thank you in advance.

setting variable from input field

I have a form that contains an input field for an email address. The form doesn't have a submit button. Instead it has the Stripe checkout.js script which provides a button that triggers a roundtrip to Stripe (to process a credit card) before submitting the form. The checkout.js script allows an optional variable data-email which makes it possible to pass a preset email address to the Stripe checkout form. I'd like to set the data-email variable with the value of the email address input field on my own form.
Here's the form and the script:
<form role="form" class="new_user" id="new_user" action="/users" method="post">
<label for="user_email">Email</label>
<input class="form-control" type="email" value="" name="user[email]" id="user_email" />
<script src="https://checkout.stripe.com/v2/checkout.js"
class="stripe-button"
data-email=document.getElementById('user_email').value
data-key="stripe_key"
data-description="Product"
data-amount="500">
</script>
</form>
I know I need to use:
data-email=document.getElementById('user_email').value
But the data-email isn't getting set. Do I need to add an onchange property to the input field? What would that look like? Do I need more than that?
If the user is entering his email on the page, you might as well just update the script as they type:
var stripe = document.getElementById("stripe");
document.getElementById("email").onkeypress = function () {
stripe.setAttribute("data-email", this.value);
}
<input id="email">
<script id="stripe"></script>
If you run the snippet and inspect the input element, then type, you'll see the data-email attribute update for the given stripe script tag. You should be able to adapt this to your form.

jQuery: how to submit a form with edited user inputed values?

So for example I have a simple HTML form:
<h3>
Login
</h3>
<div id="tabs-login">
<form method="get" action="./dev.html">
<fieldset>
<legend>
Email:
</legend>
<input type="text" class="required email" name="login" />
</fieldset>
<fieldset>
<legend>
Password:
</legend>
<input type="password" class="required" name="pass" />
</fieldset>
<input type="submit" value="Submit" />
</form>
</div>
And I use jQuery to validte it:
<script>
$(document).ready(function() { $("form").validate(); });
</script>
I want on form submition to take user inputed password value and take SHA256 from it via this jQuery plugin and submit email=user-inputed-value and pass=sha-value. How to access validated values via jQuery and change them and send to original form destination?
First -- I want to point out that I don't think this is a good idea. It's generally a bad idea to implement password hashing on the client side. Instead, the pass should be sent in plain text (over HTTPS) to the server, where it is then hashed using your preferred algorithm before storage. This has the added benefit of not advertising to potential attackers which hashing method is used, since that code exists only on the server.
That said: you're going to want to calculate that SHA value prior to form submit.
You could bind an event handler to the password field's blur event to update a hidden field's value with the new hash. Or you could add the update logic to the validation code.
Regardless of where the extra code goes, it will be much easier for you to prepare the hash prior to the form submit than it will be to send a second submission chasing after the first.
E.g.
<!-- add this to the form -->
<input type="hidden" name="sha_pass" value="" />
// add this to the document ready handler
$('[name=pass]').blur(function() {
$('[name=sha_pass]').val($.sha256($(this).val());
});

Categories

Resources