How to Keep Session on PHP ajax phonegap APP - php

i've my check_phone.php page on server as this:
<?php
session_start(); ob_start();
require '../platform2/pages/config.php';
require '../platform2/pages/function.php';
date_default_timezone_set('Europe/London');
if(isset($_POST['login']))
{
$email=mysql_real_escape_string(htmlspecialchars(trim($_POST['email'])));
$password=mysql_real_escape_string(htmlspecialchars(trim($_POST['password'])));
$stro = "select * from user where email='$email' and pwd='$password' ";
$res = mysql_query($stro) or die(mysql_error());
$login=mysql_num_rows($res);
if($login!=0)
{
echo "success";
} else {
echo "failed";
}
}
?>
And i call it from Jquery ajax call in my phonegap application in this way:
<script>
$("#login").click(function(){
var email=$("#email").val();
var password=$("#password").val();
var dataString="email="+email+"&password="+password+"&login=j";
var url = "../sandbox/platform/check_phone.php";
if($.trim(email).length>0 & $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: url,
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#login").html('Connecting...');},
success: function(data){
data = $.trim(data);
if(data=="success")
{
localStorage.login="true";
localStorage.email=email;
window.location.href = "wow.html";
/* in a normal php-application i used to store, $_SESSION['user'] $_SESSION['login'] , but i don't know how to do it in phonegap */
}
else if(data="failed")
{
alert("Login error");
alert(data);
$("#login").html('Login');
}
}
});
} return false;
});
</script>
Now, my question is: how i can save session of a User and continue to use his Session on a further request as retriving profile,make new post etc..
I've already thought to use SetLocalStorage as Username and Password, and call it with my request in every call.
But i don't know if it make west time for my server than give me a slowly response.
Is there a way for keeping session as i do on a normal request on my server?
Thanks

Related

Cancel request to PHP page results in another PHP page delayed responding

I am developing a login page which look into LDAP and MySQL database for user authentication. The idea is to request two PHP page simultaneously, any one complete request will cancel the other one request.
Here is my code:
$scope.submitForm = function(username, password) {
var ldap = $q.defer();
var userTable = $q.defer();
$http({
timeout: userTable.promise,
method: 'POST',
url: 'crud/00loginUserTable.php',
data: {
username: username,
password: password
}
})
.then(function(response) {
if (response.data.message != "ok")
alert("Tak OK");
else {
sessionStorage.jwt = response.data.jwt;
ldap.resolve();
window.location.href = "index.php";
}
});
$http({
timeout: ldap.promise,
method: 'POST',
url: 'crud/00loginLDAP.php',
data: {
username: username,
password: password
}
})
.then(function(response) {
if (response.data.message != "ok")
alert("Tak OK");
else {
sessionStorage.jwt = response.data.jwt;
userTable.resolve();
window.location.href = "index.php";
}
});
};
This code actually works. BUT...
There is 1.3 minute delay before window.location.href = "index.php"; could be execute. As I found out, it is something to do with PHP. I tried changing window.location.href = "index.php"; to window.location.href = "index.html";. Viola! No delay. So it seems the index.php is waiting for 00loginLDAP.php to timeout before responding.
I know the problem, but I don't know the solution.
Please help.
$scope.submitForm().then(function(data){
console.log(data);
window.location.href = "index.php";
});
$scope.submitForm = function(username, password) {
var ldap = $q.defer();
var userTable = $q.defer();
$http({
timeout: userTable.promise,
method: 'POST',
url: 'crud/00loginUserTable.php',
data: {
username: username,
password: password
}
})
.then(function(response) {
if (response.data.message != "ok")
alert("Tak OK");
else {
sessionStorage.jwt = response.data.jwt;
ldap.resolve('DataTable Response');
return ldap.promise;
}
});
$http({
timeout: ldap.promise,
method: 'POST',
url: 'crud/00loginLDAP.php',
data: {
username: username,
password: password
}
})
.then(function(response) {
if (response.data.message != "ok")
alert("Tak OK");
else {
sessionStorage.jwt = response.data.jwt;
userTable.resolve('LDAP response');
return userTable.promise;
}
});
};
Use this .. passing ldap.resolve('DataTable Response'); data inside resolve() is optional. if you want to pass some message then use.
As I learnt here, merely canceling the $http request won't stop the PHP execution. The reason the other PHP page wait until the first PHP page is finish, because both using session_start();.
I quote:
Moreover if you are using PHP session, they are another tricky
situation. For example, if you are doing AJAX, and you actually send
two AJAX request to a PHP script and that PHP script has need of
session with session_start(). The first AJAX query will work normally,
however the second one will have to wait until the first call is
finish, because the first script has a locked on the session. The
first script could eventually prematurely release the session with
session_write_close();

PHP codeigniter login error using flex auth

I am using Codeigniter 3, and I am struggling to make a simple login using flex auth, but it is not working at all.. The code used is similar to the one below:
function login_via_ajax()
{
if ($this->input->is_ajax_request())
{
$this->load->model('pat_auth_model');
$this->pat_auth_model->login_via_ajax();
$this->session->set_flashdata('message', $this->flexi_auth->get_messages());
if ($this->flexi_auth->is_logged_in()) {
$this->errorData['success'] = true;
} else {
$this->errorData['success'] = false;
}
$this->errorData['message'] = (! isset($this->errorData['message'])) ? $this->session->flashdata('message') : $this->errorData['message'];
die(json_encode($this->errorData));
}
else
{
/* Load Template */
$this->template->auth_render('auth/login', $this->data);
}
}
As supposed, if the username and password are correct, the jQuery script below should have toked me to the desired page:
<script>
$(document).ready(function(){
$('form').submit(function(e) {
e.preventDefault();
var submit_url = $(this).attr('action');
var $form_inputs = $(this).find(':input');
var form_data = {};
$form_inputs.each(function() {
form_data[this.name] = $(this).val();
});
$.ajax({
url: submit_url,
type: 'POST',
data: form_data,
dataType: 'json',
success:function(data) {
if (data['success'] == true) {
window.location.href = "<?= base_url();?>admin/dashboard"
}
else {
$('#ajxError').html('<button class="close" data-close="alert"></button>'+data['message']);
$('#ajxError').show();
}
}
});
});
});
</script>
I tried even to get the session variables like this:
die(print_r($this->session->userdata())); //print all session data
It seems that the app is granting permissions to the user and then deletes all session variables and then gets me back to the login page..
Does anyone know how to deal with that?
Thank you!

