Return php error from Ajax call - javascript

I have a php script and I would like it to be called with ajax, I have had an error coming from the ajax which says "Error:email=my_email&password=myPassword".
Here is the PHP script
<?php
session_start(); //starts a session in order to be-able to save session variables and to read them
require "db_config.php"; //Allows us to use the database connection from db_config.php in this file
if ($_SERVER["request_method"] == "post"){ //checks if the form was submitted
$email = $_POST["email"]; //fetching the email address which was inserted in the login.html form
$password = $_POST["password"]; //fetching the password which was inserted in the login.html form
/*
querying the database, to check whether there is a result with the email and password entered by the user
*/
$checkForUser = mysqli_query($db_connection, "SELECT * FROM `tbl_users` WHERE email = '$email' and Password = '$password' LIMIT 1");
/*
checking if the query resulted in one row, if there is a row
it means there is a user with this email and password, which means these are the correct creadentials
*/
$rows = mysqli_num_rows($db_connection, $checkForUser);
if ($rows == 1){
//this means: correct credentials
//the next few lines fetch the information from the result
while($row = mysqli_fetch_assoc($checkForUser)){
$_SESSION["user_id"] = $row["userId"]; //creates a session variable containing the users id
$_SESSION["users_name"] = $row["firstName"]. " ".$row["lastName"]; //creates a session variable containing the users name
}
echo "You are now logged in: ". $_SESSION["users_name"];
}else{
//this means: incorrect credentials
echo "Incorrect Username or password"; //prints out error message
}
}
?>
Here is main.js
$(document).ready(function() {
$('#loginForm').submit(function() {
var data = $(this).serialize();
$.ajax({
url: "../php/login.php",
type: "POST",
data: data,
success: function(data) {
$('*').html(data);
},
error: function() {
alert('ERROR: ' + data);
}
});
return false;
});
});
Here is the login.html page which may be helpful
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/main.css">
<link rel="stylesheet" type="text/css" href="css/responsive.css">
<script src="js/jquery.js"></script>
<script src="js/main.js"></script>
<meta name="copyright" content="Yudi Moszkowski">
<title>Login | Your Site Name</title>
</head>
<body>
<div id="loginContainer">
<div class="logo"><img src="img/yourLogo.png"></div>
<form action="php/login.php" method="post" id="loginForm">
<input type="text" name="email" placeholder="Email" id="loginEmail" class="loginInput" required="true">
<input type="password" name="password" placeholder="Password" id="loginPassword" class="loginInput" required="true"/>
<input type="submit" value="Login" name="loginSubmit" id="loginSubmit">
</form>
<div id="loginOptions"><p id="noAccount">Not signed up? Signup</p><p id="forgotPass">Forgot password?</p></div>
</div>
</body>
</html>
Thanks for your time :)

it seem that you type wrong url :
in html action, u use "php/login.php" and in ajax call, u use same url with "../" before it. if you explain the location of login.php and this html file, it will be helpful to solve your problem.

Related

Email not storing in variable from ajax request

