I am building a simple login system. I do not want the page to reload when the user submits the form, in case there is an error, and I need to seamlessly display an error message (Like wrong password). When the users submits the data, AJAX passes it onto the submit.php script. This script validates the data and then sets a JSON object to a number 1-3 based on what is wrong or right with the submitted credentials. I don't know how to have the AJAX call, decode the JSON, and then have some if statements that decide what to do based on the value of that JSON.
Below is the code I am using for the form.
HTML:
<form method="post" id="myForm">
<h1 class="title" unselectable="on">Login</h1>
<input placeholder="Username" type="text" name="username" class="form" id="username"/>
</br>
<input placeholder="Password" type="password" name="password" class="form" id="password"/>
</br>
<input class="button" type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit"/>
</br>
</form>
JS/AJAX (Same page):
function SubmitFormData() {
var username = $("#username").val();
var password = $("#password").val();
$.post("submit.php", { username: username, password: password},
function(data) {
$('#results').html(data);
$('#myForm')[0].reset();
});
}
Next is the PHP (submit.php). The PHP will look at the incoming data from the AJAX script, and then assign an error number to a JSON object depending on what is wrong with the credentials.
$username = mysqli_real_escape_string($connect, $_POST["username"]);
$password = mysqli_real_escape_string($connect, $_POST["password"]);
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if(password_verify($password, $row["password"]))
{
$Obj->error = "three";
$myJSON = json_encode($Obj);
}
else
{
$Obj->error = "two";
$myJSON = json_encode($Obj);
}
}
}
else {
$Obj->error = "one";
$myJSON = json_encode($Obj);
}
//error one=user not found
//error two=wrong password
//error three=all detials are correct
Now, the trouble I am having is back at the main page where the user is. I want the JS to look at the $myJSON variable and decide what to do based on that. I have written some pseudo code below, but I don't know if or how I can do this in JS or AJAX.
decode JSON package
if error=one, do something
if error=two, do something else
if error=three, run a php script that sets some session variables. (Is it possible to run php inside of JS?)
Any help accomplishing these results would be greatly appreciated.
This is a vanilla javascript solution:
const xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
//passes results to a function
start(JSON.parse(this.responseText));
}
}
xmlhttp.open("POST", "PHP WEBSITE URL", true);
//sends the request with a FormData object based on the form
xmlhttp.send(new FormData(document.getElementById("myForm")));
function start(object) {
alert(object);
}
For this to work, your PHP script will have to echo your result object. Example:
if ($_POST["username"] === "correctUsername" && $_POST["password"] === "correctPassword") {
//echo javascript object
echo json_encode(['success'=>true]);
} else {
//echo javascript object
echo json_encode(['success'=>false]);
}
Obviously it needs to be more complex but this is the idea.
I have made login pages before and instead of returning a success I used the current PHP page as the main one and echoed the info to fill the page as well as credentials that can be used with AJAX requests. Hopefully this helps.
Related
I'm creating a small game where users must register or login before playing. I have a separate json file that stores already registered users.
Once a user enters their username and password into a field I make an AJAX call to retrieve the data using PHP with the intent of checking whether their details are on file. Firstly I tried sending back a JSON encoded object to parse through in Javascript. This is the code I have so far:
JSON:
{"LogIns":[
{
"Username":"mikehene",
"password":"123"
},
{
"Username":"mike",
"password":"123"
}
]
}
HTML:
<fieldset>
<legend>Please log in before playing</legend>
<form>
Username: <br>
<input type="text" placeholder="Enter a Username" id="username1" name="username"><br>
Password: <br>
<input type="password" placeholder="Enter a password" id="password" name="password"><br>
<input type="submit" value="Submit" onclick="return checkLogin();">
</form>
</fieldset>
PHP:
<?php
$username = $_POST['username'];
$str = file_get_contents('logins.json'); // Save contents of file into a variable
$json = json_decode($str, true); // decode the data and set it to recieve data asynchronosly - store in $json
echo json_encode($json);
?>
Javascript & AJAX call:
var usernamePassed = '';
function checkLogin(){
usernamePassed = document.getElementById("username1").value;
callAJAX();
return false;
}
function callAJAX(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp.responseText);
}
}
xhttp.open("POST", "LogInReg.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + usernamePassed);
}
function myFunction(response) {
var arr = response;
var objJSON = JSON.parse(arr);
var len = objJSON.length;
for(var key in objJSON){
console.log(key);
}
}
But it only prints out "LogIns". I also tried this:
for (var i = 0; i < objJSON.length; ++i) {
if(objJSON[0].Username == usernamePassed){
console.log("found it");
}
else{
console.log("didn't find it!");
}
}
Therefore I tried another approach (parse the data in the PHP file) like so:
foreach ($json['LogIns'][0] as $field => $value) {
if($json['LogIns'][0]['Username'] == $username){
echo "Logged In";
break;
}
else{
echo "No user found";
break;
}
}
But when I enter "mike" as a user name it is echoing "No user found". So I'm lost! I'm new to coding and trying to learn myself. I would love to learn how to do it both methods (i.e. PHP and Javascript).
Everything I've found online seems to push toward JQuery but I'm not quite comfortable/good enough at JQuery yet so would like to gradually work my way up to that.
I haven't even got to the register a user yet where I'm going to have to append another username and password on registration.
Any help would be GREATLY appreciated.
Thanks in advance
Try this
$json = json_decode($str, true);
$password = $_POST['password'];
foreach($json['LogIns'] as $res)
{
if($res['Username']==$username && $res['password']==$password)
{
echo json_encode($res['Username']);
//echo 'user found';
}
}
I am trying to do a basic AJAX implementation to send some form data to a php script and db. I'm just doing this for learning purposes, and have taken it as far as I could. When I hit the "Create Profile" button, nothing is happening. From my code below, does anything obvious jump out at anyone in my syntax/structure?
Note* I've yet to implement the code to retrieve the data using AJAX, will do this later once I get the send working.
EDIT*** I made some slight changes to the sendFunction(), and have seen some success. Values are now being added to my database, but they values are blank, instead of the values in the form data.
Thank you for all help/suggestions ahead of time!
HTML doc:
<!DOCTYPE HTML>
<html>
<head>
<title>Ajax Form</title>
<script language="javascript" type="text/javascript">
function sendFunction() { // Create a function to handle the Ajax
var xmlhttpCreate; // Variable to hold the xmlhttpRequest object
if (window.XMLHttPRequest) { // Checks for browser compatibilities
xmlhttpCreate = new XMLHttpRequest();
}
else {
xmlhttpCreate = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpCreate.onreadystatechange = function() {
if (xmlhttpCreate.readyState == 4) { // If server has processed request and is ready to respond
document.getElementById("createSuccess").innerHTML = xmlhttpCreate.responseText; // Display a success message that the data was sent and processed by the php script & database
}
}
var fName = document.getElementById('firstName').value; // Dump user firstName into a variable
var lName = document.getElementById('lastName').value; // Dump user lastName into a variable
var queryString = "?fName=" + fName + "&lName=" + lName; // A query string that will be sent to the php script, which will then send the values to the db
xmlhttpCreate.open("GET", "ajax_create.php" + queryString, true); // Open the request
xmlhttpCreate.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttpCreate.send(); // Send the request
}
</script>
</head>
<body>
<h3>Create Profile</h3><br>
<form name="form">
First Name: <input type="text" id ="firstName"/><br><br>
Last Name: <input type="text" id="lastName"/><br><br>
<input type="button" onclick="sendFunction()" value="Create Profile">
</form><br>
<div id="createSuccess"></div><br>
<h3>Search for Profile</h3><br>
<form name="searchForm">
First Name: <input type="text" id="searchFirstName"/><br><br>
<input type="button" onclick="sendFunction()" value="Search for Profile"/>
</form><br><br>
<div id="resultFN"></div><br>
<div id="resultLN"></div><br>
</body>
</html>
And here is my PHP script:
<?php
// Connect to the database
$con = mysqli_connect('localhost', 'root', 'intell', 'ajax_profile');
// GET variables from xmlhttpCreate
$fName = $_POST['fName'];
$lName = $_POST['lName'];
// Escape the user input to help prevent SQL injection
$fName = mysqli_real_escape_string($fName);
$lName = mysqli_real_escape_string($lName);
// Build the query
$query = "INSERT INTO users (firstName, lastName) VALUES ('$fName', '$lName')";
mysqli_query($con, $query);
mysqli_close($con);
$success = "Profile added to the database";
echo $success;
?>
you are sending data with method GET and you want to get the date in your php file with POST ... now you have two solutions . you can change the javascript code to send with GET like this :
var queryString = "fName=" + fName + "&lName=" + lName; // A query string that will be sent to the php script, which will then send the values to the db
xmlhttpCreate.open("POST", "ajax_create.php", true); // Open the request
xmlhttpCreate.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttpCreate.send(queryString);
or you can change the way you get the data on your php file like this:
$fName = $_GET['fName'];
$lName = $_GET['lName'];
don't do both things , only one, change either javascript function or php file.
I'm creating a simple form, which takes a couple of fields as input, runs some AJAX checks and submits to SQL database via PHP. I'm able to insert all other fields EXCEPT the phone number. Here's a snippet of the codes:
HTML ---
<form name="signupform" id="signupform" onSubmit="return false;">
<div>Phone Number: </div>
<input id="phon" type="text" maxlength="20">
<button id="signupbtn" onClick="signup()">Create Account</button>
<span id="status" style="color: red"></span>
</form>
JS ---
function signup() {
var status = document.getElementById("status");
var phone = document.getElementById("phon").value;
status.innerHTML = phone; //testing, doesn't display anything
var ajax = ajaxObj("POST", "index.php"); // accepted
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "Succesfully signed-up!"){ ///returned from php file
status.innerHTML = ajax.responseText;
}
}
}
ajax.send("phone="+phone); //shoots variable to php
}
PHP ---
if(isset($_POST["phone"])) {
$phone = $_POST['phone'];
echo $phone; //was testing, again, nothing shows
$sql = "INSERT INTO users(phone) VALUES('$phone')";
}
$query2 = mysqli_query($con, $sql);
echo 'successfully_updated';
NOTE: I tried to check if JS and PHP are receiving the phone number, but it's not displaying anything (other form elements such as name and email are displayed, though, tested that already). But later-on, in the PHP code, it isn't showing any error when checked against "if (isset($_POST["phone"])), it inserts the other elements of the form without trouble. No clue why that's happening, any ideas please? My guess is that since JS doesn't reflect the value, that's where the error lies.
Been searching and trying in vain since hours! Any help would be great, thanks!
using jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
phoneNum = $("#phon").val();
$("#signupbtn").click(function(){
$.ajax({url:"./index.php",data:{phone:phoneNum},success:function(result){
alert(result);
}});
});
});
</script>
status.innerHTML = phone; //testing, doesn't display anything
must be
document.getElementById("status").innerHTML = phone;
why not write $query2 = mysqli_query($con, $sql) or die(mysqli_error());
That way, you can see what the error occurs
Please try this
$sql = "INSERT INTO users(phone) VALUES('".$phone."')";
I have a file, form.php, that has a small form for searching the database for people by first and last name. The form uses a JavaScript function to send variables to search_name.php through AJAX and information queried from mydatabase as values in a form.
I want to be able to update the information on the form in the #result element with the results from the search.
I tried doing a small example that did no have the form returned through AJAX and it worked but for some reason I am not able to do it in my bigger project.
Can anyone please help. I have looked for examples and information but I'm new to AJAX and PHP and can't figure out why this is happening.
form.php
<script language="JavaScript" type="text/javascript">
function ajax_post(){
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var errorMsg ="";
if (fn==null || fn=="" ){
errorMsg +="Enter First Name \n";
document.getElementById("first_name").focus();
}
if (ln==null || ln=="" ){
errorMsg +="Enter Last Name \n";
document.getElementById("last_name").focus();
}
if(errorMsg != ""){
alert(errorMsg);
document.getElementById("first_name").focus();
return false;
}else{
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "search_name.php";
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("result").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("result").innerHTML = "processing...";
}
}
</script>
</head>
<body>
<div class="left" id="search">
First Name: <input id="first_name" name="first_name" type="text" />
<br /><br />
Last Name: <input id="last_name" name="last_name" type="text" />
<br /><br />
<input name="myBtn" type="submit" value="Search" onClick="javascript:ajax_post();return">
<br /><br />
</div>
<div id="result"></div>
search_name.php
<?php $form_profile = '<form method="POST" action=""><table width="450px"><tr><td><label for="firstname" >First Name: </label></td><td><input type="text" id="first_name" name="first_name" maxlength="50" size="30" value="'.$first_name.'"/></td></tr><tr><td><label for="lastname" >Last Name: </label></td><td><input type="text" id="last_name" name="last_name" maxlength="50" size="30" value="'.$last_name.'"/></td></tr><tr><td><label for="headline">Headline</label></td><td><input type="text" id= "headline" name="headline" maxlength="50" size="30" value="'.$profile_headline.'"/></td></tr></table><input type="submit" id="submit" name="submit" value="Save and Update"></form>'; ?>
<?php
//check if form has been submitted
if(isset($_POST['submit'])){
$first_name= $_POST['first_name'];
$last_name= $_POST['last_name'];
$headline= $_POST['headline'];
$summary= $_POST['summary'];
$title_array= $_POST['title'];
$company_array= $_POST['company'];
$start_month_array= $_POST['start_month'];
$start_year_array= $_POST['start_year'];
$end_month_array= $_POST['end_month'];
$end_year_array= $_POST['end_year'];
if($first_name && $last_name){
//connect to server
$link = mysql_connect("localhost", "root", "########");
if($link){
mysql_select_db("mydatabase",$link);
}
//check if person exists
$exists = mysql_query("SELECT * FROM profile WHERE firstname = '$first_name' AND lastname = '$last_name'") or die ("The query could not be complete.");
if(mysql_num_rows($exists) != 0){
//update
mysql_query("UPDATE profile SET headline='$headline' WHERE firstname = '$first_name' AND lastname = '$last_name'") or die("Update could not be applied");
echo "Success!!";
}else echo "That alumni is not in the database";
}else echo "You must provide a first and last name.";
}
?>
As Timmy mentioned there is no submit value being posted (that only happens automatically if the post was triggered via a form). Also, you are trying to grab $_POST['first_name'] when you're sending 'firstname' (same goes for last_name vs lastname).
It's important to use some sort of developer tool when you are working with JavaScript / AJAX. I personally use Chrome Developer Tools (Press F12 in Chrome https://developers.google.com/chrome-developer-tools/). This will show you what the request / response actually looks like so you can figure out what your issues are. Based on what your front end it doing, I quickly rewrote the PHP script you are posting to:
<?php
//check if form has been submitted
if(isset($_POST['firstname']) || isset($_POST['lastname'])){
$first_name= $_POST['firstname'];
$last_name= $_POST['lastname'];
/*
$headline= $_POST['headline'];
$summary= $_POST['summary'];
$title_array= $_POST['title'];
$company_array= $_POST['company'];
$start_month_array= $_POST['start_month'];
$start_year_array= $_POST['start_year'];
$end_month_array= $_POST['end_month'];
$end_year_array= $_POST['end_year'];
*/
//connect to server
$link = mysql_connect("localhost", "root", "########");
if($link){
mysql_select_db("mydatabase",$link);
}
//check if person exists
$exists = mysql_query("SELECT * FROM profile WHERE firstname LIKE $first_name.'%' AND lastname LIKE $last_name.'%'") or die ("The query could not be completed.");
if(mysql_num_rows($exists) != 0){
//update
//mysql_query("UPDATE profile SET headline='$headline' WHERE firstname = '$first_name' AND lastname = '$last_name'") or die("Update could not be applied");
echo "Success!!";
} else {
echo "That alumni is not in the database";
}
} else {
echo "You must provide a first and last name.";
}
?>
I fixed the bad variable names and commented out the ones that are not being sent over at the moment. I also updated your MySQL query to use the LIKE string comparison function which is much better for searching. This way if someone doesn't know the last name, or only a portion, they can still finish the lookup. More on string comparison functions here: http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html. A copy and paste of the code should solve your problems for now.
Your javascript here:-
var vars = "firstname="+fn+"&lastname="+ln;
is not including "submit" which your PHP script requires to search the database, here:-
if(isset($_POST['submit'])){
So if you just add +"&submit=true" to the end of your vars variable, it should fix the given problem.
var vars = "firstname="+fn+"&lastname="+ln+"&submit=true";
Of course, you will see a lot of Undefined index warnings as your PHP script looks for lots of other variables that aren't sent initially =)
Hope this is of some help!
I am currently making a iPhone application using Kendo UI which i am running through phone gap to test on my iPhone.
The design is all mapped out nicely and I am getting to grips with the Kendo framework. I am trying to make some functionality whereby they log into an account.
My external PHP file which runs the query and returns JSON:
<?php
$arr = array();
//Takes the username and password from the login form and queries the database to find out if they have access to the site.
//Cleanse inputs
$username = $_GET['username'];
$password = md5_base64($_GET['password']);
$stmt = $memberMysqli->prepare("SELECT id, firstname, dob, sex, recordingWeight, blocked, enabled FROM member WHERE email = ? AND password = ?");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($memberid, $firstname, $dob, $sex, $recordingWeight, $blocked, $enabled);
$stmt->store_result();
session_start();
while ($stmt->fetch())
{
$userIsBlocked = $blocked;
$enabled = $enabled;
}
if(($numRows = $stmt->num_rows) > 0) //If num rows is 1 the combination exists therefore it is a succesful login
{
if($userIsBlocked)
{
$arr['status'] = "error";
$arr['message'] = "Sorry, your account isnt active. Please contact us to re-activate it.";
}
else if(!$enabled)
{
$arr['status'] = "error";
$arr['message'] = "Sorry, your account isn't enabled. Please contact us.";
}
else
{
$_SESSION['memberid'] = $memberid;
$_SESSION['memberFirstname'] = $firstname;
$_SESSION['dob'] = $dob;
$_SESSION['sex'] = $sex;
$_SESSION['recordingWeight'] = $recordingWeight;
$arr['status'] = "success";
$arr['message'] = "Logged in";
}
}
else
{
$arr['status'] = "error";
$arr['message'] = "Sorry, Wrong Username/Password Combination";
}
header("Content-type: application/json");
echo json_encode($arr);
/* close connection */
function md5_base64 ( $data )
{
return preg_replace('/=+$/','',base64_encode(md5($data,true)));
}
?>
So this returns success, logged in or sorry wrong username/password combination..
Here is my form code:
<form>
<fieldset>
<p><label style="color:white;" for="email">E-mail address</label></p>
<p><input type="email" id="email" value=""></p>
<p><label style="color:white; font" for="password">Password</label></p>
<p><input type="password" id="password" value=""></p>
<p><input type="submit" value="Sign In"></p>
</fieldset>
and the JS:
<script>
$("form").on("submit", function() {
var username = document.getElementById('email').value;
var password = document.getElementById('password').value;
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: 'http://myurl.co.uk/appqueries/login.php?username='+username+'&password='+password,
dataType: "json"
}
}
});
//alert("Your username is "+username+" and your password is: "+password);
});
</script>
Can anybody help me getting what the JSON that the PHP file returns and then letting the user into the app if login is successful, or displaying a message if they were not.
I don't think you want a DataSource for this (it could be done, but the DataSource expects an array of objects from the read operation), unless there are additional requirements.
If this is your HTML:
<input id='username' type='text' value='user'></input>
<input id='password' type='text' value='password'></input>
<button id='loginbutton'>Login</button>
<div id='loginresult'></div>
Then you can use jQuery (which I assume you're using since it's a requirement for Kendo UI):
function loginClick() {
var username = $("#username").val();
var password = $("#password").val();
var loginUrl = 'http://myurl.co.uk/appqueries/login.php?username='+username+'&password='+password;
$.ajax({
url: loginUrl,
type: 'GET',
dataType: 'json',
success: function (data) {
handleLoginResult(data);
}
});
}
$(document).on("click", "#loginbutton", loginClick);
function handleLoginResult(data) {
var status = data.status;
var message = data.message;
if (status === "success") {
// do whatever needs to be done after successful login
$("#loginresult").html(message);
}
}
See a working example here (there are a few differences because this is using jsfiddle's echo api): http://jsfiddle.net/lhoeppner/9TGJd/
This works almost the same for Kendo Mobile, except you'd use the mobile button and the data-click binding:
<a id="loginbutton" data-role="button" data-click="loginClick">Login!</a>
You should not use form submit in Kendo Mobile application as a Kendo mobile application is basically a Single Page Application. What you need to do is to have a Kendo button and on the click event handler, fire the JSON call. You can see the demo of Kendo Button click event here: http://demos.kendoui.com/mobile/button/events.html#/