Dynamically change html after unsuccessful login - javascript

I am building a login form in a HTML page login.html. Now after submitting the form the data is send to a php server side script named login.php. My problem is that if for some error say if the username is already present in the database table I want the user to stay in the same page with a red colored warning. Or if I want to add the popular two passwords did not match error message. How can I achieve this. As the data is stored in a mysql database I cannot access it using any client side script. But in my approach the php script moves the user to another page. And there is no way to dynamically make some error messages visible. I tried to make seperate html pages for this purpose, but I think it is not a very good solution. Can anyone provide me a sample code for this purpose? Thanks in advance.

You can either change messages with a switch statement in login.php (login.php would display the error message), or you can send the user back to login.html with an error code appended to url that can be retrieved (that is what I would do).
Using Switch in login.php
You would enter your predefined error code into an error function, there are multiple ways to do this.
function display_error_message($e) {
switch ($e) {
case "error_1":
echo "Error message 1";
break;
case "error_2":
echo "Error message 2";
break;
//Will execute the default if the error code does not match
default:
echo "Error message 2";
}
}
Calling:
display_error_message("error_1");
Appending Error to URL of login.html (recommended)
Here we again use a function. It will redirect user back to login.html with the error, this can be used on a successful login as well with append /?status=success.
Please note that you cannot use the header() function if any content is being displayed on login.php before the function is executed.
function error_redirect($e) {
header("Location: www.example.com/login.html?error=$e");
exit();
}
Calling:
error_redirect("nouser");

Related

Strange characters when passing string from PHP to Javascript

When the user presses the submit button from different forms, action pages execute their jobs. Before the end of those action pages I have put this lines:
$_SESSION['status']="inserted";
header("Location: storage.php");
or
$_SESSION['status']="removed";
header("Location: storage.php");
or
$_SESSION['status']="updated";
header("Location: storage.php");
The purpose of those lines is to save "globally" the success of the operation and then take the user to another page (storage.php).
In the storage.php page I want to show a specific message (depending on the operation) to inform the user that everything went fine (<body onload = "statusMessage()">).
Since $_SESSION['status'] is a PHP variable and the message is displayed using Javascript I googled a way to pass variables form PHP to Javascript.
The following code is what I have done:
In storage.php I have put these lines:
<div id="data-status" style="display: none;">
<?php
echo $_SESSION['status']; // put as the div content
$_SESSION['status']=""; // clear the variable
?>
</div>
with the purpose to save into an "invisible" <div> the value of my PHP variable.
Then I use DOM to access to that value:
<script type="text/javascript" >
function statusMessage() {
var status = document.getElementById("data-status").textContent;
switch(status){
case "inserted":
alert("Data inserted into database");
break;
case "removed":
alert("Data removed from database");
break;
case "updated":
alert("Data updated");
break;
default:
alert('Status code not known!');
break;
}
}
</script>
The problem is that always the default case is executed showing "Status code not known!".
Trying to debug I wrote this code:
var status = document.getElementById("data-status").textContent;
var string = "inserted";
console.log(string);
console.log(typeof(string));
console.log(string.length);
console.log("--------------------");
console.log(status);
console.log(typeof(status));
console.log(status.length);
and that's the output:
console output
It seems that for some strange reason, special non printable characters are added to the status string. I don't know why and how to remove them.
Sorry for my long message, I hope someone can help me.
Thanks in advance!

Why does Stripe's handleCardPayment not run in my Javascript function?

I am trying to use Stripes handleCardPayment to process a charge following a payment intent. I can't get the handleCardPayment function to run inside another Javascript function.
I have tried to debug my code step by step. The Javascript function runs and will print out an alert to the window.
The Javascript variables I set at the top of the function also get set.
The handleCardPayment() function however does not seem to run?
I have attempted a try/catch to see if I can catch the error coming from the request but nothing is logged.
I am a little stumped as to where the issue is with this? although I suspect it might be something basic that I am missing on calling the stripe function correctly.
function completePayment() {
// Assign client secret from PHP session variable
var clientSecret = "<?php echo $_SESSION['c_secret'] ?>";
try {
stripe.handleCardPayment(
clientSecret, cardElement, {
source_data: {
owner: {email: "<?php echo $_SESSION['m_usr_email'] ?>"}
}
}
).then(function(result) {
if (result.error) {
alert("Error in payment");
} else {
alert("Success in payment");
}
});
}
catch(error) {
console.log(error.message);
}
}
My payment intent is created on a separate PHP page. This works correctly and a payment intent is created in stripe with an associated client secret.
How the app currently functions:
User presses 'Subscribe' button.
Ajax request runs and POSTS to a separate PHP file
PHP file creates the payment intent and saves the client secret in a PHP SESSION variable
Ajax 'Complete function()' then calls 'completePayment();'
Javascript function 'completePayment();' is located just before the closing tag at the bottom of the page.
Debugging 'completePayment()' shows that the function does execute following the Ajax 'Complete function()' call.
stripe.HandleCardPayment fails to do anything.
cardElement is a global Javascript variable set when the card element is created (this is created on initial page load).
I have debugged both PHP SESSION variables and confirm that they have both been set with the correct information prior to using them in the handleCardPayment function.
Any suggestions on what I am doing wrong here?
I had same problem. It looks like the function it does not execute becouse the console logs does not appear but after searching I saw that I missing $intent->client_secret, before that, the js console not show me anything and I had to call only the function stripe.handleCardPayment without any code extra then the cosole show me $intent->client_secret It was undefined.
I don't speak english very well I hope that It will serve somebody

