I'm trying to authenticate a user using AJAX wrapped with jQuery to call a PHP script that queries a MySQL database. I'm NOT familiar with any of those technologies but I (sorta) managed to get them working individually, but I can't get the jQuery, AJAX and HTML to work properly.
[Edit:] I followed Trinh Hoang Nhu's advice and added a return false; statement to disable the Submit button. All previous errors fixed, I can't get the object returned by the AJAX right.
HTML
Here's the HTML snippet I use:
<form id="form" method='post'>
<label>Username:</label>
<input id="user" name="user" type="text" maxlength="30" required /> <br />
<label>Password:</label>
<input id="pass" name="pass" type="password" maxlength="30" required /> <br />
<input id="url" name="url" type="text" value="<?php echo $_GET['url'] ?>" hidden />
<input name="submit" type="submit" value="I'm done">
</form>
jQuery/AJAX
Here's my jquery code for using AJAX to authenticate a user (sorry if the indenting is messed up because of the tabs):
function changeMessage(message) {
document.getElementById("message").innerHTML = message; }
$(document).ready(function() {
$("#form").submit(function() {
changeMessage("Checking");
//check the username exists or not from ajax
$.post("/stufftothink/php/AJAX/login.php",
{user: $("#user").val(), pass: $("#pass").val(), url: $("#url") },
function(result) {
//if failed
if (result === 'false') {
changeMessage("Invalid username or password. Check for typos and try again");
$("#pass").val(""); }
//if authenticated
else {
changeMessage("Authenticated");
window.location.href = result; }
} );
//to disable the submit button
return false;
} );
} )
PHP
And here's my PHP script that gets called:
<?php
ob_start();
session_start();
$user = $_POST['user'];
$pass = md5($_POST['pass']);
mysql_connect('localhost', 'root', '');
mysql_select_db('stufftothink');
$query = "select * from users where user = '$user' and pass = '$pass'";
$result = mysql_query($query);
$i = 0;
while ($row = mysql_fetch_array($result)) {
$i = 1; }
if ($i == 1) {
$_SESSION['user'] = $user;
$invalid_urls = array('register.php', 'login.php');
$url = $_REQUEST['url']; //not sure whether _GET or _POST
if (in_array($url, $invalid_urls)) {
echo '/stufftothink/profile.php'; }
else {
echo '/stufftothink/'.$url; }
}
else {
echo 'false'; }
mysql_close();
?>
Edit
I've been getting a lot of downvotes on this question. I had accidentally submitted the question without the explanation filled in. I went back to edit it, but when I came back, there were already 4 downvotes. It had barely been a couple of minutes. Am I doing something wrong, or were the first 5 minutes the problem?
First if you want to submit form using ajax, you must return false from your submit function. Otherwise your browser will handle it and redirect you to another page.
If you want to return an object from PHP, you must convert it to json using json_encode,
for example:
//PHP
$return = array("url" => "http://www.google.com");
echo json_encode($return);
//would echo something like {"url":"http://www.google.com"}
//JS
$.post(url, data, function(data){
alert(data.url);
});
You have no ending ;'s on functions.
Should be:
function changeMessage(message) {
document.getElementById("message").innerHTML = message;
};
$(document).ready(function() {
$("#form").submit(function() {
changeMessage("Checking");
//check the username exists or not from ajax
$.post("/stufftothink/php/AJAX/login.php",
{user: $("#user").val(), pass:$("#pass").val() },
function(result) {
//if failed
if (result === 'false') {
changeMessage("Invalid username or password. Check for typos and try again");
$("#pass").val("");
}
//if authenticated
else {
changeMessage("Authenticatred");
window.location.href = "/stufftothink/" + result;
}
});
});
});
Not sure if that'll fix it, but it's the only thing that jumps out at me.
Related
I am validating a sign In form through ajax. After successful validation the form is not redirecting to the required page.
Ajax Codes
function login_submit(){
var stat="";
$("#submit").val("Loging in...");
$.ajax({
type: "POST",
url: "php/login.php",
data: {
uname: $("#uname").val(),
pass : $("#pass").val()
},
success: function(result) {
if(result=="parent"){
window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index";
}
else if(result == "sucess_normal"){
window.location.assign("../normal_admin");
}
else if(result == "deactivated account") {
window.location.assign("reactivate_account/");
}
else if(result == "banned account") {
window.location.assign("banned_account/");
}
else{
$("#submit").val("Login");
$("#error_msg").css({color: 'red'});
document.getElementById("error_msg").innerHTML= result;
stat = false;
}
}
});
if(!stat)
return false;
}
The php code
if(isset($_POST['uname']) && isset($_POST['pass'])){
$username = encode($_POST['uname']);
$password = encrypt(encode($_POST['pass']));
// check if entered username and password is in the database
$result = mysqli_query($conn,"SELECT * From admin_account where admin_account.username = '$username' AND admin_account.password = '$password' ");
if($row = mysqli_num_rows($result) == 1){
$found = mysqli_fetch_array($result);
if($found['state'] == 1){
$account_id = $found['account_id'];
setcookie("admin_id", $account_id, time() + (86400 * 30), "/");
$_SESSION['admin_id'] = $account_id;
$result1 = mysqli_query($conn,"SELECT role_id From admin where admin_id = '$account_id'");
$found1 = mysqli_fetch_array($result1);
$_SESSION['account_type'] = $found1['role_id'];
if($found1['role_id'] == "1"){
echo "parent";
//header("Location: http://localhost:90/auction/augeo/admin/parent_admin/index");
}else{
echo "sucess_normal";
}
}
elseif($found['state'] == 2){
echo "banned account";
}
else{
$_SESSION['deactivated_id'] = $found['account_id'];
echo "deactivated account";
}
}
else{
echo "Incorrect Username or Password";
}
}
I have tried all I could do but to no avail. I want to check if result=="parent" and if result=="parent" it should redirect to window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index"; but instead it is echoing out parent.
You say "it is echoing out parent". But this should never happen with the AJAX code you supplied.
So I'm suspecting that you have a form that's running its own default submit, and that is what you're seeing.
You may want to check out this answer:
$('#idOfYourForm').submit(function() {
var $theForm = $(this);
// This is a button or field, right? NOT the form.
$("#submit").val("Logging in...");
$.post(
'php/login.php',
{
uname: $("#uname").val(),
pass : $("#pass").val()
}
).done(function(result) {
// check the result
alert("Server said: " + result);
});
// prevent submitting again
return false;
});
You get the button with
$("#submit")
This is ok, but if the button is defined as:
<input type="submit" id="submit" value="..." />
You'll get a subsequent submit of the form the button is defined in.
To avoid this, a far easier solution to the other suggested, is to not use a submit button at all. Instead, use a simple action button. These are two examples, the second of which is probably better because it is easier to design with bootstrap/HTML5/CSS...
<input type="button" id="submit" value="..." />
or better:
<button type="button" id="submit">...</button>
In case of slow server/network, you'll probably want to aid AJAX usability by disabling the button:
$("#submit").val("Logging in...").prop("disable", "disable");
This helps avoiding multiple submits when the server is slow and the user impatient.
I have a problem and a question for the code below.
The code below performs a live check if username already exists in database. Now when I enter username manually it all works fine with giving live success or error message as the case is but when after typing 1 or 2 characters I choose username from autofill options given by browser It doesn't give any success or error message instead keeps showing Enter 3 to 11 characters which is initial message for username requirements. Can't figure out why it doesn't work when username is selected from autofill options.
index.php
<script type="text/javascript">
$(document).ready(function(){
$('#un').keyup(function(){
var username = $(this).val();
var Result = $('#result');
if(username.length > 2 || username.length > 11) { // if greater than 2 (minimum 3)
Result.html('./img/loadgreen.gif');
var dataPass = 'action=availability&username='+username;
$.ajax({ // Send the username val to available.php
type : 'POST',
data : dataPass,
url : 'available.php',
success: function(responseText){ // Get the result
if(responseText == 0){
Result.html('<span class="success">Available</span>');
}
else if(responseText > 0){
Result.html('<span class="error">Unavailable</span>');
}
else{
alert('Problem with sql query');
}
}
});
}else{
Result.html('Enter 3 to 11 characters');
}
if(username.length == 0) {
Result.html('');
}
});
});
</script>
<table>
<tr>
<td>
<input type="text" name="username" id="un" placeholder="Username" class="username" />
</td>
<td class="result" id="result"></td>
</tr>
</table>
available.php
<?php
include ( "./inc/connect.php" );
if(isset($_POST['action']) && $_POST['action'] == 'availability')
{
$username = $_POST['username'];
$que=$db->prepare("SELECT username FROM users WHERE username=:username");
$que->execute(array(':username'=>$username));
$count = $que->rowCount();
echo $count;
}
?>
Now my question is how to secure POST on available.php lot of people tell you need to sanitize or escape every POST and GET data. So what works best with PDO. Also heard escaping doesn't works with PDO may be I am wrong?
try jquery .change() instead of .keyup()
So, I'm new to using PHP but want to add whatever a user enters into this form into a database.
However, I'm getting an error for each index of name, role, and wage. It seems that it isn't picking that up.
HTML:
<form id="input" name="input" action="employees.php" method="post">
<div id="boxes">
<input type="text" name="name" placeholder="Input" class="name" required><br/>
<input type="text" name="role" placeholder="Role" class="role" required><br/>
<input type="number" step="any" name="wage" placeholder="Wage" class="wage" required>
<br />
<br />
</div>
<button type="submit" onsubmit="return ajaxFunction()" class="button">Submit</button>
<button type="reset" class="button">Reset</button>
</form>
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "employees";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br/>";
$name2 = $_POST['name'];
$role2 = $_POST['role'];
$wage2 = $_POST['wage'];
if (mysql_query("INSERT INTO employees VALUES ('$name2', '$role2', '$wage2')"))
echo "Successfully inserted";
else
echo "Insertion failed";
$conn->close();
?>
I also have some javascript set up to catch the values of each field and to send them to the PHP file. I'm probably doing something very wrong... but anyway here's the JS:
function ajaxFunction() {
var name = $('.name').val();
var role = $('.role').val();
var wage = $('.wage').val();
var dataString = '&name1' + name + '&role1' + role + '&wage1' + wage;
$.post('employees.php', {name1:name, role1:role, wage1:wage}, function(data){
$('#main').html(data);
});
if (name == '' || role == '' || wage == '') {
alert("Please fill in all fields.");
} else {
$.ajax({
type: "POST",
url: "employees.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}
In your Ajax dataString is
var dataString = '&name1' + name + '&role1' + role + '&wage1' + wage;
But in your PHP
$name2 = $_POST['name'];
$role2 = $_POST['role'];
$wage2 = $_POST['wage'];
Should be
$name2 = $_POST['name1'];
$role2 = $_POST['role1'];
$wage2 = $_POST['wage1'];
The undefined error means that your data is not found, this is happening because your php is looking for a POST index of "name" whereas javascript is sending "name1".
There are a few issues with the setup that can be greatly improved here.
Firstly the onsubmit needs moved into the form tag.
<form onsubmit="return isFormValid()" id="input" name="input" action="employees.php" method="post">
Secondly you don't actually need to actually make an ajax request from Javascript because the return on submit is saying if the returned value of the js function is true submit the form otherwise don't. Therefore we just need to return a true or false based on form validation.
Here is the updated JS function.
function isFormValid(){
var name = $('.name').val(),
role = $('.role').val(),
wage = $('.wage').val(),
data = [name, role, wage],
isValid = true;
data.forEach(function(el){
if( isValid && !el.trim() ){
alert("Please fill in all fields.");
isValid = false;
}
});
return isValid;
}
There are also some security concerns regarding MySQL injection from how the form data is being entered into the database without being escaped.
A quick solution is to add a basic PHP method to escape the strings before hitting the database.
// add at the top of your php file
function escape($value){
return mysql_real_escape_string($value);
}
// then update your variables
$name2 = escape($_POST['name']);
$role2 = escape($_POST['role']);
$wage2 = escape($_POST['wage']);
You can read more about mysql injection and how to prevent it here:
http://php.net/manual/en/function.mysql-real-escape-string.php
EDIT ---------------------------
I've simplified the JS and removed the token issue you were having. If you add more input fields you can simply add a new variable to store it's value and add that variable name to the data array.
I've also updated the function name in both the JS and the html as it relates more to the purpose of the task.
Here is a working example:
http://codepen.io/davidbattersby/pen/LVabQe
obviously the php file doesn't exist so will point to a blank page if submission passes validation, it will alert and not send if invalid.
Everything works perfectly except the submit button typically takes three to four times before it works. So I'll have the necessary cid number, plug it into the form, and hit submit. It might work the first time, but it also might take me seven attempts. I've got a bit of a deadline on this thing, and I have no idea how to even go about troubleshooting this so any help at all would be hugely appreciated!
So I've got this form:
<form action="" onsubmit="redirect()">
<input type="text" name="val1" id="val1" placeholder="CID (ten digits)">
<br>
<input type="submit" value="Submit" id="submit">
</form>
Which triggers this javascript function:
function redirect() {
var userID = document.getElementById("val1").value;
var userID = userID.replace(/-/g, "");
//alert(userID);
//var userID = "9183179265";
$.ajax({
type: "POST",
url: './getNetworkType.php',
data: "userID=" + userID,
success: function(data) {
//alert(data);
if(data.indexOf("Search") > -1) {
//alert(data.substr(data.length - 10));
window.location = "http://jumpsixdashboard.com/Reporting/display_search.php?cid=" + data.substr(data.length - 10);
}
else {
//alert(data.substr(data.length - 10));
window.location = "http://jumpsixdashboard.com/Reporting/display_report.php?cid=" + data.substr(data.length - 10);
}
}
});
}
Which executes this script:
<?php
$val1 = $_POST['userID'];
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql3 = "SELECT * FROM account_type WHERE cid ='" . $val1 . "'";
$result3 = $mysqli->query($sql3);
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
echo $row3["network"];
}
}
?>
I think the problem is in your function onsubmit.
You should try something like this.
Set ID to form to example "myForm". Remove onsubmit from Form.
And add this code. This should send data successfull and avoid the submit that you don't won't.
$("#myForm").submit(function() {
redirect();
return false; // this avoid submit.
});
I am trying to convert my login page to use html and use jquery and php to fetch and process the results, Reason is if i want to go mobile with my project then i am nearly there.
The problem i have is passing variables back from php to jquery to display at the same time.
my example
index.html
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Auth Demo 2</title>
<script src="jquery/jquery-1.7.2.min.js"></script>
<script src="main.js"></script>
</head>
<body onload="handleLogin()">
<form id="loginForm">
<label for="email">Email:</label>
<input type="text" name="email" id="email" value="" placeholder="email" />
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
<input type="submit" value="Login" id="submitButton">
</form>
</body>
</html>
main.js
function handleLogin(){
var form = $("#loginForm");
var u = $("#email", form).val();
var p = $("#password", form).val();
if(u!= '' && p!= '') {
$.post("http://www.mysite.co.uk/login.php",{
email:$('#email', form).val(),
password:$('#password', form).val(),
rand:Math.random()
} ,function(data)
{
if(data=='yes') //if correct login detail
{
alert( "Request success: ");
}
else
{
//add reason in alert box here
alert ("failed reason")
}
});
} else {
alert( "Username/password empty");
}
return false;//not to post the form physically
}
login.php
<?//get the posted values
require_once("../backend/functions.php");
dbconn(true);
if ($_POST["email"] && $_POST["password"]) {
$password = passhash($_POST["password"]);
if (!empty($_POST["email"]) && !empty($_POST["password"])) {
$res = SQL_Query_exec("SELECT id, password, secret, status, enabled FROM users WHERE email = " . sqlesc($_POST["email"]) . "");
$row = mysql_fetch_assoc($res);
if ( ! $row || $row["password"] != $password )
$message = "Wrong password";
elseif ($row["status"] == "pending")
$message = "Account Pending";
elseif ($row["enabled"] == "no")
$message = "Account Suspened";
} else
$message = "No Username/password added";
if (!$message){
logincookie($row["id"], $row["password"], $row["secret"]);
if (!empty($_POST["returnto"])) {
header("Refresh: 0; url=" . $_POST["returnto"]);
die();
}
else {
echo "yes";
die();
}
}else{
echo $message;
}
}
logoutcookie();
As you can see when the login fails have various reasons i want to pass back to the alert box. Whats the best way to go about this
just alert data
if(data=='yes') //if correct login detail
{
alert( "Request success: ");
}
else{
alert (data)
}
however i recommmend to get the response as JSON.....
if(u!= '' && p!= '') {
$.post("http://www.mysite.co.uk/login.php",{
email:$('#email', form).val(),
password:$('#password', form).val(),
rand:Math.random()
} ,function(data)
{
if(data=='yes') //if correct login detail
{
alert( "Request success: ");
}
else
{ //add reason in alert box here
alert (data)
}
});
} else {
alert( "Username/password empty");
}
return false;//not to post the form physically
}
Try to use JSON;
JSON.stringify(your_object, null, 2);
Catch the POST in PHP with this to get an array back: http://www.php.net/manual/en/function.json-decode.php
$data = json_decode($_POST);
When PHP is done echo a encoded JSON string of your array data back: http://www.php.net/manual/en/function.json-encode.php
echo json_encode($return_data);
In jQuery, for testing do;
console.log(data);
console.log(data.yes);
The best way to do this is to use $.ajax() and use the "XML" type. Then have login.php return a XML file with whatever parameters you need (user id, error message if any, username, etc). You can then parse the XML file with jQuery to use those variables immediately. It's more secure to handle errors on the backend anyway.
function handleLogin(){
var form = $("#loginForm");
var u = $("#email", form).val();
var p = $("#password", form).val();
if(u!= '' && p!= '') {
jQuery.ajax({
type: "POST",
url: "http://www.mysite.co.uk/login.php",
data: 'username='+u+'&password='+p+'&rand='+Math.random(),
complete: function(data){
if(data.responseText == 'yes'){
alert( "Request success: ");
}else{
alert( "failed: ");
}
});
} else {
alert( "Username/password empty");
}
return false;//not to post the form physically
}