HTML Forms two actions - php

So generally I have a form whose action is a link that verifies the user's username and password (can't post the link does not belong to me) and if it's correct it gives me an "ok" or else a "no"
How can I make it in a way that if yes it directs me to my index page and if no gives an error or reloads the page or something. Is their a way to do that
the general html appearance is:
<form method="post" action="https://***************/login">
<label for="book">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter username">
<label for="course">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter password">
<input type="submit" value="Log in">
</form>
so if I were to change it into the way I want it then the action should change into something like verify.php which would have the appearance of
<?php
# how do I use an if for a link using the info that was input
if($_POST["https://***************/login"]){
#load index.html
?>
<script type="text/javascript">
window.location.href = 'index.html';
</script>
<?php
else{
#load the page again
?>
<script type="text/javascript">
window.location.href = 'login.php';
</script>
<?php
}
?>
I'm a bit new to php.
So please help

There is a header to redirect, you have to put it in your php script :
header('Location: yoururl.com');
To record error from your script, you can set it in $_SESSION variables :
session_start(); // at the beginning of your script
$_SESSION['error'] = 'Password incorrect, please try again';
And so, in your other page, you can use something like :
if($_SESSION['error']) {
echo $_SESSION['error']; // display error
$_SESSION['error'] = ''; // delete it
}

Being unable to edit the login verification file, I think your best option is to submit the form via ajax and handle its response with javascript, having your form like
<form method="post" action="" onsubmit="return false;">
<label for="book">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter username">
<label for="course">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter password">
<input type="submit" value="Log in" onclick="btnAuthenticateUser();">
</form>
then, in plain javascript something like
<script type="text/javascript">
var xmlHttp;
function GetXmlHttpObject() {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function btnAuthenticateUser() {
try {
var username = document.getElementById('username');
var pwd = document.getElementById('password');
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
var url = 'https://***************/login?username=' + username.value + '&password=' + pwd.value;
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
if (xmlHttp.responseText == "ok") {
window.location = "index.html";
} else {
location.reload();
}
}
if (xmlHttp.readyState == 4) {
// LoadingPage
}
}
}
xmlHttp.open("POST", url, true);
xmlHttp.send(null);
if (xmlHttp.readyState == 1) {
//LoadingPage
}
} catch (e) {
alert(e.Message);
}
}
</script>
or if you're using jQuery
function btnAuthenticateUser() {
$.ajax({
async: true,
type: 'POST',
url: 'https://***************/login',
data: { username: $('#username').val(), password: $('#password').val()}
})
.done(function (data) {
if (data == "ok") {
window.location = "index.html";
}else{
location.reload();
}
})
.fail(function (jqxhr, textStatus, error) {
GriterError(Global.FailTryAgain);
});
}

You can perform the action you need on your verification script and then throw in a redirect using the headers in PHP.
After the verification action you can choose which page to go to through an if/then statement
for example:
if ([the action you wanted succeeded]) {
header('Location: index.php');
}
else {
header('Location: login.php');
}

Related