HTML form with PHP - submitting and staying on same page [duplicate]

This question already has answers here:
PHP form - on submit stay on same page
(11 answers)
Closed 5 years ago.
I have a form on a website (www.mywebsite.com). I have a PHP script that sends me an e-mail with information when somebody submits a form on my website. But with action="submitform.php" in the form, it updates the site to the URL www.mywebsite.com/submitform.php. I would like it to stay on the main site (index).
The solution for this: I added header("Location: http://mywebsite.com"); die(); to my PHP code. In this way, users will be redirected to the main site when they have submitted code.
However, this pose a new problem.
Whenever someone submit the form, I would like to display a message such as "Mail has been sent". To make this work, I tried to have a small JavaScript code, basically
document.getElementById("message").innerHTML = "Mail has been sent."
... and <div id="message"></div> to my HTML code. Which works...... However, due to my PHP script redirecting me to my website (with header) when someone is submitting the form, the message will only be displayed for like half a second or something.
Anyone know any workarounds for this? Thanks in advance. I can provide more detail if needed, but my problem should be clear from this. Hope anybody is able to spot my mistake...
I use javascript and ajax for most of my form post. Works wonderful.
Ajax can grab the form information in a form object or pass it as an array. URL is your php proc page, there it will come back with whatever you "print/echo" in a data object that is passed into the success function.
Use this in your HTML,
<input type="button" onclick="submitForm();" value="Submit">
Javascript,
function submitForm(){
//Validate INPUT first. Then grab the form.
form = new FormData($('#frmIdHere')[0]);
$.ajax ({
type: 'POST',
dataType: 'text',
url: url,
data: form,
success:data => {
//Success message here.
//clear form here.
},
error: () => {
// error message here.
}
});
}
php process file use,
$inputFromForm = (isset($_REQUEST["NameOfInputFromForm"])) ? strip_tags($_REQUEST["NameOfInputFromForm"]) : "-";
Without using Ajax (which means you can send the form without refreshing the page), you have two options. Either send the form to a different file, process it, and redirect back - but with a GET parameter to indicate success or failure. Alternatively, just post to the same page (so the handling of the form happens in the same page - I recommend the first alternative).
If you want to use the post-redirect-get pattern, you would use
header("Location: /?status=success");
exit;
when the form was successfully handled in your submitform.php file.
Then you just check what the message in $_GET['status'] was, and display the message accordingly in your index.php file.
if (isset($_GET['status']) && $_GET['status'] == 'success') {
echo "Your message was successfully sent!";
}
This logic can be developed further to have different parameters, to post messages for success and failure, if that's needed for the application.
assumption: you want the user to stay on the page with the form.
in that case you probably don't return false / stop event propagation in your calling code.
let's say, you call your ajax like this:
<form onsubmit="submitform(this);" ...>[form]</form>
onsubmit does the following, it executes anything that is in it's attribute value (submitform(this)) and if it returns some non-false value, it will actually do the action of the form, as if the onsubmit wouldn't have existed. I assume this is exactly what's happening in your case.
To avoid this:
<form onsubmit="submitform(this); return false">[form]</form>
the return false will stop the form from being submitted, after it was already submitted by ajax. this also has the benefit of still working, if the user has javascript disabled.
if my assumption is false however ...
if you want to refresh the page, don't even use ajax and just add a parameter to the url that triggers the message to show. or add the message to the session in php and clear it out of there after displaying.
To doing this, You can use a SESSION var to store message send type (success or failed) and test it everytime on main page, if exist, display message and unset $_SESSION var !
Like this :
MAIN
if(isset($_SESSION['message'])){
if($_SESSION['message'] == 'success'){
echo "Yeah !";
}else{
echo "Problem";
}
unset($_SESSION['message']);
}
MESSAGE
if(mail()){
$_SESSION['message']='success';
}else{
$_SESSION['message']='error';
}
You can set interval and then redirect them to desired page.
<script>
setInterval(function(){ window.location.href="http://mywebsite.com" }, 5000);
</script>

Redirect after 5 seconds but only allow the page to be accessed by the referrer

