can not call any other function, then die my code - php

I'm building a login with ajax and php. My code works great until I do a call in my php code to another class. when dying my php code I get int even put a var_dump. you can see in my php code I've commented it out as I want to do really
View:
<body>
<p> </p>
<div id="content">
<h1>Login Form</h1>
<form id="form1" name="form1" action="stack.php" method="post">
<p>
<label for="username">Username: </label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="password">Password: </label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="button" id="login" name="login" value="submit"/>
</p>
</form>
<div id="message"></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#login").click(function(){
var action = $("#form1").attr('action');
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
is_ajax: 1
};
$.ajax({
type: 'POST',
url: action,
data: form_data,
success: function(data){
if(typeof(data) != 'undefined' && (data == 'success' || data == 'error')){
if(data == 'success'){
$("#form1").slideUp('slow', function() {
$("#message").html("<p class='success'>You have logged in
successfully!</p>");
});
} else if(data == 'error'){
$("#form1").slideUp('slow', function() {
$("#message").html("<p class='error'>Invalid username and/or
password.</p>");
});
}
} else {
console.log("här");
console.log(data);
$("#message").html("<p class='error'>Error to connect to server</p>");
}
}
});
return false;
});
});
</script>
</body>
</html>
PHP:
class DologinHandler{
public function Login(){
if(isset($_REQUEST['is_ajax']))
{
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
// $UserHandler = new UserHandler();
//$UserHandler -> controllDB($username,$password);
if($username == 'demo' && $password == 'demo')
{
exit('success');
} else {
exit('error');
}
}
}
}
?>

If the code in your post is all the PHP code you have written, it is not going to do anything. If your client expects 'success' or 'error', the fact that it's getting an empty string may be the reason why you're getting your error message.
In PHP, when you declare a Class, the code is only executed when you instantiate that class. You can do that by adding the two lines of code Waygood wrote in his answer, to the bottom of your stack.php file.
<?php
/* All your PHP code */
$loginclass=new DologinHandler();
$loginclass->Login();
And, for good practice, if there's no content appended to the code written above, get rid of the ?> at the bottom, that can save you quite some trouble. Not related to this issue though.

try
echo 'success';
return true;
instead of
exit('success');
also at the end of the function you should deal with non-ajax login
stack.php should be something like:-
$loginclass=new DologinHandler();
$loginclass->Login();

Related

Submit form using ajax: Was working, now not working?