I'm attempting to use ajax to send input from an html form and try to fine the email in a MySQL database. I tested the search and it works just fine (using dummy data.) I have my PHP files running on WAMP. I checked Chrome to see if the email/password are showing and they are.
Here is my code:
HTML & Ajax
<html>
<head>
<!--initialize jquery from js folder-->
<script src ="js/jquery-3.3.1.min.js"></script>
</head>
<body>
<!--output of the json-->
<div>
<!--set the id to DOM to show output-->
<ul id="DOM">
</ul>
</div>
<form>
<label><b>Email</b></label>
<input type="text" placeholder="Enter email" id="email"
required>
<br/>
<label><b>Password</b></label>
<input type="text" placeholder="Enter password" id="passwrd"
required>
<br/>
<button type="button" id="submit">Login</button>
</form>
insert
delete
show data
login
<!--Implementation of jquery/ajax-->
<script type="text/javascript">
$('#submit').on('click',function(e){
e.preventDefault()
var data = {
email: $("#email").val(),
passwrd: $("#passwrd").val()
}
$.ajax({
url : "http://localhost/api/login.php",
type : "POST",
dataType : "json",
data : JSON.stringify(data),
//on success it will call this function
success : function(data){
alert(data.toString());
//if fail it will give this error
}, error : function(e){
alert("failed to work:" +JSON.stringify(e));
}
});
});
</script>
</body>
</html>
PHP
include "db.php";
header('Content-type: application/json');
//$con->escape_string
$email = isset($_POST['email']);
//$email = "fk5829#wayne.edu";
$result = $con->query("SELECT * FROM users WHERE email='$email'");
echo "$email";
if($result->num_rows == 0){ //if the user doesnt exist
$_SESSION['message'] = "user doesnt exist";
echo ' / user not exist / ';
}
else{ //user exists
$user = $result->fetch_assoc();
if(password_verify(isset($_POST['passwrd']), $user['passwrd'])){
//Verify the password entered
//if password correct, link information from DB to session
//variables
$_SESSION['f_name']= $user['f_name'];
$_SESSION['l_name']= $user['l_name'];
$_SESSION['email']= $user['email'];
$_SESSION['authorized']= $user['authorized'];
//Will be used to check if users session is logged
//in/allowed to do things
$_SESSION['logged_in'] = true;
//return to Success
return $_SESSION['logged_in'];
exit("Success");
}
else{
$_SESSION['message'] = "You have entered the wrong password,
please try again";
}
echo ' / user exists / ';
}
echo ' / After the check / ';
My question is this: Why is the email from the form id "email" not getting stored in $email? is it on my ajax request side? or is it in my PHP file when im trying to $_POST?
Any direction is appreciated.
I tried this function and got it to work. Maybe you can try this too.
<script type="text/javascript">
$('#submit').on('click',function(e){
e.preventDefault()
$.post('http://localhost/api/login.php', {email:$("#email").val(),passwrd:$("#passwrd").val()},
function(data){
alert(data.toString());
}).fail(function(e){
alert("failed to work:" +JSON.stringify(e));
});
});
</script>

Passing JSON string to Perl CGI