I am trying to have page1.php redirect to page2.php after 5 seconds. However page2.php needs to be a restricted page that can only be viewed if you are being sent from --> mydomain.com/page1.php and can not be accessible if you type the address manually into the address bar.
I have tried methods that use shared keys, htaccess and php HTTP_REFERRER.
I believe the issue is coming from the redirection, and I believe it is because the redirect script is not sending the HTTP_REFERRER and therefore page2.php is looking at the url sent from the redirection script as being manually entered. I have tried with a simple php redirect and javascript. Below are the two different redirect scripts I have used.
php version.
header( "refresh:5;url=page2.php" );
Javascript version.
<script type="text/javascript">
function Redirect()
{
window.location="page2.php";
}
setTimeout('Redirect()', 5000);
</script>
I have tried these with the full url and with/without http:// for example mydomain.com/page2.php.
Page2.php needs to only accept traffic from page1.php. I have no objection as to how to go about achieving this. Using shared keys or any other aspect just as long as the user can not enter the address manually and visit the page. I am also fully aware the Referrer can be spoofed however I do not have the expertise to get to advanced.
You can use session data to make sure users of page2 have passed through page 1
With the way sessions work,The encrypted string is quite secure even if it is not encrypted at all.
on page1:
session_start();
$_SESSION['secret_key'] = 'encrypted_string';
on page2:
session_start();
if($_SESSION['secret_key'] == 'encrypted_string'){
// user is authorized
echo 'You are authorized to see this page';
}
else{
echo 'Please visit page1 before accessing this page';
}
// Logic for authorized user
Or, shorter version for page2 :
if(empty($_SESSION['secret_key']) || $_SESSION['secret_key'] != 'encrypted_string'){
die('You are not authorized to view this page.');
}
echo 'only authorized user will see from here forward';
BTW, when testing, remember that once your session is set, you will have to delete sessions in browser, or use incognito to test again.
To delete cache on chrome ctrl+shift+delete and choose cookies and other
Here's how I would do it, using 3 pages.
On the landing page, include your JavaScript, this will redirect you to an intermediate page that sets a session variable before redirecting to the final page.
On the final page, check the session variable, determine whether or not to display the page, then unset the session variable (so if they try again without returning to the first page, it will no longer work).
p1.php
<?php session_start(); ?>
<script type="text/javascript">
function Redirect()
{
window.location="p12.php";
}
setTimeout('Redirect()', 5000);
</script>
p12.php
<?php session_start();
$_SESSION['secret'] = 'todays_password';
$newURL = 'p2.php';
header('Location: '.$newURL);
?>
<script type="text/javascript">
function Redirect()
{
window.location="p2.php";
}
Redirect();
</script>
p2.php
<?php session_start();
if (isset($_SESSION['secret']))
{
if ($_SESSION['secret'] == 'todays_password')
{
//The user provided the correct secret session variable
echo 'welcome. you can view this page.';
//Put all of your page content here
?>
<!-- HTML content should be in between php delimiters, like this-->
<?php
}
else
{
//The user supplied a secret code, but it was not the correct one
echo 'invalid secret.';
//You can also add code for redirecting the user back to p1 here
//Or just display an error message
}
}
else
{
//The user did not provide a secret session variable -- they most likely did not pass through p12.
echo 'error, you are unable to view this page';
//You can also add code for redirecting the user back to p1 here
//Or just display an error message
}
unset($_SESSION['secret']); //This line makes the user return to p1 every time they visit p2 -- delete this line if you only want them to visit p1 once.
?>
To make this method secure, you'd need to give each user a unique value for their secret session variable. Store this variable, along with it's timestamp when the user visits p1 both as a session variable for the client and in a server-side database. When p2 is loaded, check to see if the session value they provide is at least 5 seconds old in the database. If it is, let them see the page. Then delete the value in the database.

document.referrer gives an incorrect value

I use document.referrer to see if a user has added a new message on my application. The page where the messages are shown is called 'messages.php' and the script that handles adding messages is called 'add_message.php'.
I want to create an effect on the last added message, but only if the user has just added the message. To see if the last message was just added and wasn't there before, I need to see if the user's last visited page was 'add_message.php'.
This is the code I use to detect the last visited URL with an if statement to check if that's the case:
var prevURL = document.referrer;
var newMessageURL = 'add_message.php';
if(prevURL.indexOf(newMessageURL) > -1) {
alert(prevURL);
}
The problem is that when I add a message, the script 'add_message.php' is called (via form action), however, document.referrer returns 'messages.php' as the last visited page, but it should be 'add_message.php', because that's where I come back from when I add a new message.
How can I get document.referrer to return 'add_message.php' when I add a message?
In the 'add_message.php' I use
header('Location: ' . $_SERVER['HTTP_REFERER']);
Does this cause the issue?
Referrers are unreliable at best, especially as browsers come with the option to spoof or hide it completely. In this case, because it's a redirect, the "in-between" page doesn't get counted as the last page you visited.
That said, since you're using PHP, there's another way:
As part of your add_message.php file, add this:
// assuming you already have session_start() somewhere above
$_SESSION['just_added_a_message'] = true;
Then, where you have your JavaScript now, replace it with PHP:
<?php
if( !empty($_SESSION['just_added_a_message'])) {
?>
<script>alert("Ohai there!");</script>
<?php
unset($_SESSION['just_added_a_message']);
}
?>
I use this technique myself to show a confirmation "You sent a Personal Message to X" message when the user has been redirected back to their Inbox after sending.

Categories

Resources