AJAX not returning result from php - javascript

I am trying to learn from an example from online,for a login form with php and jquery and i am using the exactly the same example, but for some reason the AJAX isnt getting anything back but redirecting my to another php.
Here is a link of what i had been trying and the problem.
http://rentaid.info/Bootstraptest/testlogin.html
It supposed to get the result and display it back on the same page, but it is redirecting me to another blank php with the result on it.
Thanks for your time, i provided all the codes that i have, i hope the question isnt too stupid.
HTML code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form id= "loginform" class="form-horizontal" action='http://rentaid.info/Bootstraptest/agentlogin.php' method='POST'>
<p id="result"></p>
<!-- Sign In Form -->
<input required="" id="userid" name="username" type="text" class="form-control" placeholder="Registered Email" class="input-medium" required="">
<input required="" id="passwordinput" name="password" class="form-control" type="password" placeholder="Password" class="input-medium">
<!-- Button -->
<button id="signinbutton" name="signin" class="btn btn-success" style="width:100px;">Sign In</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javasript" src="http://rentaid.info/Bootstraptest/test.js"></script>
</body>
</html>
Javascript
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
$("#loginform").submit(function() {
return false;
});
}
});
php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
ob_start();
session_start();
include 'connect.php';
//get form data
$username = addslashes(strip_tags($_POST['username']));
$password = addslashes(strip_tags($_POST['password']));
$password1 = mysqli_real_escape_string($con, $password);
$username = mysqli_real_escape_string($con, $username);
if (!$username || !$password) {
$no = "Please enter name and password";
echo ($no);
} else {
//log in
$login = mysqli_query($con, "SELECT * FROM Agent WHERE username='$username'")or die(mysqli_error());
if (mysqli_num_rows($login) == 0)
echo "No such user";
else {
while ($login_row = mysqli_fetch_assoc($login)) {
//get database password
$password_db = $login_row['password'];
//encrypt form password
$password1 = md5($password1);
//check password
if ($password1 != $password_db)
echo "Incorrect Password";
else {
//assign session
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
}
}
}
}
?>
Edit
$("button#signinbutton").click(function(){
if($("#username").val() ==""||$("#password").val()=="")
$("p#result).html("Please enter both userna");
else
$.post ($("#loginform").attr("action"),
$("#loginform:input").serializeArray(),
function(data) {
$("p#result).html(data); });
});
$("#loginform").submit(function(){
return false;
});

First of all, Remove :-
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
and if you want to display the data, echo username and password.
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
echo $username."<br>".;
echo $password1;

The reason you are being redirected is that you are also calling $.submit. The classic form submit will redirect you to a new page, which is exactly what you don't want when you're using AJAX. If you remove this call:
$("#loginform").submit(function() {
return false;
});
you probably should have working solution. If not, let me know :)

Modify your javascript section so that
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
}
});
$("#loginform").submit(function() {
return false;
});
is outside the function call.

Related

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.

Login form, Ajax call to PHP function

I have a login form, where I want to pass data from it by Ajax, into a PHP function in another file. The purpose of this is that I want the page not to reload when the user is logging in.
Right now nothing happens when user tries to log in. Seems like access.php is not proccessing the data sent from Ajax.
Can someone tell me why this is not working? What are the possible causes?
index.html:
<div class="login-form">
<form method="post" action="index.php">
<input id="username" type="text" placeholder="Username...">
<input id="password" type="password" placeholder="Password...">
<button id="button" type="submit">Login</button>
</form>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script type="text/javascript">
$('#button').click(function(e) {
e.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: 'resources/includes/access.php',
data: {
func: 'loginSubmit',
usernamePHP: username,
passwordPHP: password
},
success: function(response) {
$('#result').html(response);
}
});
});
</script>
</div>
access.php:
function loginSubmit(){
require '../dbh.inc.php';
$mailuid = $_POST['usernamePHP'];
$password = $_POST['passwordPHP'];
if(empty($mailuid) || empty($password)){
header("Location: ../../index.php?error=emptyfields");
exit();
}
else{
$sql = "SELECT * FROM users WHERE uidUsers=? OR emailUsers=?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("Location: ../../index.php?error=sqlerror");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "ss", $mailuid, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if($row = mysqli_fetch_assoc($result)){
$pwdcheck = password_verify($password, $row['pwdUsers']);
if($pwdcheck == false) {
header("Location: ../../index.php");
exit();
}
else if($pwdcheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
header("Location: ../../index.php?login=success");
exit();
}
else{
header("Location: ../../index.php");
exit();
}
}
}
}
}
From what I can see from the documentation, adding the function name as a data property as you are, doesn't call that function;
data
Type: PlainObject or String or Array
When you call access.php, the file simply contains a function definition, you're not actually calling it.
So you have two options. Either call the function by adding loginSubmit() after the function (at the end of access.php), or remove the code on access.php from a function entirely.

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.