I'm trying to create a login environment that has a user input their credentials, which is then checked against a MySQL DB (with appropriate errors returned if wrong credentials) with JS (using jquery,ajax, and Perl) which, on successful login, would display a dynamic page for the user (user portal)
I can't pass the userID to the last cgi page.
below are my codes:
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>login</title>
<link rel="stylesheet" type="text/css" media="screen, projection" href="http://www.blueprintcss.org/blueprint/screen.css" />
<link rel="stylesheet" type="text/css" media="screen, projection" href="http://www.blueprintcss.org/blueprint/plugins/buttons/screen.css" />
<link rel="stylesheet" type="text/css" media="print" href="http://www.blueprintcss.org/blueprint/print.css" />
<!--[if IE]><link rel="stylesheet" type="text/css" media="screen, projection"
href="http://www.blueprintcss.org/blueprint/ie.css"><![endif]-->
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="login.js"></script>
<style type="text/css">
#loginContent { width: 350px; margin: 100px auto; }
button[type] { margin: 0.5em 0; }
#loginForm{
width:25%;
padding: 5px 5px;
margin:auto;
}
</style>
</head>
<body>
<h2>Please have pop-ups enabled for this site</h2>
<div id="loginResult" style="display:none;"></div>
<form id="loginForm" name="loginForm" method="post" action="">
<fieldset>
<legend>Enter Information</legend>
<p>
<label for="username">Username</label>
<br />
<input type="text" id="username" name="username" class="text" size="20" />
</p>
<p>
<label for="password">Password</label>
<br />
<input type="password" id="password" name="password" class="text" size="20" />
</p>
<p>
<button type="submit" class="button positive">Login</button>
</p>
</fieldset>
</form>
</body>
</html>
login.js
$(document).ready(function(){
$("form#loginForm").submit(function() { // loginForm is submitted
var username = document.getElementById("username").value; //$('#username').attr('value'); // get username
var password = document.getElementById("password").value; //$('#password').attr('value'); // get password
if (username && password) { // values are not empty
$.ajax({
type: "GET",
url: "/cgi-bin/login.pl", // URL of the Perl script
contentType: "application/json; charset=utf-8",
dataType: "json",
// send username and password as parameters to the Perl script
data: "username=" + username + "&password=" + password,
// script call was *not* successful
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#loginResult').text("responseText: " + XMLHttpRequest.responseText
+ ", textStatus: " + textStatus
+ ", errorThrown: " + errorThrown);
$('div#loginResult').addClass("error");
}, // error
// script call was successful
// data contains the JSON values returned by the Perl script
success: function(data){
if (data.error) { // script returned error
$('div#loginResult').text("data.error: " + data.error);
$('div#loginResult').addClass("error");
} // if
else { // login was successful
$('form#loginForm').hide();
$('div#loginResult').text("data.success: " + data.success
+ ", data.userid: " + data.userid);
$('div#loginResult').addClass("success");
window.open("/cgi-bin/portal.pl");
} //else
} // success
}); // ajax
} // if
else {
$('div#loginResult').text("enter username and password");
$('div#loginResult').addClass("error");
} // else
$('div#loginResult').fadeIn();
return false;
});
});
login.pl
#!C:\Strawberry\perl\bin\perl.exe
use CGI;
use DBI;
use strict;
use warnings;
# read the CGI params
my $cgi = CGI->new;
my $username = $cgi->param("username");
my $password = $cgi->param("password");
# connect to the database
my $db = 'bakery_users';
my $host = 'localhost';
my $user = 'root';
my $pass = 'P#ssw0rd';
my $dbh = DBI->connect ("DBI:mysql:database=$db:host=$host", $user, $pass) or die "Can't connect to database: $DBI::errstr\n";
# check the username and password in the database
my $statement = qq{SELECT id FROM users WHERE username=? and password=?};
my $sth = $dbh->prepare($statement)
or die $dbh->errstr;
$sth->execute($username, $password)
or die $sth->errstr;
my ($userID) = $sth->fetchrow_array;
# create a JSON string according to the database result
my $json = ($userID) ?
qq{{"success" : "login is successful", "userid" : "$userID"}} :
qq{{"error" : "username or password is wrong"}};
# return JSON string
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json;
And this is the garbage portal cgi page that needs to know the user so I can serve some specific information
#!C:\Strawberry\perl\bin\perl.exe
use CGI;
use strict;
use warnings;
my $cgi = CGI->new; #new CGI routine
print $cgi->header('text/html'); #create HTTP header
print "<html> <head>\n";
print "<title>Hello, world!</title>";
print "</head>\n";
print "<body>\n";
print "<h1>Hello, world!</h1>\n";
print "</body> </html>\n";
Most of the login files are modified from the IBM developer page on simple CGI user login page with mySQL
I was able to pass over CGI parameters with another Perl module, CGI:Session.
by adding
my $session = new CGI::Session(undef, undef) or die CGI::Session->errstr;
$session->param("username", $username);
my $cookie = $cgi->cookie(CGISESSID => $session->id);
print $cgi->header( -cookie=>$cookie );
to my login.pl file and adding the following block to my portal.cgi
my $sid = $cgi->cookie('CGISESSID') || $cgi->param('CGISESSID') || undef; #loads previous cookie
my $session = load CGI::Session(undef, $sid);
my $user = $session->param("username");
This creates a local cookie in the temp dir and is read to find the "username" variable I passed into it on the login.pl page

Login system with password preset in variable

