Many spaces before javascript result - javascript

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.

Related

Ajax call for the Bootstrap Modal not working

I'm trying to make a simple Ajax call for a Bootstrap login modal. The main HTML code of the login Modal looks like this:
<form method="post" id="loginForm">
<div id="loginMessage"></div>
<div class="modal-footer">
<button type="button" class="btn btn-success mr-auto" data-target="#signupModal" data-toggle="modal" data-dismiss="modal">Register</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<input class="btn" name="login" type="submit" id="inputButton" value="Login">
</div>
</form>
In case the whole HTML code for the modal would help : https://jsfiddle.net/aslah/hykxLqd5/2/
The jQuery code looks like this:
$('#loginForm').submit(function(event){
//prevent default php processing
event.preventDefault();
//collect user inputs:
var datatopost = $(this).serializeArray();
//send the user data to login.php using AJAX
$.ajax({
url: "login.php",
type : "POST",
data : datatopost,
success : function(data){
if(data == 'success'){
window.location = "mainpage.php";
}else{
$('#loginMessage').html(data);
}
},
error : function(){
$('#loginMessage').html('<div class="alert alert-danger">There was an error with the AJAX call. Please, try again later!</div>');
}
});
});
This is my login.php code :
<?php
//starting the session
session_start();
//connecting to database
include('connection.php');
//check user inputs
// DEFINE ERROR MESSAGES //
$missingEmail = '<p><strong>Please enter your email address!</strong></p>';
$missingPassword = '<p><strong>Please enter a password!</strong></p>';
// $email = $_POST["loginEmail"]
// $password = $_POST["loginPassword"]
if(empty($_POST["loginEmail"])){
$error .= $missingEmail;
}else{
$email = filter_var($_POST["loginEmail"], FILTER_SANITIZE_EMAIL);
}
if(empty($_POST["loginPassword"])){
$error .= $missingPassword;
}else{
$password = filter_var($_POST["loginPassword"], FILTER_SANITIZE_STRING);
}
//If there are any ERRORS
if($error){
$resultMessage = '<div class="alert alert-danger">'. $error .'</div>' ;
echo $resultMessage ;
}else{
$email = mysqli_real_escape_string($link, $email);
$password = mysqli_real_escape_string($link, $password);
// $password = md5($password); no secure
$password = hash('sha256', $password);
//check if the user is registered by matching EMAIL & PASSWORD
$sql = "SELECT * FROM users WHERE email = '$email' AND password = '$password' AND activation='activated' ";
$result = mysqli_query($link, $sql);
//if any errors while running the query
if(!$result){
echo '<div class="alert alert-danger"> Error running the query!</div>';
exit;
}
//if login failed print ERROR
$count = mysqli_num_rows($result);
if($count !== 1){
echo '<div class="alert alert-danger">Wrong username or password</div>';
}else{
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
//if remember me is not checked
if(empty($_POST['rememberme'])){
echo "success";
}else{
// if rememberme is checked
}
}
}
?>
On submit of the the Login button I want to redirect the user to the mainpage.php. I tried all the different fixes I found here but nothing worked. I can't figure out what I'm doing wrong. Any help is highly appreciated.
This is what I get when I submit the form
Aslah P Hussain
I have tested your code. The first thing that caught my attention is Notice about the undefined variable $error. Possibly you have defined it in include('connection.php'); but if not, this can cause problems with PHP output that you are expecting.
Additionally, if you are 100% sure that the console returns the message success - you can change your check in JavaScript to:
if(data.indexOf('success') >= 0){
window.location = "mainpage.php";
}else{
$('#loginMessage').html(data);
}
Possibly not the best solution to the problem, but at least will show you that redirect is working

Ajax validation duplicates html page inside html element

My PHP username validation with Ajax duplicates my html page inside of html div(this is for showing ajax error) element. I tried some solutions and google it bu can't find anything else for solution. Maybe the problem is about the $_POST but I also separated them in php (all the inputs validation).
Here is PHP code
<?php
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (! $user->isValidUsername($username)){
$infoun[] = 'Your username has at least 6 alphanumeric characters';
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['username'])){
$errorun[] = 'This username is already in use';
}
}
}
if(isset($_POST['fullname'])){
//fullname validation
$fullname = $_POST['fullname'];
if (! $user->isValidFullname($fullname)){
$infofn[] = 'Your name must be alphabetical characters';
}
}
if(isset($_POST['password'])){
if (strlen($_POST['password']) < 6){
$warningpw[] = 'Your password must be at least 6 characters long';
}
}
if(isset($_POST['email'])){
//email validation
$email = htmlspecialchars_decode($_POST['email'], ENT_QUOTES);
if (! filter_var($email, FILTER_VALIDATE_EMAIL)){
$warningm[] = 'Please enter a valid email address';
} else {
$stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
$stmt->execute(array(':email' => $email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['email'])){
$errorm[] = 'This email is already in use';
}
}
}
?>
Here is Javascript
<script type="text/javascript">
$(document).ready(function(){
$("#username").keyup(function(event){
event.preventDefault();
var username = $(this).val().trim();
if(username.length >= 3){
$.ajax({
url: 'register.php',
type: 'post',
data: {username:username},
success: function(response){
// Show response
$("#uname_response").html(response);
}
});
}else{
$("#uname_response").html("");
}
});
});
</script>
<input type="text" name="username" id="username" class="form-control form-control-user" placeholder="Kullanıcı Adınız" value="<?php if(isset($error)){ echo htmlspecialchars($_POST['username'], ENT_QUOTES); } ?>" tabindex="2" required>
<div id="uname_response" ></div>
Here is the screenshot:
form duplicate screenshot
The only code in your PHP file should be within the <?php ?> tags. You need to seperate your PHP code into another file.