I have the following HTML form in signup.php:
<form id="signup" action="" method="POST" autocomplete="off" autocomplete="false">
<div class="signup_row action">
<input type="text" placeholder="What's your Name?" name="name" id="name" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<input type="text" placeholder="Got an Email?" name="email" id="email" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<div class="g-recaptcha" style="margin-top:30px;" data-sitekey="6LeCkZkUAAAAAOeokX86JWQxuS6E7jWHEC61tS9T"></div>
<input type="submit" class="signup_bt" name="submit" id="submt" value="Create My Account">
</div>
</form>
I am trying to submit the form using ajax, without page refresh:
<!-- include files -->
<?php include 'assets/config.php';?>
<?php if(isset($_SESSION["CUSTOMER_ID"])){
header('Location: myaccount.php'); } ?>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('assets/login.php',function(){}).hide().fadeIn(500);
}
});
});
});
</script>
I am posting the form to do_signup_check.php and running a query to see if the user is already registered. echo 1 for a positive result and 0 for a negative result:
Do_Signup_Check.php:
<?php
session_start();
require 'assets/connect.php';
$myName=$_POST["name"];
$myEmail=$_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn)); }
if(mysqli_num_rows($check) > 0){
echo '1';
}else{
echo '0';
}
?>
If the result is 0 then the ajax should load my page do_signup.php.
But alas it is not getting this far. It was working and then i switched off the computer and came back to it and now it won't work.
Please can someone show me where I've gone wrong?
if(result == 0){ here result is not using in success function:
you must need to pass resultant variable here:
success: function () {
as:
success: function (result) {
Now, you can use your condition if(result == 0){
Second, i suggest you to pass dataType: 'html' in your ajax request.
Edit:
You are using <?php if(isset($_SESSION["CUSTOMER_ID"])){ line in your code, if you are not using session_start() in your code then this check will not work.
For this line data:{"name":name,"email":email}, i didnt see name and email in your code, where you define these 2 variables which you are using in your ajax params.

login with ajax issue

I am trying to create on-page login.
without ajax it works very well. Here is my login.php;
if($_POST)
{
$username =$_POST["username"];
$password =$_POST["password"];
$query = $handler->query("SELECT * FROM members WHERE username='$username' && password='$password'",PDO::FETCH_ASSOC);
if ( $say = $query -> rowCount() ){
if( $say > 0 ){
session_start();
$_SESSION['session']=true;
$_SESSION['username']=$username;
$_SESSION['password']=$password;
echo "ok";
}else{
echo "Couldn't login.";
}
}else{
echo "Wrong username or password.";
}
}
Anyway, here is my java script code;
$(function(){
$("#loginbutton").click(function(){
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != ""){
$.ajax("login.php",{
type : "POST",
data : "username="+username+"&password="+password,
success : function(data){
if(data == "ok"){
$("#message").html(data);
}else{
$("#fail").fadeIn();
}
}
});
}
});
});
Even though I put correct login information (when I get "ok" response from login.php, it always outputs $("#fail").fadeIn(); . instead of $("#message").html(data); I couldn't figure out where I am mistaken.
and here is login form:
<div id="login">
<form action="" onsubmit="return false;" method="post">
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off"><br>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" autocomplete="off"><br>
<input class="btn btn-success" type="submit" id="loginbutton" value="Login">
</form>
<div id="message"> </div>
<div id="fail" style="display: none;">failed.</div>
</div>
You are using type as post, but sending parameters as get.Change your ajax like this,
$.ajax("login.php",{
type : "POST",
data : {username:username,password:password},// only this line is changed.
success : function(data){
if(data == "ok"){
$("#message").html(data);
}else{
$("#fail").fadeIn();
}
}
});
Here is a quick example of using post with JQuery AJAX.
$(document).ready(function(){
$.post("login.php", {username:username, password:password}, function(data){
if(data == 'ok'){
$("#message").html(data);
}else{
alert(data);//alert the data you receive. It alerts you if there is any error in php file.
$("#fail").fadeIn();
}
});
});
Hope that was helpful!
Firstly, debug your code like this:
1) On button click you will put alert function inside javascript code. if it is working then move second step.
2) use alert function to print username and password if it comes inside your javascript code and correct as you put into input fields then move third step.
3) use serialize method in javascript.
I hope its help you to get your solution.

Form still redirect to PHP with preventDefault

EDIT:
This was related to a typo elsewhere in my Javascript. I had forgotten to check the Javascript console. Thank you for your comments.
This is my first post on this site. I have been reading it for a long while though.
I am working on a login form utilizing jQuery, AJAX, and PHP. Several times now I have run into the problem where I am redirected to the PHP page where I see the echoed data I wanted returned. I have tried to figure this out but I am stuck.
EDIT:
I did include jQuery:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
HTML:
<form name="login" id="loginForm" action="login.php" method="post">
<label for="usernameInput">Username: </label>
<input type="text" name="usernameInput" id="usernameInput" placeholder="Username" autofocus required>
<label for="passwordInput">Password: </label>
<input type="password" name="passwordInput" placeholder="Password" required>
<input type="submit" name="loginSubmit" value="Log In">
</form>
jQuery:
function login () {
$('#loginForm').on('submit', function(e){
e.preventDefault();
var formObject = $(this);
var formURL = formObject.attr("action");
$.ajax({
url: formURL,
type: "POST",
data: formObject.serialize(),
dataType: 'json',
success: function(data)
{
$("#loginDiv").remove();
if(data.new) {
$("#setupDiv").show();
} else {
statusUpdate();
/* EDIT: Changed from dummy text 'continue()' */
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#loginDiv").append(textStatus);
}
});
});
}
Call:
$(document).ready(function() {
login();
});
PHP:
// Main
if (isset($_POST['usernameInput'], $_POST['passwordInput']))
{
require "hero.php";
// Starts SQL connection
$sql = getConnected();
$userArray = validateUser($sql);
if ( $userArray['id'] > 0 ) {
sessionSet($userArray);
$userArray['user'] = (array) unserialize($userArray['user']);
$userArray = json_encode($userArray);
echo $userArray;
exit();
}
else
{
echo 'Username does not exist';
}
}
else
{
echo "Please enter a username and password.";
}
I know I have not included everything, but here's the output:
{"id":"11","name":"st5ph5n","new":true,"user":[false]}
So everything up to $userArray is working as expected. Why is this not staying on index.html and instead redirecting to login.php?
Thank you for any responses.

AJAX login form reloading the page

Trying to create a login form using AJAX so the page does not have to change to log a user in. So far I have the following after using a tutorial I found however I have the problem of the form is reloading the page instead of calling the JavaScript function.
HTML:
<form class="login-form" onSubmit="check_login();return false;">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit" class="btn trans login-button">Login</button>
</form>
PHP:
// Retrieve login values from POST variables
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
// Salt and hash password for database comparison
$password = saltHash($password);
// Check that both fields are not empty
if(!empty($email) || !empty($password)) {
// Query database to check email and password match entry
$database->query('SELECT * FROM users WHERE email = :email AND password = :password');
$database->bind(':email',$email);
$database->bind(':password',$password);
$result = $database->single();
if(!empty($result)) {
// Check entered details match the database
if($email == $result['email'] && $password == $result['password']) {
// If login details are correct, return 1
echo '1';
}
}
else {
// If not returned results, return 2
echo '2';
}
}
else {
// If either fields are empty, return 3
echo '3';
}
JavaScript / jQuery:
// Login function
function check_login() {
$.ajax({
type: 'POST',
url: 'check-login.php',
data: 'email=' + $('input[value="email"]').val() + '&password=' + $('input[value="password"]').val(),
success: function(response){
if(response === '1') {
alert('Log In Success');
}
else if(response === '2') {
alert('Incorrect Details');
}
else if(response === '3') {
alert('Fill In All Fields');
}
}
});
}
Any help is greatly appreciated.
Use This bro...
<form id="F_login" class="login-form">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button id="btn_login" type="submit" class="btn trans login-button">Login</button>
</form>
$("#btn_login").click(function(){
var parm = $("#F_login").serializeArray();
$.ajax({
type: 'POST',
url: 'check-login.php',
data: parm,
success: function (response) {
if(response === '1') {
alert('Log In Success');
}
else if(response === '2') {
alert('Incorrect Details');
}
else if(response === '3') {
alert('Fill In All Fields');
}
},
error: function (error) {
alert("Login Fail...");
}
});
});
else if(response === '3') {
alert('Fill In All Fields');
}
}
});
}
It should run well...
Try this:
<form class="login-form">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button class="btn trans login-button" onclick="check_login()">Login</button>
</form>
When the login submits, it will still try to reload the page, so you should remove the submit type and put the login function on the button
Attaching event listeners via tags is not a good practice and using jQuery for it it's cleaner and easier.
Try doing this:
$("form.login-form .login-button").click(function(e) {
e.preventDefault();
check_login();
});
Remember to remove this:
onSubmit="check_login();return false;
The statement check_login();return false will not work. You have to call return check_login(); and return false inside the function.
HTML
<form onsubmit="return check_login();">
<!-- input fields here -->
</form>
Javascript
function check_login() {
// Do your ajax call.
return false;
}
Right way is:
HTML Code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// Login function
$(function() {
$('.login-button').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'check-login.php',
data: $('form.login-form').serialize(),
success: function(response) {
if (response === '1') {
alert('Log In Success');
} else if (response === '2') {
alert('Incorrect Details');
} else if (response === '3') {
alert('Fill In All Fields');
}
}
});
});
})
</script>
<title>Ajax Login Form (Demo)</title>
</head>
<body>
<form class="login-form" name="login-form" method="POST" action="">
<input type="text" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password" />
<button type="submit" class="btn trans login-button">Login</button>
</form>
</body>
</html>
Write your ajax code inside
$(document).ready(function(){
//
}); or
$(function(){
//
});
User Prevent Default to stop Form Submission
You can use 'serialize' function to make POST pram.
Remove the button type and use the onclick handler on it, not on the form.
It will also take care of the situation when it automatically submits on pressing enter key by accident.
Happy Coding !!!
there are a lot of way to do this:
write this code in your index:
index
use "eval" function in javascript instead of "alert" to show the reasult
it means that on your PHP code when the code receive the true inputs and there is a user in your database like the input, the PHP code echo javascript orders (bellow is your PHP codes that you send an ajax request to that):>
<?php if(response==1){
echo '$("link_reload").trigger("click");';
} ?>
and in your javascript use evel() instead of alert()
Try changing the input type from "submit" to a regular button whose onclick action is to call check_login()

