Reputation: 45
I'd like to post a login form using AJAX, then with a PHP page validate credentials, create a session and then redirect to a protect page. I have 4 files, index.php (containig the login form), index.js (containing javascript code for posting), check.php (the page that check the credentials and create the session), home.php (protected page).
index.php
<!DOCTYPE html>
<html>
<head>
<title>cieimpel</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>
<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
</body>
</html>
index.js
$(document).on('pageinit', '#login', function () {
$(document).on('click', '#submit', function () { // catch the form's submit event
if ($('#username').val().length > 0 && $('#password').val().length > 0) {
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({
url: 'check.php',
data: {
formData: $('#check-user').serialize()
},
type: 'POST',
async: 'true',
dataType: 'json',
beforeSend: function () {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function () {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if (result.status) {
if (result.login) {
$.mobile.changePage("home.php");
} else {
alert("wrong credentials " + result.username);
}
} else {
alert("errore");
}
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert("An error occurred: " + status + "nError: " + error);
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
check.php
<?php
// Prevent caching.
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 1996 00:00:00 GMT');
// The JSON standard MIME header.
header('Content-type: application/json');
// Decode JSON object into readable PHP object
$formData = json_decode($_POST['formData']);
// Get username
$username = $formData->{'username'};
// Get password
$password = md5($formData->{'password'});
if ($username == "pippoooo"){
$output = array('status' => true, 'login' => true);
echo json_encode($output);
setcookie('LOGIN', $username, time()+72000);
}else{
$output = array('status' => true, 'login' => false, 'username' => $username);
echo json_encode($output);
}
?>
home.php
<?php
if(!isset($_COOKIE['LOGIN'])){
header("Location: index.php");
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
home.php
</body>
</html>
now, if I write in check.php a line like $username = "pippoooo" everything goes well, so i suspect that formData is empty. Does anyone knows where is the mistake?
EDIT: Ok, I'm definitively sure that the problem is in:
$formData = json_decode($_POST['formData']);
I controlled the request with chrome developer's tools and the formData sent is right. The problem is in the receiving of posted data in check.php page, which is null.
Upvotes: 1
Views: 1898
Reputation: 45
JQuery Mobile POST data empty in $_POST
in this question there is the solution to my problem. I simply take off the
contentType: 'json',
from AJAX request and the header
// The JSON standard MIME header.
header('Content-type: application/json');
from check.php page. In this way $_POST array will be populated.
I made also some little changes to ajax request in index.js and in the gathering of form fields values in check.php. Working code:
index.html
<!DOCTYPE html>
<html>
<head>
<title>cieimpel</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="index.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>
<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
</body>
</html>
index.js
$(document).on('pageinit', '#login', function () {
$(document).on('click', '#submit', function () { // catch the form's submit event
if ($('#username').val().length > 0 && $('#password').val().length > 0) {
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
console.log($('#check-user').serialize());
$.ajax({
url: 'check.php',
data: $('#check-user').serialize(),
type: 'POST',
beforeSend: function () {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function () {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
console.log(result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert("An error occurred: " + status + "nError: " + error);
}
});
} else {
alert('Please fill all necessary fields');
}
event.preventDefault(); // cancel original event to prevent form submitting
});
});
check.php
<?php
// Prevent caching.
header('Cache-Control: no-cache, must-revalidate');
// Get username
$username = $_POST['username'];
// Get password
$password = md5($_POST['password']);
if ($username == "pippoooo"){
// Lets say everything is in order
$output = array('status' => true, 'login' => true);
echo json_encode($output);
setcookie('LOGIN', $username, time()+72000);
}else{
// Lets say everything is in order
$output = array('status' => true, 'login' => false, 'username' => $username);
echo json_encode($output);
}
?>
Thanks to Dragan Gaić for the assistance and original code.
Upvotes: 1