$.ajax( type: “POST” POST method to php file

I'm trying to use the POST method in jQuery to send mobile to a php file called save.php. So this is the code in the html page:
<script>
function saveit(userid){
var number = userid;
number = number.replace(/[^0-9.]/g, "");
var transaction = sendNumber(number);
if(transaction === '0'){
//alert("Transaction Successfull");
console.log('Success');
}else{
console.log('Failed');
}
userid=userid;
$.ajax({
type: "POST",
url: "./ajax/save.php",
data: { userid: userid },
beforeSend: function ( ) {
}
}).done(function ( data ) {
alert("Vielen Dank, Sie wurden erfolgreich registriert");
window.history.back();
if( console && console.log ) {
console.log("Sample of data:", data);
}
});
return false;
}
</script>
My question is now, what should I write in save.php to see all the numbers?
You will need a server running, are you doing this on your own computer via xampp or similar, or do you have a hosting provider ?
<?php echo $_POST['userid']; ?>

Ajax Login Form - Callback to PHP?

I'm trying a login in a lightbox via jquery and ajax.
My goal is that after the user logs in successful, he gets redirected to a special site.
The login via jQuery.ajax works fine, but I would like that in case the user is logged in he gets redirected, in case he's not logged in he stays on the login site.
Here's my code so far:
$(".logmein").click(function() {
var username = $("input#username").val();
var password = $("input#password").val();
var dataString = 'username='+ username + '&password=' + password + '&login=Login' ;
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF']; ?>",
data: dataString,
success: function() {
window.location = "http://test.home/kundenbereich.html";
$('#login_form').html("<div id='message'>Superb</div>");
}
});
return false;
});
The ajax request is performed successfully but, can I generate a callback from php to inform js that the user is not logged in, and then not redirect him via "window.location"?
In this case he gets redirected anyway, no matter if the login in php was successful or not!
The login function is on the same page(php) and is working with username and password.
It would be great to get some help on this issue.
Sincerely.
Make your php login function return a json object for instance:
// login.php page :
[...]
if (some_auth_system_log_user_in($username, $password)) {
exit(json_encode(array('result'=>'success', 'message'=>'Logged in successfully!')));
} else {
exit(json_encode(array('result'=>'error', 'message'=>'Some error')));
}
Then the jquery code would be:
var username = $("input#username").val();
var password = $("input#password").val();
$.post('login.php', {username:username, password:password}, function(response){
if (response.result == 'success') {
// redirect
} else {
// do something with response.message here
}
}, 'json');
Using json gives you the ability to post back multiple params, or translated messages, etc, so in general is better than just echo true/false in your php file
PHP:
if (Fe_User::Login($this->getPost('username'), $this->getPost('password'))){
echo "true";
}
else{
echo "false";
}
Script :
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF']; ?>",
data: dataString,
success: function(response) {
if(response == "true"){
$('#login_form').html("<div id='message'>Superb</div>");
window.location = "http://test.home/kundenbereich.html";
}
}
});
It worked when i putted the output at the start of the php file and let it die(); after outputting the ajax value.
It didnt worked out because i use the same document for the ajax output, therefore the response was the whole Markup of the page.
Thanks for your help

JQuery POST showing as empty array in PHP script

In a JS file I am performing this function:
$(function() {
$(".button").click(function() {
//get the button's ID (which is equal to its row's report_id)
var emergency = this.id;
var button = this.attributes['name'].value;
var dataString = 'reportid=' + emergency;
alert(dataString);
if (button == "clockin") {
$.ajax({
type: "POST",
url: "/employeetimeclock.php",
data: dataString,
success: function() {
window.location = "/employeetimeclock.php";
}
});
} else if (button == "closereport") {
var r = confirm("Are you sure you want to close this report?\nThis action CANNOT be undone!");
if (r == true) {
$.ajax({
type: "POST",
url: "/closeemergencyreport.php",
data: dataString,
success: function() {
alert("Report Successfully Closed!");
window.location = "/closeemergencyreport.php";
},
error: function() {
alert("An error has occured, the report was not closed");
}
});
} else {
alert("Report was not closed.");
}
}
});
});
For the else if (to closeemergencyreport.php) the code in that php script is as follows:
<?php
require_once("models/config.php");
require_once("models/header.php");
require_once("models/dbconnect.php");
$reportid = $_POST['reportid'];
var_dump($_POST);
$sql = "UPDATE emergency_report SET report_closed = '1' WHERE report_id IN ( $reportid )";
//execute and test if succesful
$result = mysql_query($sql) or die(mysql_error());
if($result){
} else{
}
?>
I've done this same exact thing on 3 other pages and it works flawlessly however this is giving me trouble where on that php script the VAR_DUMP is saying it's returning an empty array. I've been reading and rereading the code for about an hour and a half now so I think i'm burnt out and need to have an outside view. Ive been all over the site and no one has had a solution that worked for me.
I know it's posting because fire bug is showing this on the form's page that the javascript is run on:
http://i.imgur.com/hItdVU1.png (sorry cant post images yet)

Categories