I'am using ajax to receive result from validating Username and password from another PHP script, in that script i'am using header("location:...."); to redirect to the admin page, but ajax catch the link and showing it in the main Login form. Any ideas :).
PHP
<?php
...
...
if ( $username && $password )
{
$data['response'] = 'valid';
else
{
$data['response'] = 'invalid';
}
echo json_encode($response);
AJAX
$.ajax({
type: 'POST',
url: 'url',
data: {username : username, password: password},
success: function(response){
if(response.response === valid){
window.location.replace('admin-page');
}else{
//error
}
}
});
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 have an error where I can't proceed my login_process.php using ajax. I have stored all my files as a one folder. If I run my HTML log in page, the error is appeared. Below is my code. It is just a simple code. Before this, I have applied the similar code as below (except for login_process.php because I've put a few functions) as my homework. But when I've try to make it again, as i said, the browser, either in Chrome or Firefox, displays an error as I wrote in ajax below.
index.html(ajax part)
$(document).ready(function(){
$("#subBTN").click(function(){
var username = $("#username").val();
var password = $("#password").val();
var status = $("#statusAlert");
if(username === "" && password === ""){
status.html("<span>Username and password are both required!</span>");
}
else if(username === ""){
status.html("<span>What is your username?</span>");
}
else if(password === ""){
status.html("<span>What is your password?</span>");
}
else{
$.ajax({
url:'login_process.php',
type: 'post',
data: {"?admin_name=": username, "&admin_pass=": password},
dataType: 'html',
success: function(data){
//alert(data);
if(data.success){
status.html("<span>"+ data +"</span>");
}
else{
status.html("<span>error</span>");
return false;
}
}
});
}
});
});
login_process.php
<?php
session_start();
if($_POST):
$username = $_POST["username"];
$password = $_POST["password"];
if($username):
echo "Hi " . $username;
endif;
endif;
?>
You got a error in jQuery ajax call in passing data
You use :
data: {'admin_name':username, 'admin_pass': password},
instead of
data: {"?admin_name=": username, "&admin_pass=": password},
Or access in php code data to use:
$_POST['admin_name'] AND S_POST['admin_pass']
You should change this line of code
if(data.success){
status.html("<span>"+ data +"</span>");
}
else{
status.html("<span>error</span>");
return false;
}
To
if(data.Length > 0){
status.html("<span>"+ data +"</span>");
}
else{
status.html("<span>error</span>");
return false;
}
I have this javascript in one of my forms.
This one is the login form
I get the URL from the form itself
I'm using API style, ("not sure if I got the concept right")
but I will attach the code down
var formup = $('#loginfrom');
formup.submit(function () {
$.ajax({
type: formup.attr('method'),
url: formup.attr('action'),
data: formup.serialize(),
success: function (data) {
alert('you have successfuly logged in');
window.location = "profile.html";
}
});
return false;
});
here is my login function called from api file
if(!mysql_fetch_array($result)){
return $res;
}
else
return $resc;
where $res returns "error", and $resc returns "correct"
and my api.php
if(!isset($function))
$resp['err'] = "Function: ".$action." does not exist";
else
$resp = $function($request);
when I enter the correct user name and password, it works fine and I'm directed to the user profile.
However, I don't know how to handle if I got the user name or password incorrect
I don't want to be directed to profile
I do think the return from php should do something to tell the javascript that the login did not work then do something else
please provide me some help regarding this problem, I will appreciate it.
The request is always a success so, you have to check the value of the data variable to redirect to an error page
...
success: function (data) {
if ( data == 'correct') {
alert('you have successfuly logged in');
window.location = "profile.html";
} else {
// handle error
}
}
...
Change your login code to this
if(!mysql_fetch_array($result)){
echo 'failure'; die;
}
else {
echo 'success'; die;
}
And change your ajax success to this
success: function (data) {
if (data == 'success') {
alert('you have successfuly logged in');
window.location = "profile.html";
} else {
alert('Login Failed');
}
}
Use datatype as json to get the return value from php. Check my suggestions in the below code.
$.ajax({
type: formup.attr('method'),
url: formup.attr('action'),
data: formup.serialize(),
dataType: 'json',
success: function (data) {
if(data.error == 0) {
alert('you have successfuly logged in');
window.location = "profile.html";
} else {
alert("error");
}
}
});
In your php file, convert $res and $resc into an array and then later use json_encode.
Like this,
if(!mysql_fetch_array($result)){
echo array('value'=>$res,'error'=>0);
}
else
echo array('value'=>$res,'error'=>1);
You can do something with the data or you can have PHP return a 401 status, if you return something with your PHP instead of a 401 status than you can have your JavaScript check the returned text:
var formup = $('#loginfrom');
formup.submit(function () {
$.ajax({
type: formup.attr('method'),
url: formup.attr('action'),
data: formup.serialize(),
success: function (data) {
console.log(data);
// check your console (press F12 in Chrome or Firefox with firebug plugin)
// do something if the data is valid.
window.location = "profile.html";
}
});
return false;
});
When the login fails in PHP and you want to return 401 (causing your javascript success function not to be called but you might need a fail/error function in JS.
header("HTTP/1.0 401 Unauthorized");
And you need to add a fail callback in your javaScript so the user knows the log in failed:
$.ajax({
...
success: function (data) {
...
},
error: function(){
//inform the user
}
});
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
I am using PHP + jQuery AJAX to log a user into my site. The PHP connects to the database and the jquery connects to the PHP file and everything works until it comes time to actually log in. When I type in my username and password, the file returns an error. I had this working about a week ago but I was doing some code cleanup and I accidentally deleted the script where it performed the log in and now I can't get it to work. Here is my PHP file:
<?php
include('.conf.php');
$user = $_POST['user'];
$pass = $_POST['pass'];
$result = mysql_query("SELECT * FROM accountController WHERE username = '$user'");while ($row = mysql_fetch_array($result)) {
if (sha1($user.$pass) == $row['pword']) {
setcookie('temp', $row['username']);
session_start();
$_SESSION['login'] = 1;
$_SESSION['uname'] = $row['username'];
echo "success";
}
}
?>
I do believe the PHP file is echoing the correct statement and yes, the passwords in the database are sha1 encrypted. Here is the jquery code:
$('.mainlogin').submit(function() {
$.ajax({
url: 'log.php',
type: 'POST',
data: {
user: username,
pass: password
},
success: function(response) {
if(response == 'success') {
window.location.reload();
} else {
$('.logerror').fadeIn(250);
}
}
});
return false;
});
Thanks for all the help!
EDIT: I am not sure what is wrong right now but it won't log me in no matter what I try. I have corrected everything you guys suggested below, but to no avail. Anything wrong in my PHP file possibly?
try this:
$('.mainlogin').submit(function() {
$.ajax({
url: 'log.php',
type: 'POST',
data: {
username: username,
password:password
},
success: function(response) {
if(response == 'success') {
window.location.reload();
} else {
$('.logerror').fadeIn(250);
}
}
});
return false;
});
or chaneg data params
data: 'username='+username+'&password='+password
AND USE &!!!!
You have a typo:
data: 'user='+username+'pass='+password,
should be:
data: 'user='+username+'&pass='+password,
or use #Olaf's alternative, which makes sure you don't make mistakes like that.
What others have said. The '&' is needed to separate your parameters.
On a somewhat related note, you might want to consider salting those passwords...