Unable to post values to a PHP page using AJAX - 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>

Related

unable to get POST data in php 'undefined index' error

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");

HTML Forms two actions

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');
}

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

AJAX form data not sending from PHP included pages

I am building a sign up form, and want to include it into a div on the main page. The main page also includes a 'log in' form.
Both forms are included on the page using php include commands in the appropriate div i.e:
<?php include_once("login.php")?>
<?php include_once("signup.php")?>
Now when I use ajax on the second form i.e. the signup.php form, it sends back information from the fields in the first form. It doesn't help that they are both email and password fields.
Does anyone know how I can isolate the information from each form so i can send the data from each form separately? Below is all the relevant code for the forms and the Javascript.
Here is the code for the first form(login.php):
<form name="loginform" id="loginform" onsubmit="return false;">
<input style="margin-bottom:5px;" id="email" type="text" class="searchbox" onblur="checkusername()" maxlength="35" value="Email">
<span id="emailstatus"></span>
<input id="password" class="searchbox" type="password" onfocus="emptyElement('status')" maxlength="88" value="Password">
<p>Log In / <a href="#" onclick="forgotpass()">Forgot Password</p>
<span id="status"></span>
</form>
and the ajax for it:
function login(){
//isolate the variables from the form
var p = _("password").value;
var e = _("email").value;
var status = _("status");
if(e != "Email" && p != "Password"){
_("loginbtn").style.display = "none";
status.innerHTML = 'please wait ...';
//start the Ajax Request
var ajax = ajaxObj("POST", "login.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "login_failed"){
status.innerHTML = 'There was a problem. Please check your email and password and try again. ';
_("loginbtn").style.display = "block";
} else {
window.location = "user.php?id="+ajax.responseText;
}
}
}
//data being sent by the ajax call
ajax.send("e="+e+"&p="+p);
} else {
status.innerHTML = "You're missing something..";
}
}
function emptyElement(x){
//The _(x) function is a shortcut for getElementById
_(x).innerHTML = "";
}
//This jQuery used to pre populate the email and password fields with "email" and "password"
$('input .seachbox').each(function(){
$(this)
.data('default', $(this).val())
.focus(function(){
if ($(this).val() == $(this).data('default')||''){
$(this).val() = ''
}
})
.blur(function(){
var default_val = $(this).data('default');
if($(this).val() == ''){
$(this).val($(this).data('default'))
}
});
});
and the second form(signup.php):
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Email Address:</div>
<input id="emails" type="text" class="searchbox" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" class="searchbox" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" class="searchbox" onfocus="emptyElement('status')" maxlength="16">
</form>
<br> Create Account<p>
<div class="statuserror"><span id="status" >This is a permanent error</span></div>
</div>
and the ajax for it:
function signup(){
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var status = _("status");
if( e == "" || p1 == "" || p2 == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else {
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "OK"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
_("p1").innerHTML = "Please check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("e="+e+"&p="+p1);
}
EDIT - SOLUTION:- Have - after 3 days found a solution so stupid i had to share it. Basically I changed the id of the status div from "status" to "status1" and found that everything is working fine now. I think that it might be because on the login page I also have a div named status so the browser is unsure which div to put it in and just does nothing. This also explains why the signup.php page works when run alone in the browser but not when the login.php is included along with it in the main page.
Moral of the story - MAKE SURE YOUR IDS ARE ALL DIFFERENT!!
Thanks to everyone for the help.

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