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;"/>
Related
Completely flummoxed after going over and over this problem for hours. Have tried a large number of approaches, without success.
Intent is to send login form data to PHP and have PHP return the result of an API call.
My latest approach is to have form onSubmit in login.html call myFunction() which performs POST call to n_authorise.php for some server side processing. In future the PHP will return API secrets. For my testing I stripped back the PHP to echo back the user input extracted from the $_POST global.
No matter what combinations of form ACTION / SUBMIT or XMLHttpRequest structures I try, I can't seem to pass the $_POST from the HTML to the PHP. I repeatedly get "Undefined index" from the PHP suggesting the $_POST is not populated.
I have tried action="n_authorise.php" directly in the form (avoiding myFunction() ) but this either fails or when it does work loads the PHP file to the browser NOT just returning the result.
I am so frustrated as it has to be possible and I can see from other postings that they have had (and resolved) similar problems... I just can't crack it, so asking the experts! Thanks in advance.
My HTML in file login.html :
<html>
<head>
<script>
function myFunction() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
};
xmlhttp.open("post", "n_authorise.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
</script>
</head>
<body>
<form name="loginform" onsubmit="myFunction()" method="post">
<input type="text" name="t_username" id="t_username" placeholder="Username" required autofocus>
<input type="password" name="t_password" id="t_password" placeholder="Password" required>
<input name ="submit" type="submit" value="submit">
</form>
</body>
</html>
My minimal PHP in file n_authorise.php
<?php
$email = $_POST["t_username"];
$password = $_POST["t_password"];
echo $email . " " . $password;
?>
Expected result is for alert box to display entered email & password (this would be replaced in final version).
Note: I have tried with and without xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");. In fact, I think I've tried nearly every possible combination of code without success... yet.
This is a most simple answer:
you are not adding any parameters to your request, you could do it with native js like this:
var form = document.querySelector('form'); // <-- extend this to select your form, maybe add an id to select
var data = new FormData(form);
var req = new XMLHttpRequest();
req.send(data); // <----- this way the form data is appended
Based on the above - sharing working code with humble thanks. FYI only:
<html>
<head>
<script>
function myFunction() {
var form = document.querySelector('form.loginform'); // <-------- extended to select new class ID for form
var data = new FormData(form); // <-------- 'data' extracts form content
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
};
xmlhttp.open("post", "n_authorise.php", true);
xmlhttp.send(data); // <-------- 'data' sent to PHP!
}
</script>
</head>
<body>
<form name="loginform" class="loginform" onsubmit="myFunction()" method="post">. // <-------- new class added
<input type="text" name="t_username" id="t_username" placeholder="Username" required autofocus>
<input type="password" name="t_password" id="t_password" placeholder="Password" required>
<input name ="submit" type="submit" value="submit">
</form>
</body>
</html>
I am using plain javascript for Ajax request. when sending data by post method php throwing an error.
index.php
<html>
<header>
<script>
function submit(){
var userName = document.getElementById("username").value;
var passWord = document.getElementById("password").value;
var data = "username=" + userName + "&password=" + passWord;
//send ajax request
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
console.log(xmlHttp.responseText);
}
}
xmlHttp.open("post", "validateuser.php");
xmlHttp.send(data);
}
</script>
</header>
<body>
<label>User Name : </label>
<input type="text" name="username" id="username"/>
<label>Password : </label>
<input type="text" name="password" id="password"/>
<button onClick="submit()"> Login</button>
</body>
</html>
validateuser.php
<?php
$userName = $_POST["username"];
$password = $_POST["password"];
echo $userName . $password;
In Javascript ajax for post you need to add following line in your code:
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
You can check documentation and example W3schools and developer mozilla
And for more reliable code just add following line to your php code
if(isset($_POST['username']) && isset($_POST['password'])){
//your code
}
You need to set the headers on your xmlHttp object. Add the following line before xmlHttp.send(data); line :
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
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');
}
I want to post login email and password to a PHP page using AJAX
<form onsubmit="authenticate()">
<input type="text" placeholder="E-mail" name="email" id="email" />
<input type="password" placeholder="Password" name="password" id="password" />
<input type="submit" value="Login"/>
</form>
AJAX:
function authenticate() {
var email = document.getElementById("email").value;
var pass = document.getElementById("password").value;
var params = 'email=' + email + '&pass=' + pass;
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "http://127.0.0.1/login/login.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1)
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
if(httpc.responseText == "success") {
window.location.replace("files.html");
}
else if (httpc.responseText == "fail")
alert("Invalid details");
}
httpc.send(params);
}
}
If the select query returns a row after authentication, it echoes "success, else it echoes "fail"
I think your problem is that you're sending your params from inside the function onreadystatechange, it probably doesn't work at all right now, because the "state" will change once you send something, but your code doesn't send anything until the "state" has changed... This should fix it:
function authenticate() {
var email = document.getElementById("email").value;
var pass = document.getElementById("password").value;
var params = 'email=' + email + '&pass=' + pass;
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "http://127.0.0.1/login/login.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1)
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
if(httpc.responseText == "success") {
window.location.replace("files.html");
}
else if (httpc.responseText == "fail")
alert("Invalid details");
else
alert(httpc.responseText);
}
// Your httpc.send was here
}
httpc.send(params); // <-- should be here
}
You must also change your HTML to add a return false; after the call to the authenticate function, in order to prevent the form from doing its "default" action (submitting to itself, in "GET" mode).
<form onsubmit="authenticate(); return false;">
<input type="text" placeholder="E-mail" name="email" id="email" />
<input type="password" placeholder="Password" name="password" id="password" />
<input type="submit" value="Login"/>
</form>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Validate Zip Code</title>
<script type="text/javascript">
function IsValidZipCode(zip) {
var isValid = /20132/.test(zip);
if (isValid)
alert('Valid ZipCode');
else {
alert('yep')
}
}
</script>
</head>
<body>
<form>
<input id="txtZip" name="zip" type="text" /><br />
<input id="Button1" type="submit" value="Check My Zipcode"
onclick="IsValidZipCode(this.form.zip.value)" />
</form>
</body>
</html>
I need to use this to allow the user to go either to a page that says sorry we cannot service your area or to another page that says yes we can service your area based on wheter their zipcode is listed.
also how can i add more than one zip code in the isValid = line?
Setting window.location.href = "your url here"; answers the first part of your question.
"also how can i add more than one zip code in the isValid = line?"
If you want to stick with a regex test you can use the regex or |:
var isValid = /^(20132|20133|20200|90210|etc)$/.test(zip);
Note that I've also added ^ and $ to match the beginning and end of the entered string - the way you had it you'd also get matches if the user entered a longer string containing that code, e.g., "abc20132xyz" would match.
I'd be more inclined to do this validation server-side though.
if (isValid)
document.location.href="validzipcode.html";
else {
document.location.href="yep.html";
}
function IsValidZipCode(zip) {
var isValid = /20132/.test(zip);
if (isValid)
document.location.href="valid_zip.html";
else {
document.location.href="not_valid_zip.html";
}
}
<script type="text/javascript">
function IsValidZipCode(zip) {
var isValid = /20132/.test(zip);
if (isValid)
window.location = baseurl."/valid.php"
else {
window.location = baseurl."/invalid.php"
}
}
</script>
You can redirect it in javascript with following code , that can be put in your example instead of alert()
window.location.href = "http://stackoverflow.com";
You can try ajax for this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Validate Zip Code</title>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function IsValidZipCode(zip){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
//alert(ajaxRequest);
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//var ajaxDisplay = document.getElementById('ajaxDiv');
//ajaxDisplay.innerHTML = ajaxRequest.responseText;
alert(ajaxRequest.responseText);
if(ajaxRequest.responseText=="")
{
alert("sorry we cannot service your area");
}
else{
window.location = "Page.php?zip="+zip+"";
}
}
}
//var age = document.getElementById('age').value;
//var wpm = document.getElementById('wpm').value;
//var sex = document.getElementById('sex').value;
var queryString = "?zip=" + zip;
ajaxRequest.open("GET", "zip_check.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
</head>
<body>
<form name="form1" method="post">
<input id="txtZip" name="zip" type="text" /><br />
<input type="button" id="Button1" value="Check My Zipcode"
onclick="IsValidZipCode(document.form1.zip.value)" />
</form>
</body>
</html>