How to use $.ajax function properly?

I don't know how to run $.ajax properly. I usually make all xmlHTTP objects manually using javascript and then use jQuery wherever required. So please help me use this function properly in jQuery.
HTML
<form action="login.php" method="post" onSubmit="return login()" >
<input type="text" name="eMailTxt" id="eMailTxt" placeholder="Email Address" />
<input type="password" name="passWordTxt" id="passWordTxt" placeholder="password" />
<br />
<p><!--wanna show password does not match here--></p>
<input type="submit" value="Login" id="submitBtn" class="Btn" />
</form>
JQuery Ajax
function login()
{
$email = $("#eMailTxt").val();
$pass = $("#passWordTxt").val();
$.ajax({
url:'loginCheck.php',
type:'POST',
data:{q:$email,s:$pass},
success:function(response){
$("#loginForm p").innerHTML = xmlhttp.responseText;
return false; //is this the correct way to do it?
}
});
return true; //not really sure about this
}
PHP MySQL
$q=$_POST["q"];
$s=$_POST["s"];
$con=mysqli_connect("localhost","root","","SocialNetwork");
$check="SELECT PassWord FROM people WHERE EMAIL = '".$q."'";
$data=mysqli_query($con,$check);
$result=mysqli_fetch_array($data);
if ($s != $result)
{
echo "Password does not match";
}
jQuery object doesn't have a property innerHTML which is used on DOM element. Use method html() instead:
$("#loginForm p").html(response);
Or you could refer to DOM element like that:
$("#loginForm p")[0].innerHTML = response; // equivalent to .get(0)
Be aware as ajax is async by default, your login function here will always return true.
BTW, response here corresponds to the returned value from server, not the jqXHR object (xhr object wrapped inside a jquery object).
UPDATE
function login(form)
{
$email = $("#eMailTxt").val();
$pass = $("#passWordTxt").val();
$.ajax({
url:'loginCheck.php',
type:'POST',
data:{q:$email,s:$pass},
success:function(response){
if(response === "Password does not match") {
$("#loginForm p").html(response);
return false;
}
//if password match, submit form
form.submit();
}
});
//we always return false here to avoid form submiting before ajax request is done
return false;
}
In HTML:
<form action="login.php" method="post" onSubmit="return login(this)" >
HTML
<form action="login.php" method="post" class="js-my-form">
<input type="text" name="record[email]" id="eMailTxt" placeholder="Email Address" />
<input type="password" name="record[password]" id="passWordTxt" placeholder="password" />
<br />
<p><!--wanna show password does not match here--></p>
<input type="submit" value="Login" id="submitBtn" class="Btn" />
</form>
jQuery
$(document).ready(function () {
$('.js-my-form').submit(function () {
var data = $(this).serialize();
var action = $(this).attr('action');
var methodType = $(this).attr('method');
$.ajax({
url: action,
type: methodType,
data: data,
beforeSend: function () {
//Maybe Some Ajax Loader
},
success: function (response) {
// success
},
error: function (errorResponse) {}
});
return false; //Send form async
});
});
PHP
if (isset($_POST['record']) {
//Your PHP Code
} else {
header("HTTP/1.0 404 Not Found"); // Trow Error for JS
echo 'invalid data';
}
Ajax success call back contains only data (you are confused with the compete function of ajax or pure javascript xmlhttp request)
therefore
success:function(response){
$("#loginForm p").html(response);
}
Also seeing your query you are susceptible to sql injection

Categories