Wednesday, 21 August 2013

AJax/PHP Login Form - Mysql Database [Jquery Mobile]

AJax/PHP Login Form - Mysql Database [Jquery Mobile]

I'm having an issue with AJAX/PHP form submission.
My ajax is as follows:
<script type="text/javascript">
$('#loginForm').submit(function() {
$.ajax({
type: "POST",
url: "php/server/login.php",
data: {
username: $("#username").val(),
password: $("#password").val()
},
success: function(html)
{
if(html == 'true')
{
window.location.replace('main.html');
}
else
{
$("#errorMessage").html(html);
}
},
beforeSend:function()
{
$("$errorMessage").html("Attempting to login...");
}
});
return false;
});
</script>
My form:
<form id="loginForm">
<div id="errorMessage"></div>
<div data-role="fieldcontain">
<label for="username">Username:</label>
<input class="required" id="username" type="text"
placeholder="Username" />
</div><!-- End Contained Fields -->
<div data-role="fieldcontain">
<label for="password">Password:</label>
<input class="required" id="password" type="password"
placeholder="Password" />
</div><!-- End Contained Fields -->
<div data-role="fieldcontain">
<input type="submit" id="login" value="Login" />
</div><!-- End Contained Fields -->
</form><!-- End Form -->
And then my login.php script:
<?php
session_start();
$username = $_POST['username'];
$password = md5($_POST['password']);
$db = new PDO('mysql:host=localhost;dbname=mobile;charset=utf8', 'root',
'password');
try {
$stmt = $db->query("SELECT * FROM users WHERE username='$username' and
password='$password'");
$row_count = $stmt->rowCount();
if($row_count == 1)
{
echo 'true';
$_SESSION['username'] = $username;
}
else
{
echo 'false';
}
} catch(PDOException $ex) {
echo "An error has occured!";
}
?>
I originally had programmed my whole JQuery Mobile application using just
raw php, but recently found out that I must use AJAX and Html to be able
to port it to IOS and Android using PhoneGap.
I'm rather new to using ajax and have read as many articles that I
could/topics here to try to get it to work. Unsure if I'm having a syntax
issue or just not handling it correctly.
My local machine is loading a mysql server (database name is mobile, table
I'm trying to load is users). I know that part is all correct because it
works fine with php.
Could someone explain my issue? Thank you.

No comments:

Post a Comment