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();
Related
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
I am working on login form in Angular Js.The HTML and validation part is working fine.
The problem is when i send data using HTTP POST method to my servicecall PHP page and want to save it to DB.
I have tried all the way by setting this in JS
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
I have tried by setting enctype of form to
enctype="application/x-www-form-urlencoded"
as well.But none of them is working i am not able to get data via $_REQUEST, $_POST, $_GET any of these method.
I have also tried using PHP library function.
$postdata = file_get_contents("php://input");
But it gives some weird string which i can't handle because number of POST data could be hundreds.
So this there any other way to solve the problem.
Code for http request is
var req = {
method: 'POST',
url: 'servicecall.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
username: $scope.loginData.username,
password: $scope.loginData.password,
action : 'checkLogin'
} //First way of sending data
//Second way of sending data which is also not working
//data: "{username:"+$scope.loginData.username+",password:"+$scope.loginData.password+",action:checkLogin}"
}
$http(req).then(function(response){
console.log(response);
}, function(response){
alert("Error "+response);
});
At PHP page i do
print_r($_REQUEST);
print_r($_POST);
But it prints just blank array like array{}
Following the code that I am using for same purpose. Hope that may help you.
var app = angular.module('angularApp', []);
app.controller('loginCtrl', function ($scope, $http) {
$scope.login = function () {
var request = $http({
method: "post",
url: "login.php",
data: {
email: $scope.email,
password: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP post request or not */
request.success(function (data) {
if(data == "1"){
$scope.responseMessage = "Successfully Logged In";
}
else {
$scope.responseMessage = "Username or Password is incorrect";
}
});
}
});
I have an ajax function that should be able to log me in, the function is executing and if I firebug it, every thing seems ok.
the php event handler, is also working since i used form post method before, but would like to use ajax now, Any body see where the problem is ?
Ajax function.
$(document).ready(function() {
$('#login').click(function() {
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
url: 'core/manage_articles.php',
type: 'POST',
data: {
login:email,
email:email,
password:password,
},
success: function() {
window.location = 'profile.php';
}
});
});
});
and the eventlistner.
if(isset($_POST['login'])) /*Login -two arguments.*/
{
$email = $_POST['login_email'];
$password = $_POST['login_password'];
... all login stuff.
}
$_POST['login_email'] doesn't match your data. Should be $_POST['email']. Same with password.
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
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Kill Ajax requests using JavaScript using jQuery
Here is the simple code I am working with:
$("#friend_search").keyup(function() {
if($(this).val().length > 0) {
obtainFriendlist($(this).val());
} else {
obtainFriendlist("");
}
});
function obtainFriendlist(strseg) {
$.ajax({
type: "GET",
url: "getFriendlist.php",
data: "search="+strseg,
success: function(msg){
UIDisplayFriends(msg);
}
});
}
Essentially, if a keyup event is fired before the function obtainFriendlist returns a result (and triggers UIDisplayFriends(msg), I need to cancel the in-flight request. The issue I have been having is that they build up, and then suddenly the function UIDisplayFriends is fired repeatedly.
Thank you very much, and advice is helpful too
The return value of $.ajax is an XHR object that you can call actions on. To abort the function you would do something like:
var xhr = $.ajax(...)
...
xhr.abort()
It may be smart to add some debouncing as well to ease the load on the server. The following will only send an XHR call only after the user has stopped typing for 100ms.
var delay = 100,
handle = null;
$("#friend_search").keyup(function() {
var that = this;
clearTimeout(handle);
handle = setTimeout(function() {
if($(that).val().length > 0) {
obtainFriendlist($(that).val());
} else {
obtainFriendlist("");
}
}, delay);
});
A third thing that you should really be doing is filtering the XHR responses based on whether or not the request is still valid:
var lastXHR, lastStrseg;
function obtainFriendlist(strseg) {
// Kill the last XHR request if it still exists.
lastXHR && lastXHR.abort && lastXHR.abort();
lastStrseg = strseg;
lastXHR = $.ajax({
type: "GET",
url: "getFriendlist.php",
data: "search="+strseg,
success: function(msg){
// Only display friends if the search is the last search.
if(lastStrseg == strseg)
UIDisplayFriends(msg);
}
});
}
How about using a variable, say isLoading, that you set to true through using the beforeSend(jqXHR, settings) option for .ajax, and then using the complete setting to set the variable back to false. Then you just validate against that variable before you trigger another ajax call?
var isLoading = false;
$("#friend_search").keyup(function() {
if (!isLoading) {
if($(this).val().length > 0) {
obtainFriendlist($(this).val());
} else {
obtainFriendlist("");
}
}
});
function obtainFriendlist(strseg) {
$.ajax({
type: "GET",
url: "getFriendlist.php",
beforeSend: function () { isLoading = true; },
data: "search="+strseg,
success: function(msg){
UIDisplayFriends(msg);
},
complete: function() { isLoading = false; }
});
}