I am new to php and I am trying to make a login system but somehow it does not work. I predefine the password in a variable and i created a function that checks if the entered password matches with the password in the variable.
This is my code so far:
<?php $validkey = "Test" ?>
<script type="text/javascript">
function check_value()
{
var password = document.getElementById("password").value;
if (password == '<?php echo $validkey; ?>')
{
location.href = "tafels.html";
}
}
</script>
<input type ="text" name="password" id="password" />
<button onclick="check_value();">Login</button>
This is not the way a login process should work.
First of all the password should be hashed and stored in the database. NEVER store passwords as clear text.
Secondly the password validation should happen server side, in a PHP file.
To explain you why it's dangerous to validate a password in the front end, just check this part of your code:
if(password=='<?php echo $validkey; ?>')
{
location.href = "tafels.html";
}
While the server processes your PHP script it will echo the valid password into the resulting HTML. That HTML will be then sent over to the browser. Let's say that the valid password is "p#$$w0rd", if you inspect the page's source code you're going to find this:
if(password=='p#$$w0rd')
{
location.href = "tafels.html";
}
The server will have replaced this:
<?php echo $validkey; ?>
with the value of the password. And that will be visible to everyone. Not safe at all.
To give you a start, here is an example, but please take care of this answer https://stackoverflow.com/a/36883388/3799829
A very simple and stateless (no memory / no session) example of login system
login.php
<?php
$password = 'Test';
$url = 'tafels.html';
if(isset($_POST['password']) && $_POST['password'] === $password)
{
header('Location: ' . $url);
exit;
}
?>
<html>
<head>
<title>You need a password to continue</title>
</head>
<body>
<form action="" method="POST">
<input type="password" name="password" placeholder="Password"><button type="submit">Go on !</button>
</form>
</body>
</html>

how to link php, sql, and Javascript together,