PHP login and set cookie properly

I have never worked with $_COOKIES, and now I've been given the task to make it work.
I have been following a couple of tutorials online.
Found here: http://www.phpnerds.com/article/using-cookies-in-php/2
And then here:https://www.youtube.com/watch?v=Dsem42810H4
Neither of which worked for me.
Here is how my code ended up. I shortened it as much as I could.
Starting with the index.php page, which contains the initial login form:
<form role="form" action="index.php" method="post" id="loginForm" name="loginForm">
<input type="text" class="form-control" id="username" name="username"
value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" />
<input type="password" class="form-control" id="password" name="password"
value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>"/>
<button type="button" id="loginSubmit" name="loginSubmit" class="btn btn-primary btn-block btn-flat">Sign In</button>
<input type="checkbox" id="rememberme"
<?php if(isset($_COOKIE['username'])){echo "checked='checked'";} ?> value="1" />
</form>
Here is the JavaScript used to send the form values:
$('#loginSubmit').on('click', function()
{
var username = $('#username').val();
var password = $('#password').val();
var rememberme = $('#rememberme').val();
// skipping the form validation
$.post('api/checkLogin.php', {username: username, password: password, rememberme:rememberme}, function(data)
{
// the data returned from the processing script
// determines which page the user is sent to
if(data == '0')
{
console.log('Username/Password does not match any records.');
}
if(data == 'reg-user")
{
window.location.href = "Home.php";
}
else
{
window.location.href = "adminHome.php";
}
});
});
Here is the processing script, called checkLogin.php. This is where I attempt to set the $_COOKIE:
<?php
include ("../include/sessions.php");
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['password'])));
$rememberme = $_POST['rememberme'];
$select = "SELECT username, fullname, password FROM users WHERE username = '".$username."'";
$query = mysqli_query($dbc, $select);
$row = mysqli_fetch_array($query);
$dbusername = htmlentities(stripslashes($row['username']));
$dbfullname = htmlentities(stripslashes($row['fullname']));
$dbpassword = htmlentities(stripslashes($row['password']));
if(password_verify($password, $dbpassword))
{
// setting sessions here
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $dbfullname;
// here is where I attempt to set the $_COOKIE
if(isset($remember))
{
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', $_POST['password'], time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false);
setcookie('password', $_POST['password'], false);
}
echo $username; // this gets sent back to the JavaScript
mysqli_free_result($query);
}
else
{
// username/password does not match any records
$out = 0;
echo $out;
}
}
?>
So now that I have attempted to set the $_COOKIE, I can try to print it to the home page, like so:
<?php echo 'cookie ' . $_COOKIE["username"]; ?>
To which does not work, because all I see is the word 'cookie'.
Besides that, when I log out, I am hoping to see the login form already filled out, which is the overall task I have been trying to complete, but have been unsuccessful at doing so.

loop through JSON file using ajax, PHP & Javascript

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';
}
}

PHP and Javascript - Problems with undefinded variable

Hey guys i am very new to this so i am sorry if there is just something completely stupid i am missing here. I have the following Sign Up Form. And in the URL http://www.rockaholics-cologne.de/root/signup.php?e=cataras#gmx.de i am trying to submit the value e. However, in all cases e is simply empty or undefined:
<?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$p = $_POST['p'];
$e = $_GET['e'];
echo "test";
echo "$e";
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM team WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $p == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
$cryptpass = crypt($p);
include_once ("php_includes/randStrGen.php");
$p_hash = randStrGen(20)."$cryptpass".randStrGen(20);
// Add user info into the database table for the main site table
$sql = "UPDATE team
SET username='$u',password='$p_hash',ip='$ip',signup=now(),lastlogin=now(),notecheck=now()
WHERE email='$e'";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
// Email the user their activation link
$to = "$e";
$from = "auto_responder#yoursitename.com";
$subject = 'Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8">
<title>yoursitename Message</title></head>
<body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;">
<div style="padding:10px; background:#333; font-size:24px; color:#CCC;">
<img src="http://www.rockaholics-cologne.de/root/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">Account Activation</div>
<div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* Username: <b>'.$u.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
?>
I do get new entries into the database when i fill out the form. But it does neither send me an email or UPDATE the database at the specified email. It simply updates all the entries with a blank email. The echo "$e" within the script also return nothing.
I used this code to check:
<?php
echo "<pre>";
print_r($_GET);
echo "</pre>";
$e = $_GET['e'];
echo "$e";
?>
And in this case it does return an array with [e]=cataras#gmx.de and it also prints out $e. But why doesnt it work in the other skript? I'm using the exact same methods to get e from the URL.
When i run my Javascript function:
function signup(){
var u = _("username").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var status = _("status");
if(u == "" || p1 == "" || p2 == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText.replace(/^\s+|\s+$/g, "") == "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&p="+p1);
}
}
I get Uncaught ReferenceError: e is not defined. And the site stops at "please wait...". I just took out the +e+ in the js to get to the php above. Sorry for the long post but i am really running out of ideas. THANKS in advance!!!
I think $_GET['e'] is not working in your original script because it's not getting passed to that processing script from your form page. I accessed the URL you provided (http://www.rockaholics-cologne.de/root/signup.php?e=cataras#gmx.de). Note that when you submit your form, the value of "e" in your URL is not being passed to whatever is processing your script. In your form, you need to either do this:
<form action="{yourscripturl}?e=<?php echo $_GET['e']?>" {rest of form tag}>
Or, add a hidden to hold the value of "e", and then use $_POST['e'] on your processing script instead of $_GET['e'].
<input type="hidden" name="e" value="<?php echo $_GET['e']?>" />

Categories

Resources