Here my php code. I need to redirect to another page when if($users[$name] === $password) or when $users[$name] = $password; but it does not work.What is wrong?Here ajax too.
$(document).ready(function() {
$('#submit').click(function() {
var name = $('#username').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: 'php/login_script.php',
data: {
user: name,
pass: password
},
success: function(a) {
alert(a);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
if(!isset($_POST['user'])||!isset($_POST['pass'])){
die();
}
$file = "users.json";
$users = json_decode(file_get_contents($file), true);
$name = $_POST['user'];
$password = $_POST['pass'];
if(isset($users[$name])) {
if($users[$name] === $password){
header("Location:chat.html");
exit;
}
else {
echo "Wrong password";
}
}
else {
$users[$name] = $password;
file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT));
header("Location:chat.html");
exit;
}
Because you're fetching the page with ajax the redirection will happen to the ajax request which means you will get back a 301 response.
This should work:
$(document).ready(function() {
$('#submit').click(function() {
var name = $('#username').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: 'php/login_script.php',
data: {
user: name,
pass: password
},
success: function(a) {
document.location = 'chat.html';
},
error: function() {
alert('Invalid password');
}
});
});
});
and
<?php
if(!isset($_POST['user'], $_POST['pass']) || empty($_POST['user']) || empty($_POST['pass'])){
// Send bad request so redirect doesn't happen
http_response_code(400);
die();
}
$file = "users.json";
$users = json_decode(file_get_contents($file), true);
$name = $_POST['user'];
$password = $_POST['pass'];
if(isset($users[$name])) {
if($users[$name] != $password){
http_response_code(400);
echo "Wrong password";
}
}
else {
$users[$name] = $password;
file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT));
}
This will return 200 on success and 400 on failure which will trigger the success and error parts of the $.ajax request.
The thing you need to realize about PHP is all of the PHP stuff is done before sending the page to the user, so calling a redirect on php/login_script.php does nothing.
What you need to do is return something to indicate success of the login.
Here's what you should do to understand my explanation:
Replace header("Location:chat.html"); with echo "success"; in your PHP code.
Change your jQuery to the following:
success: function(a)
{
if (a === "success")
{
window.location.replace("chat.html");
}
}
Related
This question already has answers here:
Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?
(13 answers)
Closed 7 years ago.
I want to do this simple log in task using php web service. I am just trying to authenticate username and password on the basis of text result I am echoing in my php.
PHP:
<?php
// Include confi.php
include_once('confi.php');
$found = false;
$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";
$password = isset($_POST['password']) ? mysql_real_escape_string($_POST['password']) : "";
if(!empty($email) && !empty($password)){
$login=mysql_num_rows(mysql_query("select *
from `login`
where `email`='$email'
and `password`='$password'"));
$result =array();
if($login!=0)
{
echo "success";
}
else
{
echo "failed";
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: text/plain');
?>
If the username and password match; it displays success.
Jquery
<script>
$(function () {
$("#logon").click(function () {
var email = $("#username").val();
var password = $("#pass").val();
var dataString = "email=" + email + "&password=" + password;
if ($.trim(email).length > 0 & $.trim(password).length > 0) {
$.ajax({
type: "POST",
url: "http://*****/login.php",
data:dataString,
crossDomain: true,
cache: false,
beforeSend: function () { $("#logon").html('Connecting...'); },
success: function (data) {
if (data == "success") {
alert(result+"You are in");
localStorage.login = "true";
localStorage.email = email;
window.location.href = "test.html";
}
else if (data == "failed") {
alert("Login error");
$("#logon").html('Login');
}
}
});
}
});
});
</script>
you are missing the json function you have to encode what ever you want to send to back to request
<?php
/*output the header here*/
header("Content-Type: application/json");
// Include confi.php
include_once('confi.php');
$response['Status'];// declare a variable to store msg
$found = false;
$email = isset($_POST['email']) ?
mysql_real_escape_string($_POST['email']) : "";
$password = isset($_POST['password']) ?
mysql_real_escape_string($_POST['password']) : "";
if(!empty($email) && !empty($password)){
$login=mysql_num_rows(mysql_query("select *
from `login`
where `email`='$email'
and `password`='$password'"));
$result =array();
if($login!=0)
{
$response['Status']=""success";
}
else
{
$response['Status']="failed";
}
}
#mysql_close($conn);
here make the change
$result= json_encode($message);
echo $result;
?>
in you jquery data to ajax function add
dataType:"json",
success: function (data) {
if (data.Status == "success") { //here check the condition
alert(result+"You are in");
localStorage.login = "true";
localStorage.email = email;
window.location.href = "test.html";
}
else if (data.Status== "failed") { //here check the condition
alert("Login error");
$("#logon").html('Login');
}
}
I've got an AJAX script that lets the user login on the login page however the script seems to stop after it runs the beforeSend.
<script>
$(document).ready(function()
{
$('#login').click(function() {
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0) {
$.ajax({
type: "POST",
url: "login.php",
data: dataString,
cache: false,
beforeSend: function(){
$("#login").val('Connecting...');
},
success: function(data){
if(data) {
$("body").load("<?php echo $dom; ?>").hide().fadeIn(1500).delay(6000);
window.location.href = "<?php echo $dom; ?>";
} else {
$('#shakeme').shake();
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
} return false;
});
});
</script>
The AJAX script sends the data to login.php
if(isset($_POST['username']) && isset($_POST['password'])) {
$username=clean($_POST['username']);
$password=clean($_POST['password']));
$sql = "SELECT password FROM user WHERE username='" . $username . "'";
$result = $conn->query($sql)->fetch_assoc();
$pass = $result['password'];
$salt = getSalt($pass);
$password = $salt . $password;
$password = $salt . hash('sha256', $password);
if(strcmp($pass,$password)==0) {
$_SESSION['login_user']=$username;
}
}
Am I doing something wrong with the PHP script? Am I meant to return data somehow? This is my first time using AJAX.
You need to return values from your login.php file as
login.php
if(strcmp($pass,$password)==0) {
$_SESSION['login_user']=$username;
echo true;
}else{
echo false;
}
exit;
and within js
success: function(data){
if (data == true) {
$("body") . load("<?php echo $dom; ?>") . hide() . fadeIn(1500) . delay(6000);
window.location.href = "<?php echo $dom; ?>";
} else {
$('#shakeme') . shake();
$("#login").val('Login')
$("#error") . html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
In my case I am sending POST request by $.post using JQuery and PHP.
But I am gettinh this error in while posting data.
POST https://xxxxxxxxxxxxx/xxxxxxxxxxx/php/control/LoginControl.php 500 (Internal Server Error)
here is my jquery code :
var url = 'php/control/LoginControl.php';
$.post(url,
{
task : "login_verify",
username:_username ,
password:_user_password,
})
.error(function(er){
console.log(er);
})
.success(
function(data){
if(data == true){
window.location = 'index.php';
}else{
$("#user_password" ).css({border:'1px solid red'});
}
}
);
PHP - LoginControl.php
<?php
try{
if(isset($_POST) && $_POST['task'] == 'login_verify'){
$user_name = $_POST['username'];
$password = md5($_POST['password']);
require '../class/login.php';
if(class_exists('Login')){
$user = Login::verifyCredentials($user_name,$password);
if($user != NULL){
if(isset($_SESSION)){
session_destroy();
}
session_start();
$_SESSION['uid'] = $user[0]->ADMIN_ID;
echo true;
}else{
echo false;
}
}
}
} catch (Exception $ex){
echo $ex;
}
?>
note: I deploy successfully this code on live test server. and it is completely working fine. But on new server I am getting this error. I am using SSL on this new server this might be issue.
Please comment if its not enough information.
Please help.
Here's an edit to your scripts. Maybe something along the lines of this will help.
JS:
$(function()
{
var url = 'php/control/LoginControl.php';
$.post(url, {
task: "login_verify",
username: _username,
password: _password
}, function(data, status, xhr)
{
// success
if(data.error===false)
window.location = 'index.php';
else
$("#user_password").css({border: '1px solid #ff0000'});
}).error(function(xhr, status, error)
{
console.log("Error loading page. Status: "+status+" | Error: "+error);
});
});
PHP:
<?php
// Session must be started before session checking and destroying can happen
session_start();
// Set error true by default
// Error is always returned.
// If no error, it'll be set to false in if statement
// So a value will always be returned.
$return['error'] = true;
if(isset($_POST) && $_POST['task'] == 'login_verify')
{
require_once __DIR__.'/../class.login.php';
if(class_exists('Login'))
{
$uname = $_POST['username'];
$passwd = $_POST['password'];
$user = Login::verifyCredentials($uname, $passwd);
if(!empty($user))
{
if(isset($_SESSION))
session_destroy();
$_SESSION['uid'] = $user[0]->ADMIN_ID;
}
else
$return['error'] = false;
}
}
echo #json_encode($return);
One thing I did notice in your PHP script that I corrected in my edits, is you're using $_SESSION and session_destroy() when no session is open. You must first define session_start() before any of the session methods or magic variables become available to you. That's why I placed it at the very top of the PHP script.
Also, if you want to use another data type rather than json, it's easiest just to use the $.ajax() function
var loginData = {
username: _username,
password: _password,
task: 'login_verify'
};
$.ajax({
url: url,
type: 'post',
data: loginData,
dataType: 'html',
success: function(data, status, xhr)
{
// If page loading was a success. i.e. 200 OK status message
},
error: function(xhr, status, error)
{
// error. Status other than 200
}
});
======================================================================
EDIT: New Code
Take a look at this, see if this will help.
PHP:
<?php
$return['error'] = true;
if(isset($_POST) && $_POST['task'] == 'login_verify')
{
if(!empty($_POST['formData']['username']))
{
if(!empty($_POST['formData']['password']))
{
$return['error'] = false;
$message = "The AJAX call was successfull! The data passed is listed below.\n\n"
. "task: " . $_POST['task'] . "\n"
. "username: " . $_POST['formData']['username'] . "\n"
. "password: " . $_POST['formData']['password'];
$return['message'] = $message;
}
else
$return['message'] = 'Password is empty!';
}
else
$return['message'] = 'Username is empty!';
}
else
{
$return['message'] = 'Invalid request! ' . $json->task;
}
echo #json_encode($return);
JavaScript:
$(function()
{
$("#login").click(function()
{
var jdata = {
task: 'login_verify',
formData: {
username: $("#username").val(),
password: $("#password").val()
}
}
$.ajax({
url: 'login.php',
type: 'post',
dataType: 'json',
data: jdata,
cache: false,
success: function(data, status, xhr)
{
var dataStatus = (data.error===true) ? "Error" : "Success";
var message = "Status: " + dataStatus + "\n"
+ data.message;
alert(message);
},
error: function(xhr, status, error)
{
alert('Error: ' + error);
}
});
return false;
});
});
This code, works. I have a live version of it. Exact code and all.
AJAX/PHP Example
I hope this helps
i want to make login form with session (with PHP + ajax), i send username from controller with json but it doesn't work. i don't know whats wrong, please help
this is the function in controller :
public function actionLogin()
{
$username = isset($_POST['username'])?$_POST['username']:null;
$password = isset($_POST['password'])?sha1($_POST['password']):null;
$json = new JsonHelper();
$result = array();
if($username && $password !=''){
$checkLogin = Administrator::model()->findByAttributes(
array('username'=>$username, 'password'=>$password));
$checkUser = Administrator::model()->findByAttributes(
array('username'=>$username));
$checkPass = Administrator::model()->findByAttributes(
array('password'=>$password));
$login = count($checkLogin);
$user = count($checkUser);
$pass= count($checkPass);
if($login==1)
{
$result['status'] = 'success';
$result['username'] = $username;
$json->addData('ajax', $result);
}
elseif($user == 1 && $pass == 0)
{
$result['status'] = 'wrongPass';
$json->addData('ajax', $result);
}
elseif($user == 0 && $pass == 1)
{
$result['status'] = 'wrongUser';
$json->addData('ajax', $result);
}
}
echo json_encode($json->getJson());
}
and this is the form_login.js file :
function login(){
var form = $('#login-form');
var formId = form.attr('id');
var action = form.attr('data-action');
var method = form.attr('data-method');
var formData = serializer(form); //don't mind this function
$.ajax(
{
url: action,
cache: false,
processData: false,
contentType: false,
type: method,
data: formData,
success: function(json)
{
// AJAX SUCCESS
var json = JSON.parse(result);
if(json['result']['ajax']['status']=='success')
{
//$_SESSION['username'] =json['username'];
window.location = baseUrl + "/appsterize/dashboard/index";
}
else if(json['result']['ajax']['status']=='wrongPass')
{
// Password wrong
alert("The password you entered is incorrect.");
}
else if(json['result']['ajax']['status']=='wrongUser')
{
// Username isn't exist
alert("Username isn't exist");
}
},
error: function(xhr, status, error)
{
// AJAX ERROR
var string = "<strong>Error!</strong> " + xhr['responseText'];
$(alertError).attr('data-text', string);
$(alertError).click();
},
});
}
some error is 'Uncaught ReferenceError: alertError is not defined'
Have an element with id = 'alertError'?
Could this be the solution:
$("#alertError").attr('data-text', string);
...
Basically, what #serakfalcon said above:
...
error: function(xhr, status, error)
{
// AJAX ERROR
var errorMsg = "<strong>Error!</strong> " + xhr['responseText'];
alert(errorMsg);
},
...
hi i am working on an authentification page , so my code is the following
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
alert(result);
}
}});
});
});
i get the form , the login and password and i pass them to my php script .
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
if($msg == 0)
{
echo"false1";
}
else if($row[1] == crypt($password,$row[1]))
{
echo"true";
}
else
{
echo"false2";
}
?>
everything is goood , when i give the good email and password i get true otherwise i get false, that's not the problem , the problem is i am trying to redirect the user to another page called espace.php if the result is true so i've tried this .
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
form.submit(true);
}
else form.submit(false);
}});
});
});
now even if the login and password are not correct the form is submitted , how could i manage to do that i mean , if the informations are correct i go to another page , otherwise i stay in the same page.
use json to get result from authanication page
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
$result = array();
if($msg == 0)
{
$result['error'] = "Fail";
}
else if($row[1] == crypt($password,$row[1]))
{
$result['success'] = "success";
}
else
{
$result['error'] = "try again";
}
echo json_encode($result); die;
?>
And in the ajax,, check what is the response.
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
var response = JSON.parse(result);
if(response.error){
//here provide a error msg to user.
alert(response.error);
}
if(response.success){
form.submit();
}
}});
});
});