I'm doing a log in page, i have javascript doing validations ( checking if field is blank) sql storing the data and php doing what php does (idk).... anyway when I press submit it tells me Cannot POST /login.php
is there away to test it on a website and see if it actually works or is the code completely wrong.
<?php
$server = 'localhost';
$username = 'root';
$passowrd = 'cosc_453';
$dbname = 'login'
if(!empty($_POST['user']))
{ $query = mysql_query("SELECT * FROM UserName where userName ='$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
{ $_SESSION['userName'] = $row['pass']; echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..."; }
else { echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
if(isset($_POST['submit']))
{ SignIn();
} ?>
php external
function validate(){
if ( document.getElementById (user).value=="")
{
alert ("Please enter your user name");
}
else if ( document.getElementById(pass).value=="")
alert("Please enter you password");
else {
alert("Processing Login........");
}
}
javscript external
CREATE TABLE UserName (
UserNameID int(9) NOT NULL auto_increment,
userName VARCHAR(40) NOT NULL,
pass VARCHAR(40) NOT NULL,
PRIMARY KEY(UserNameID) );
INSERT INTO
UserName (userName, pass)
VALUES
("cosc" , "453");
sql external
<!DOCTYPE HTML>
<html>
<head>
<title>Sign-In</title>
<link rel="stylesheet" type="text/css" href="home.css">
<script src ="login.js"></script>
</head>
<body id="body-color">
<div id="Sign-In">
<fieldset style="width:30%">
<legend>LOG-IN HERE</legend>
<form method="Post" action="login.php" submit =" validate()">
User:<br><input type="text" name="user" size="40"><br>
Password:<br><input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
< /fieldset>
</div>
</body>
</html>
Your mysql do not have a connection to database. And please stop using mysql, use mysqli instead
<?php
$con = mysqli_connect("localhost","root","cosc_453","login");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM UserName WHERE userName ='".$_POST[user]."' AND pass = '".$_POST[pass]."'";
$result = mysqli_query($conn,$sql);
$count_result = mysqli_num_rows($result);
// Login Success URL
if($count_result == 1)
{
// If you validate the user you may set the user cookies/sessions here
#setcookie("logged_in", "user_id");
#$_SESSION["logged_user"] = "user_id";
$_SESSION["secret_id"] = $row['secret_id'];
if($row['level'] == 1)
{
// Set the redirect url after successful login for admin
$resp['redirect_url'] = 'admin/';
}
else if($row['level'] == 2)
{
// Set the redirect url after successful login for user
$resp['redirect_url'] = 'user/';
}
}
else
{
echo "Invalid username or pass";
}
?>
To add onto what Eh Ezani stated, you have an issue in your HTML. Your form attribute reads submit when I believe what you meant is onsubmit. Might want to try something like.
<form method="Post" action="login.php" onsubmit ="return validate()">
User:<br><input type="text" name="user" size="40"><br>
Password:<br><input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
Also, "Use MySQLi over the older MySQL functions. The "i" stands for "improved". The list of improvements can be found in the docs.
-credited to
Difference between mysqli and mysql?

Redirect to an application page Not on the same server after login

I have a HTML5 app with a log in screen. When I enter the details, it goes out to an external server, runs a php file called login.php and check the details.
If the details are correct I need it to redirect back to the HTML5 app to the page with id #home on the index.html file.
If the index.html and login.php are both sitting together on the server, a header method going to work fine. But now, the html file is resting on a mobile phone as a HTML5 app, which reaches out to the server (which is possible - I have the server url). Checks for credentials and redirects. How is it going to redirect back to my app on the phone? There is no URL for the app on the phone.
Attempted with ajax too but nothing happens.
P.S: If you plan to flag this, read through and understand the issue first. Some text match doesn't mean its the same question.
First page on the app where you enter log in details:
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="scripts.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
</head>
<body>
<div data-role="page" id="loginForm">
<form id="form1" name="form1" method="POST" action="http://www.examplewebsite.com/login.php">
<input type="text" name="user" id="user" placeholder="Username"/>
<input type="password" name="pass" id="pass" placeholder="Password" />
<input type="submit" name="submit" value="Login" />
</form>
</div>
<div data-role="page" id="home">
<h1>Logged In</h1>
</div>
</body>
</html>
Script to check Log in. This php file rests on the server side.
//DB Log in credentials
$hostName = 'localhost';
$dbUser = 'fakeuser';
$dbPass = 'fakepass';
$dbName = 'fakedb';
$userTable = "faketable";
//Connect to DB
$conn = mysql_connect($hostName, $dbUser, $dbPass) or die("not connecting");
$dbSelect = mysql_select_db($dbName) or die("no db found");
//Obtain input username and password from the client
$username = $_POST["user"];
$password = $_POST["pass"];
//Check for MySql Injections
if(ctype_alnum($username) && ctype_alnum($password)){
$query1 = mysql_query("SELECT * FROM $userTable WHERE username='$username'");
//query will return 1 if the username exists in the database
$numrows = mysql_num_rows($query1);
if($numrows == 1){
//checking if the password matches the username now
$query2 = "SELECT password FROM $userTable WHERE username='$username'";
$result2 = mysql_query($query2);
$row = mysql_fetch_array($result2, MYSQL_ASSOC);
$pass = $row['password'];
if($password == $pass){
//If successful, redirect to the #home page
//anything I can do here to redirect back to #home on my app?
}
else
echo "Password incorrect";
}
else
echo "username incorrect" . $numrows;
}
else{
echo "Not alpha Numeric Input!!";
}
Attempted Ajax portion
var isLogged = false;
/**
* Method used to log into the application
*/
$(document).on("pageinit", "#loginForm", function () {
$("#form1").on("submit", function (event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "http://www.examplewebsite.com/login.php",
data: $("#form1").serialize(),
success: function (data) {
console.log(data);
if (data.loggedIn) {
isLogged = true;
$.mobile.changePage("#home");
} else {
alert("You entered the wrong username or password. Please try again.");
}
}
});
});
});
Where is loggedIn defined? You never get into this scope if (data.loggedIn) { }, or?
Have you tried to "return" a json encoded array and actually use that data?
As I see it you are not really using the different errors the user might run into, i.e. "Password incorrect", "username incorrect" and "Not alpha Numeric Input!!".
You might want to do something like:
if (data.loggedIn) { /* Went well */ }
else if (data.passIncorrect) { /* Password incorrect */ }
else if (data.userIncorrect) { /* User incorrect */ }
else if (data.passIncorrect) { /* NaN */ }
You might be able to find more info on the subject here or here.
I don't know if this is any help what so ever and I might even be off on a tangent here.

Categories