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';
}
}
Related
PHP code
<?php
...
//Extract the data that was sent to the server
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$findemail = [
"email" => $email,
"password" => $password,
];
$cursor = $collection->findOne($findemail);
if($cursor){
if($cursor['email'] == $email and $cursor['password'] == $password){
// I Know these two lines don't work but I want to show what I want to do
echo "success";
header('location: cms-view-products.html');
}
else {
echo "failed";
header('location: login.php');
}
}
?>
AND this is my HTML code
<?php include('demo2.php') ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="demo2.php" onsubmit="return false"; method="post">
Email: <input type="email" name="email" required >
name: <input type="password" name="password" required >
<button type='submit' onclick="loadContent()">Load</button>
</form>
<div id="ServerContent">
<p>Dynamically loaded content goes here</p>
</div>
<script>
function loadContent(){
var url = "demo2.php";
var email = document.getElementsByName('email').value;
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById("ServerContent").innerHTML = this.responseData;
}
else
alert("Error communicating with server");
}
var data = `JSON.stringify({
"email": "document.getElementsByName('email').value",
"name": "document.getElementsByName('name').value"
})`;
xhr.send(data);
}
</script>
</body>
</html>
I've currently tried to echo the message via JS, the specific element <p id=" feedback"></p>, nevertheless it doesn't work. With PHP the process works, nevertheless, I can't redirect users using headers. I've found $_SESSION could resolve this issue. However, my question is to use JS to open a pop-up and then redirect the user to x page?
I edited the post since comments advised me about using Ajax and so this is my first attempt. I can always achieve one of the two either redirect the user to x page or show an error massage. but I can't do both.
Also, I don't want to alert the massage, but to change HTML element dynamically.
Thanks guys for your time and comments.
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.
I have a login script that should return 'success' or 'failure' respectively, but it adds many spaces before the result, in the console it shows tha value as "<tons of space> success". This is the PHP for the login script:
public function login() {
global $dbc, $layout;
if(!isset($_SESSION['uid'])){
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
if(!empty($username) && !empty($password)){
$query = "SELECT uid, email, username, password, hash FROM users WHERE email = '$username' AND password = SHA('$password') AND activated = '1'";
$data = mysqli_query($dbc, $query);
if((mysqli_num_rows($data) === 1)){
$row = mysqli_fetch_array($data);
$_SESSION['uid'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SERVER['REMOTE_ADDR'] = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
$ip = $_SERVER['REMOTE_ADDR'];
$user = $row['uid'];
$query = "UPDATE users SET ip = '$ip' WHERE uid = '$user' ";
mysqli_query($dbc, $query);
setcookie("ID", $row['uid'], time()+3600*24);
setcookie("IP", $ip, time()+3600*24);
setcookie("HASH", $row['hash'], time()+3600*24);
echo 'success';
exit();
} else {
//$error = '<div class="shadowbar">It seems we have run into a problem... Either your username or password are incorrect or you haven\'t activated your account yet.</div>' ;
//return $error;
$err = 'failure';
echo($err);
exit();
}
} else {
//$error = '<div class="shadowbar">You must enter both your username AND password.</div>';
//return $error;
$err = "{\"result\":\"failure\"}";
echo json_encode($err);
exit();
}
}
} else {
echo '{"result":"success"}';
exit();
}
return $error;
}
and the form and JS
<div class="shadowbar"><form id="login" method="post" action="/doLogin">
<div id="alert"></div>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success : function(result) {
console.log(result);
if(result == " success"){
window.location = "/index.php";
}else if(result == " failure"){
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
});
but the result always has a lot of spaces for some reason. I'm new to JS, so if this is common, I don't already know.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
define("CCore", true);
session_start();
//Load files...
require_once('include/scripts/settings.php');
require_once('include/scripts/version.php');
require('include/scripts/core.class.php');
require('include/scripts/nbbc_main.php');
$parser = new BBCode;
$core = new core;
$admin = new admin;
require_once('include/scripts/layout.php');
require_once('include/scripts/page.php');
//Set Variables...
global $dbc, $parser, $layout, $main, $settings, $core;
$page = new pageGeneration;
$page->Generate();
?>
this is my index, and anything before the page is generated and login() is called, is in there.
I suppose you are using Ajax calls. I had the same problem, but it my case the result hadn't contain spaces, it was returned in new line. The problem was that my script which was requested by Ajax, contained "new line" character before the PHP script. Search your script file for spaces before PHP script starting with <?php //code... If you had included some scripts in the script which returns success note, search them as well.
I dont know if it matters but your
if(result == " success"){ // <<<<<< Here is a Problem maybe
window.location = "/index.php";
}else if(result == " failure"){ // <<<<<< Here is a Problem maybe
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
compares your result from the server which is i.e. "success" with " success". There is space too much.
EDIT:: I dont get ether why you jumps between the response format. Sometimes you echo "success" which is plain and good with your if condition but sometimes you return json encodes strings.
These Responses you can't just compare with plain text. These Responses you have to Parse into a JSON Object. Then you could compare with:
if (parsedJSONobject.result == "success"){}
The comments on the question are most probably correct: the spaces are being (again, probably, nobody can know for sure without reading the whole source) echoed by PHP included before this. For example, if you do:
<?php
// there's a space before the previous line
you'd get that space in the output.
What you can do is a bit of a hack, you include a header, for example:
header('Content-Type: text/html');
just before your success output, this will (yet again, probably) output something like:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
(note the "output started" part) and now you know where to start looking.
HTH.
I have been following a tutorial and the person who does it provide the code for you to use, so ive tried using the code and going through it line by line but as i hardly know anything about ajax, i cant seem to understand why it is not passing data through to the page that is specified,and since the data isnt being passed through the process of mysqli queries and all other things, they wont begin to happen as the data isnt being passed over.
The data is part of a form and it is to check usernames against the database to check availability, so the code for the data in the form is ...
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">...
And so on... the js provided is ..
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signupfunc.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
So as far as i understand, var u= _("username").value is the value of the input with the id=username, and if username is not blank then it firstly brings up the checking... before starting the var that is called ajax, it begins the process of POSTing to the page, signupfunc.php, then im not exactly sure the next bit but i think it means something like if something returns from the var ajax then it puts the response return in the unamestatus div ?? then the last bit does as it says? the var ajax sends the value of usernamecheck as the username... but it is not sending the data to the specified page ... can someone point out what im doing wrong advise how to solve this problem ??
and just incase it is needed here is the code that is on the specified page signupfunc.php that is related to the code above..
//Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
maybe you can try change you code with below jquery ajax code :
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
$.ajax({
url : "signupfunc.php",
type : "POST",
data : "usernamecheck="+u,
dataType : 'text',
success: function(data,textStatus,jqXHR){
alert(data);
}
})
}
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!