Can`t take value from html textarea to php variable

I made a blogging platform and I have an ajax updated page where I can select which article to display and his comments and add comments. When I leave a comment it takes the logged user info, the article on which the comment has been made but the comment value is not taken to store it in the database. This is the code :
<div align="center">
<h3>Comentarii:</h3>
<form method="POST">
<textarea rows="4" cols="50" name="comentariu" placeholder="Comenteaza">
</textarea><br>
<input type="submit" name="submit"><br>
<hr>
</form>
</div>
<?php
$comnou = $_POST['comentariu'];
$comuser = $_SESSION['user'];
$conadaugacom = mysqli_connect("localhost", "root", "", "blog");
$sqladaugacom = "insert into comentarii (continut_comentarii,
user_comentarii, articol_comentarii) values ('$comnou', '$comuser', '$ta')";
mysqli_query($conadaugacom, $sqladaugacom);
mysqli_close($conadaugacom);
?>
AJAX Code ->
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getuser.php?q=" + str, true);
xmlhttp.send();
}
}
Make sure that before POST request serialize the data from form.
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div align="center">
<h3>Comentarii:</h3>
<form method="POST">
<textarea rows="4" cols="50" name="comentariu" placeholder="Comenteaza">
</textarea><br>
<input type="submit" name="submit"><br>
<hr>
</form>
</div>
Jquery
<script>
$('input').submit(function(e){
e.preventDefault();
var data = $('form').serialize();
$.ajax({
url: 'your_url_to_post.php',
data: data,
success: function(response){
},
type: 'POST'
});
});
</script>
php file
add this line to check comentariu not empty
if(isset($_POST['comentariu'])){
$comentariu = $_POST['comentariu];
}

Form still redirect to PHP with preventDefault

EDIT:
This was related to a typo elsewhere in my Javascript. I had forgotten to check the Javascript console. Thank you for your comments.
This is my first post on this site. I have been reading it for a long while though.
I am working on a login form utilizing jQuery, AJAX, and PHP. Several times now I have run into the problem where I am redirected to the PHP page where I see the echoed data I wanted returned. I have tried to figure this out but I am stuck.
EDIT:
I did include jQuery:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
HTML:
<form name="login" id="loginForm" action="login.php" method="post">
<label for="usernameInput">Username: </label>
<input type="text" name="usernameInput" id="usernameInput" placeholder="Username" autofocus required>
<label for="passwordInput">Password: </label>
<input type="password" name="passwordInput" placeholder="Password" required>
<input type="submit" name="loginSubmit" value="Log In">
</form>
jQuery:
function login () {
$('#loginForm').on('submit', function(e){
e.preventDefault();
var formObject = $(this);
var formURL = formObject.attr("action");
$.ajax({
url: formURL,
type: "POST",
data: formObject.serialize(),
dataType: 'json',
success: function(data)
{
$("#loginDiv").remove();
if(data.new) {
$("#setupDiv").show();
} else {
statusUpdate();
/* EDIT: Changed from dummy text 'continue()' */
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#loginDiv").append(textStatus);
}
});
});
}
Call:
$(document).ready(function() {
login();
});
PHP:
// Main
if (isset($_POST['usernameInput'], $_POST['passwordInput']))
{
require "hero.php";
// Starts SQL connection
$sql = getConnected();
$userArray = validateUser($sql);
if ( $userArray['id'] > 0 ) {
sessionSet($userArray);
$userArray['user'] = (array) unserialize($userArray['user']);
$userArray = json_encode($userArray);
echo $userArray;
exit();
}
else
{
echo 'Username does not exist';
}
}
else
{
echo "Please enter a username and password.";
}
I know I have not included everything, but here's the output:
{"id":"11","name":"st5ph5n","new":true,"user":[false]}
So everything up to $userArray is working as expected. Why is this not staying on index.html and instead redirecting to login.php?
Thank you for any responses.

AJAX login form reloading the page

Trying to create a login form using AJAX so the page does not have to change to log a user in. So far I have the following after using a tutorial I found however I have the problem of the form is reloading the page instead of calling the JavaScript function.
HTML:
<form class="login-form" onSubmit="check_login();return false;">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit" class="btn trans login-button">Login</button>
</form>
PHP:
// Retrieve login values from POST variables
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
// Salt and hash password for database comparison
$password = saltHash($password);
// Check that both fields are not empty
if(!empty($email) || !empty($password)) {
// Query database to check email and password match entry
$database->query('SELECT * FROM users WHERE email = :email AND password = :password');
$database->bind(':email',$email);
$database->bind(':password',$password);
$result = $database->single();
if(!empty($result)) {
// Check entered details match the database
if($email == $result['email'] && $password == $result['password']) {
// If login details are correct, return 1
echo '1';
}
}
else {
// If not returned results, return 2
echo '2';
}
}
else {
// If either fields are empty, return 3
echo '3';
}
JavaScript / jQuery:
// Login function
function check_login() {
$.ajax({
type: 'POST',
url: 'check-login.php',
data: 'email=' + $('input[value="email"]').val() + '&password=' + $('input[value="password"]').val(),
success: function(response){
if(response === '1') {
alert('Log In Success');
}
else if(response === '2') {
alert('Incorrect Details');
}
else if(response === '3') {
alert('Fill In All Fields');
}
}
});
}
Any help is greatly appreciated.
Use This bro...
<form id="F_login" class="login-form">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button id="btn_login" type="submit" class="btn trans login-button">Login</button>
</form>
$("#btn_login").click(function(){
var parm = $("#F_login").serializeArray();
$.ajax({
type: 'POST',
url: 'check-login.php',
data: parm,
success: function (response) {
if(response === '1') {
alert('Log In Success');
}
else if(response === '2') {
alert('Incorrect Details');
}
else if(response === '3') {
alert('Fill In All Fields');
}
},
error: function (error) {
alert("Login Fail...");
}
});
});
else if(response === '3') {
alert('Fill In All Fields');
}
}
});
}
It should run well...
Try this:
<form class="login-form">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button class="btn trans login-button" onclick="check_login()">Login</button>
</form>
When the login submits, it will still try to reload the page, so you should remove the submit type and put the login function on the button
Attaching event listeners via tags is not a good practice and using jQuery for it it's cleaner and easier.
Try doing this:
$("form.login-form .login-button").click(function(e) {
e.preventDefault();
check_login();
});
Remember to remove this:
onSubmit="check_login();return false;
The statement check_login();return false will not work. You have to call return check_login(); and return false inside the function.
HTML
<form onsubmit="return check_login();">
<!-- input fields here -->
</form>
Javascript
function check_login() {
// Do your ajax call.
return false;
}
Right way is:
HTML Code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// Login function
$(function() {
$('.login-button').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'check-login.php',
data: $('form.login-form').serialize(),
success: function(response) {
if (response === '1') {
alert('Log In Success');
} else if (response === '2') {
alert('Incorrect Details');
} else if (response === '3') {
alert('Fill In All Fields');
}
}
});
});
})
</script>
<title>Ajax Login Form (Demo)</title>
</head>
<body>
<form class="login-form" name="login-form" method="POST" action="">
<input type="text" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password" />
<button type="submit" class="btn trans login-button">Login</button>
</form>
</body>
</html>
Write your ajax code inside
$(document).ready(function(){
//
}); or
$(function(){
//
});
User Prevent Default to stop Form Submission
You can use 'serialize' function to make POST pram.
Remove the button type and use the onclick handler on it, not on the form.
It will also take care of the situation when it automatically submits on pressing enter key by accident.
Happy Coding !!!
there are a lot of way to do this:
write this code in your index:
index
use "eval" function in javascript instead of "alert" to show the reasult
it means that on your PHP code when the code receive the true inputs and there is a user in your database like the input, the PHP code echo javascript orders (bellow is your PHP codes that you send an ajax request to that):>
<?php if(response==1){
echo '$("link_reload").trigger("click");';
} ?>
and in your javascript use evel() instead of alert()
Try changing the input type from "submit" to a regular button whose onclick action is to call check_login()

How to use $.ajax function properly?

I don't know how to run $.ajax properly. I usually make all xmlHTTP objects manually using javascript and then use jQuery wherever required. So please help me use this function properly in jQuery.
HTML
<form action="login.php" method="post" onSubmit="return login()" >
<input type="text" name="eMailTxt" id="eMailTxt" placeholder="Email Address" />
<input type="password" name="passWordTxt" id="passWordTxt" placeholder="password" />
<br />
<p><!--wanna show password does not match here--></p>
<input type="submit" value="Login" id="submitBtn" class="Btn" />
</form>
JQuery Ajax
function login()
{
$email = $("#eMailTxt").val();
$pass = $("#passWordTxt").val();
$.ajax({
url:'loginCheck.php',
type:'POST',
data:{q:$email,s:$pass},
success:function(response){
$("#loginForm p").innerHTML = xmlhttp.responseText;
return false; //is this the correct way to do it?
}
});
return true; //not really sure about this
}
PHP MySQL
$q=$_POST["q"];
$s=$_POST["s"];
$con=mysqli_connect("localhost","root","","SocialNetwork");
$check="SELECT PassWord FROM people WHERE EMAIL = '".$q."'";
$data=mysqli_query($con,$check);
$result=mysqli_fetch_array($data);
if ($s != $result)
{
echo "Password does not match";
}
jQuery object doesn't have a property innerHTML which is used on DOM element. Use method html() instead:
$("#loginForm p").html(response);
Or you could refer to DOM element like that:
$("#loginForm p")[0].innerHTML = response; // equivalent to .get(0)
Be aware as ajax is async by default, your login function here will always return true.
BTW, response here corresponds to the returned value from server, not the jqXHR object (xhr object wrapped inside a jquery object).
UPDATE
function login(form)
{
$email = $("#eMailTxt").val();
$pass = $("#passWordTxt").val();
$.ajax({
url:'loginCheck.php',
type:'POST',
data:{q:$email,s:$pass},
success:function(response){
if(response === "Password does not match") {
$("#loginForm p").html(response);
return false;
}
//if password match, submit form
form.submit();
}
});
//we always return false here to avoid form submiting before ajax request is done
return false;
}
In HTML:
<form action="login.php" method="post" onSubmit="return login(this)" >
HTML
<form action="login.php" method="post" class="js-my-form">
<input type="text" name="record[email]" id="eMailTxt" placeholder="Email Address" />
<input type="password" name="record[password]" id="passWordTxt" placeholder="password" />
<br />
<p><!--wanna show password does not match here--></p>
<input type="submit" value="Login" id="submitBtn" class="Btn" />
</form>
jQuery
$(document).ready(function () {
$('.js-my-form').submit(function () {
var data = $(this).serialize();
var action = $(this).attr('action');
var methodType = $(this).attr('method');
$.ajax({
url: action,
type: methodType,
data: data,
beforeSend: function () {
//Maybe Some Ajax Loader
},
success: function (response) {
// success
},
error: function (errorResponse) {}
});
return false; //Send form async
});
});
PHP
if (isset($_POST['record']) {
//Your PHP Code
} else {
header("HTTP/1.0 404 Not Found"); // Trow Error for JS
echo 'invalid data';
}
Ajax success call back contains only data (you are confused with the compete function of ajax or pure javascript xmlhttp request)
therefore
success:function(response){
$("#loginForm p").html(response);
}
Also seeing your query you are susceptible to sql injection

How can I make this AJAX/PHP work?

So I'm new to AJAX (not as new to PHP), and I'm trying to create a login using AJAX to query the PHP file. So, this is the code I'm trying to use.
I have three files. The first one is login_form.php. It contains the login form...
<html>
<head>
<title>Log In</title>
<script language="javascript" src="loginsender.js" />
</head>
<body>
<form method="post" name="loginfrm" onsubmit="formValidator()">
<p id="hint"></p>
<label for="username">Username:</label><input type="text" name="username" id="username" />
<label for="password">Password:</label><input type="password" name="password" id="password" />
<input type="submit" name="submit" value="Log In" />
</form>
</body>
</html>
The next loginsender.js. This is the JavaScript/AJAX file I'm using to send to the PHP script...
function formValidator()
{
if (document.loginfrm.username.value.length < 3 || loginfrm.password.value.length < 3)
{
msg = "Please enter a valid username/password."
document.getElementById("hint").innerHTML=msg;
}
else
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("hint").innerHTML = xmlhttp.responseText;
}
}
}
var params = "username=" + document.loginfrm.username.value + "&password=" + document.loginfrm.password.value;
xmlhttp.open("post", "login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
The last one is login.php, which is what I'm using to handle the actual logging in...
<?php
session_start();
require_once("includes/mysql.inc.php");
require_once("includes/functions.inc.php");
$username = sanitize($_POST['username'], true);
$password = sanitize($_POST['password'], true);
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_query($query);
if (mysql_num_rows($result) != 1) // no such user exists
{
echo 'Sorry, no such user exists';
logout();
die();
}
$userData = mysql_fetch_assoc($result);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password));
if ($hash == $userData['password'] && $username == $userData['username']) // successful log in
{
validateUser($userData['username']); // set session data
echo '<meta http-equiv="refresh" content="2; url=index.php" />';
}
else
{
echo 'Sorry, but you entered an incorrect username/password.';
logout();
die();
}
?>
All in all, the goal is to have the user enter their username and password combination in login_form.php and submit it, triggering loginsender.js (and the formValidator() method). This then will query the PHP login script, which will test for a valid user/pass combo, then set it up in the session (or not, if the log in failed). The issue is, no matter what combination I enter, nothing happens, the page refreshes upon clicking submit, but that's it.
**UPDATE 1:
I have edited my login_form page, I've simply put the formValidator function into the script to start with, that way its easier for me to look at rather than flipping between documents.
I also implemented some of the suggestions that were made.
Here it is:
<html>
<head>
<title>Log In</title>
<script type="text/javascript" language="javascript">
function formValidator()
{
if (document.loginfrm.username.value.length < 3 || loginfrm.password.value.length < 3)
{
msg = "Please enter a valid username/password."
document.getElementById("hint").innerHTML=msg;
}
else
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("hint").innerHTML = xmlhttp.responseText;
}
}
}
var params = "username=" + document.loginfrm.username.value + "&password=" + document.loginfrm.password.value;
xmlhttp.open("post", "login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
</script>
</head>
<body>
<p id="hint"></p>
<form method="post" name="loginfrm" onsubmit="formValidator(); return false;">
<label for="username">Username:</label><input type="text" name="username" id="username" />
<label for="password">Password:</label><input type="password" name="password" id="password" />
<input type="submit" name="submit" value="Log In" />
</form>
</body>
</html>
It doesn't look like you're preventing the default 'submit' action from happening, which since you haven't defined a action for the form is to just POST back to the current page.
Change your form html line to:
<form method="post" name="loginfrm" onsubmit="formValidator(); return false;">
The return false; tells it to NOT do whatever it was going to do for that action.
If you don't want the Form-submit-action to refresh the page, return false from your onsubmit script. Otherwise, the browser will do exactly what you tell him in the <form>: a HTTP POST.
I think the OnSubmit() function is executed and also the form is really submitted! So you get a blank page which is the output of php script.
Don't make it a html-form and it should work fine.
You need to write this to prevent form refresh..
<form method="post" name="loginfrm" onsubmit="formValidator(); return false;">
other than this, your code is fine..
try this
<input type="submit" name="submit" value="Log In" onclick="formValidator(); return false;"/>

Categories