Many spaces before javascript result

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.

Pushing in MySQL data with javascript and php

I'm working on a program but I'm new to js/jQuery/Ajax. I am trying to get user input from a form (html) and send it over to a php file that will insert the data into a MySQL database and then ultimately spit out the information into a div. I press submit but my user submitted data does not get inserted into the database. I initially had the submission redirect to my php file through the tag (action="post.php") which had worked in terms of inserting the data into the mysql database but had also redirected it to that post.php file upon submission.
my js file datawire.js:
$( 'button#submit').on('click', function() {
var uName = $('input#uName').val();
var uMessage = $('input#uMessage').val();
if ($.trim(uName) != '' && $.trim(uMessage) != '') {
$.post('post.php', {username: uName, message: uMessage}, function(data) {
$('div#viewer').text(data);
});
}
});
My php file post.php
<?php include("config.php");
$username = isset($_POST['username']);
$message = isset($_POST['message']);
if (($username && $message) && (empty($_POST['username'] === false) && empty($_POST['message']) === false)) {
$username = $_POST['username'];
$message = $_POST['message'];
// insert into database
$nowTime = getDateTime();
$userIp = getIp();
$sql = "INSERT INTO commentdb (id,username, message,date,ip) VALUES ('','$username','$message', '$nowTime', '$userIp') ";
$result = mysql_query($sql);
}
?>
and my HTML file:
<html>
<head>
<!-- latest jQuery direct from google -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- for getting data -->
<script src="datawire.js"></script>
<!-- for posting data -->
<script type="text/javascript">
$(document).ready(function() {
$('#viewer').load("getdata.php");
});
</script>
</head>
<body>
<div id="viewer"> </div>
<br>
<!-- User form -->
<form method='post'>
<input type="text" id="uName" name="username" placeholder="Name" value="" maxlength="15" />
<br />
<input type="text" id="uMessage" name="message" placeholder="Message" value="" maxlength="100" />
<br />
<button id="submit" type="submit">Submit!</button> <button type="reset">Clear!</button>
</form>
</body>
</html>
Try wrapping the contents of datawire.js with $(document).ready like you did in html file. This insures $ is actually defined before it's used.
Prevent your form submit with preventDefault() function
$( 'button#submit').click(function(e) {
e.preventDefault();
var uName = $('input#uName').val();
var uMessage = $('input#uMessage').val();
if ($.trim(uName) != '' && $.trim(uMessage) != '') {
$.post('post.php', {username: uName, message: uMessage}, function(data) {
$('div#viewer').text(data);
});
}
});
Return the text message from the server like this
<?php include("config.php");
$username = isset($_POST['username']);
$message = isset($_POST['message']);
if (($username && $message) && (empty($_POST['username'] === false) && empty($_POST['message']) === false)) {
$username = $_POST['username'];
$message = $_POST['message'];
// insert into database
$nowTime = getDateTime();
$userIp = getIp();
$sql = "INSERT INTO commentdb (id,username, message,date,ip) VALUES ('','$username','$message', '$nowTime', '$userIp') ";
$result = mysql_query($sql);
if($result)
{
echo " Data Inserted Successfully";
}else{
echo " Data insert failed - ".mysql_error();
}
}else{
echo " Required fields are missing";
}
?>

Categories

Resources