1
I’m making a Hybrid app with Phonegap (using HTML5, CSS and JS only - jQuery and Jquery Mobile). For this, I have the application itself, which can not use PHP, and a server apart that takes care of things like login. There is also a database.
Basically, I use Ajax requests that are received by the server, returning the database values by JSON so that they are displayed on the page. The login also works in a similar way: the values typed in the inputs are sent to a PHP file on the server, which validates the user and password and gives a response to the application.
function Authenticate(username, password) {
$.ajax({
type: 'post',
dataType: 'json',
url: 'http://localhost/app/login.php',
data: { action: 'auth', username: username, password: password },
success: function(data){
if(data.result == 'true') {
$(':mobile-pagecontainer').pagecontainer('change', '#events', {
transition: 'none',
changeHash: false,
reverse: false,
showLoadMsg: true
});
}
else {
$('#login-error').show();
$('#login-error').html('Usuário ou senha incorreta.');
$('#login-password').addClass('error');
}
},
error: function() {
alert('Erro Ajax');
}
});
}
And the PHP file that receives the data:
case 'auth':
$sql = "SELECT * FROM users WHERE username = ? AND password = ?";
$username = $_POST['username'];
$password = sha1($_POST['password']);
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0) {
$res = 'true';
}
else {
$res = 'false';
}
echo json_encode(array("result" => $res));
break;
As a very basic system, the user is redirected to the #Events page (how Jquery Mobile works) if the server response is "true" when searching for an entry in the database with that user and that specific password.
Searching about sessions, I saw that they always need to be created and managed on the server side, but I couldn’t think of any way to do that in my case.
How can I create a session for the server-side user when they log in and access the session variables in the Javascript application to, for example, redirect them directly from the #login page to the #Events page, if there is already a valid session, or similarly redirect it from the #Events page to the #login page if there is no valid session and the user is not logged in?
That’s what I needed. Thank you very much!
– Felipe Umpierre