Email not storing in variable from ajax request - javascript

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>

Related

Login with POST Form, which trigger a javascript validation, and AJAX to a PHP file. Trouble storing data to PHP

Brief
I am now stuck at a part of AJAX, as I do now know how to extract the data out from the AJAX part and put into the PHP variables, so that I could access it and use it later. It also does not redirect me to another page ("Map.php").
I tried looking online for the answers, but to no avail. Can anyone with experience please help. Also, I am not sure if my method of doing is correct, please let me know where I have done wrong.
In details
I want to do a "Login.php", which will use a form to take the email and password from the user. There will be a "Login" button on the form which will trigger a javascript for the purpose of validation.
Upon validation, I will use AJAX to call another php file called "Auth.php", which will have make a connection with a MySQL database, to search for that particular user verify the user.
The "Auth.php" will then return a json data of the user's particulars, which I intend to use in "Login.php" page, and to start a session with the $_SESSION[] variable of php. I also want the page to redirect the user to another page ("Map.php") upon successful login.
Below are parts of my codes in the "Login.php" and "Auth.php".
Login.php
<form name="myForm" action="Map.php" method="post" onsubmit="return validateForm()">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="E-mail" name="email" type="email" autofocus value="<?php echo isset($_POST["email"])? $_POST["email"]: ""; ?>">
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="<?php echo isset($_POST["password"])? $_POST["password"]: ""; ?>">
</div>
<input type="submit" value="Login" class="btn btn-lg btn-success btn-block"/>
</fieldset>
</form>
<script>
function validateForm() {
//event.preventDefault();
var email = document.forms["myForm"]["email"].value;
var password = document.forms["myForm"]["password"].value;
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (email == null || email == "") {
alert("Email must be filled.");
return false;
}
if (password == null || password == "") {
alert("Password must be filled.");
return false;
}
if(re.test(email)) {
var data = {
"email": email,
"password": password
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "GET",
dataType: "json",
url: "auth.php",
data: data,
success: function(data) {
alert("You have successfully logged in!");
// TODO store user details in session
return true; // return true to form, so will proceed to "Map.php"
}
});
return false;
}
else {
alert("You have entered an invalid email address!");
return false;
}
return false;
}
</script>
Auth.php
$connection = mysqli_connect("localhost", "root", "", "bluesky");
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ") " .
"<br>Please retry your last action. Please retry your last action. " .
"<br>If problem persist, please follow strictly to the instruction manual and restart the system.");
}
$valid=true;
if (isset($_GET['email']) && isset($_GET['password'])) {
$email = addslashes($_GET['email']);
$password = addslashes($_GET['password']);
} else {
$valid = false;
$arr=array('success'=>0,'message'=>"No username or password!");
echo json_encode($arr);
}
if($valid == true){
$query = "SELECT * FROM user WHERE email='$email' and password='$password'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_assoc($result);
$arr=array('success'=>1,'type'=>$row['type'],'user_id'=>$row['id'],'email'=>$row['email'],'name'=>$row['name'],'phone'=>$row['phone'],'notification'=>$row['notification']);
echo json_encode($arr);
}else{
$arr=array('success'=>0,'message'=>"Login failed");
echo json_encode($arr);
}
}
// close the connection that was established with MySQL for the SQL Query
mysqli_close($connection);
Your ajax call should be like this:
data = $(this).serialize() + "&" + $.param(data)
$.post('auth.php', data, function(response){
console.log(response);
});
you must use post method because you are getting password and email so its not a good practice. And for validation there is many jQuery plugins.

Ajax Button to fetch data without refresh?

I would like to know how a button submit can interact with AJAX to SELECT FROM data as a MySQL query without refreshing the page . I already have a text box interacting with AJAX so that the page does not refresh when the user inputs the text and presses enter but have no idea how to make the button do it my code below shows how im getting the text box to insert data without refreshing
Here is my script for the textbox
<div id="container">
About me<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "about_me_action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
Here is the action
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
include('..\db.php');
$con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
$name = $_POST['name'];
$name= mysqli_real_escape_string($con, $name);
$q = mysqli_query($con,"SELECT * FROM tbl1 WHERE username = '".$_COOKIE[$cookie_name]."'");
while($row = mysqli_fetch_assoc($q)){
//echo $row['id'];
$id = $row['id'];
}
$result=$con ->query=("REPLACE INTO about_user (about_me,number) VALUES ('".$name."','".$id."')");
$insert = $con->query($result);
echo "About Me Updated";
}
?>
Now all I need to do is have the below example of a button do something similar but instead of INSERTING just SELECT , how can i change the above script to allow a button to handle the action please?
<form
action="action_mail_view.php" method="post">
<input type="submit" class="button" name='msubmit' value="View Mail"/>
</form>
function callServer() {
$('#mail-button').on('click', function() {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "about_me_action.php",
data: {
name: info
},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
});
}
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
$('#mail-button').trigger('click');
};
});
});
<form action="action_mail_view.php" method="post">
<input type="submit" class="button" id="mail-button" name='msubmit' value="View Mail" />
</form>
You haven't showed us how you tried to make your button work so how can we give you feedback? Basically you want a similar ajax call that calls action_mail_view.php using the GET method
Ajax
$.ajax({
method: "GET",
url: "action_mail_view.php",
data: {},
success: function(results) {
var userinfo = JSON.parse(results);
//Todo: do what you want with the user's info
}
});
On the PHP side, you should first authenticate the user (not shown here), then SELECT her info from the DB and return it
action_mail_view.php
//Todo: authenticate
//this works with your setup, but it's a bad idea to trust
//a cookie value or anything else coming from the
//browser without verification
$username= mysqli_real_escape_string($con, $_COOKIE[$cookie_name]);
//get the user's info from your DB. By using a JOIN, we can execute
//just one query instead of two.
$sql = "SELECT t2.* FROM tbl1 as t1 "
."LEFT JOIN about_user as t2 "
."ON t1.id = t2.number"
."WHERE t1.username = $username";
//Todo: execute query. see what results you get and refine
// the SELECT clause to get just what you want
if($q = mysqli_query($con,$sql)):
$userinfo = mysqli_fetch_assoc($q);
//tell the browser to expect JSON, and return result
header('Content-Type: application/json');
echo json_encode($userinfo);
else:
//Todo: error handling
endif;

Return php error from Ajax call

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.

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.

How to check if username exists without refreshing page using wordpress

I want to check a text field in form that if username exists in database or not.i want it without refreshing page and i am using Wordpress.I know it is possible through ajax but i have tried ajax in Wordpress and any ajax code didn't run on it. Kindly provide any piece of code or any helpful link. Last time i have tried this but didn't work:
<?php
if(!empty($user_name)){
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}?>
<label for="user_name" id="user_name">Username: </label>
<input type="text" name="user_name" id="user_name" required/>
<span id="user-result" ></span>
<script type="text/javascript">
jQuery("#user_name").keyup(function (e) { //user types username on inputfiled
var user_name = jQuery(this).val(); //get the string typed by user
jQuery.post('teacher_form.php', {'user_name':user_name}, function(data) {
jQuery("#user-result").html(data); //dump the data received from PHP page
});
});
</script>
use
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
to be
<?php
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}
?>
but keyup event will call the ajax each keyup .. you can use **.blur()** instead of **.keyup()**

Categories