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.
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>
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;
} );
} )
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();
?>
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.