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

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.

Related

Won't run ajax if I change input type..?

I have a form for user to update their info using jquery + Ajax. Everything is working great so far, but WHen i change input type="email" to input type="text" in the fullname section of the form and click update. It got error??? It won't run the php file in ajax. I don't see any connection which causes this error? Anyone please sugguest why? But if I change input type in the fullname section back to "email". It works! This is so weird!
Here is my form:
<div id="changeuserinfo_result"></div>
<form role="form" method="post">
<div class="form-group">
<label>Fullname</label>
<input type="text" class="form-control" id="changename" name="changename" value="<?php echo $_SESSION['name'] ?>">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="changepass" name="changepass" value="<?php echo $_SESSION['pass'] ?>">
</div>
<button class="btn btn-default" id="changeuserinfo">Update</button>
</form>
Here is my jquery code:
$(document).ready(function(){
$('#changename').focus();
$('#changeuserinfo').click(function(){
var changename = $('#changename');
var changepass = $('#changepass');
var changeuserinfo_result = $('#changeuserinfo_result');
changeuserinfo_result.html('loading...');
if(changename.val() == ''){
changename.focus();
changeuserinfo_result.html('<span class="errorss"> * Empty fullname</span>');
return false;
}
else if(changepass.val() == ''){
changepass.focus();
changeuserinfo_result.html('<span class="errorss">* Empty password</span>');
return false;
}
else {
var UrlToPass = {changename:changename.val(),changepass:changepass.val()} ;
$.ajax({
type : 'POST',
cache: false,
data : UrlToPass,
url : 'changeuserinfo.php',
success: function(responseText){
if(responseText == 1){
$('#changeuserinfo_result').html('<span style="color:green"> Update OK</span>');
}
else{
$('#changeuserinfo_result').html('<span class="errorss"> Update fail. Try again</span>');
}
}
});
}
});
});
You have no closing tags on your inputs.
It should be <input type="text"... />
Also set the doctype of the page to HTML5.
<!DOCTYPE HTML>
....
</html>

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()

Return false on Ajax form not working

I have a form in that evaluates information in the database on my process page and returns errors if necessary. I'm using Ajax so it shouldnt actually be going to the process page and loading what I have encoded in Json to return. Here is my form plus Javascript:
<form method="post" action="../user/process_login" id="login_form">
<input type="hidden" name="action" value="login">
<label>Email Address:</label>
<input type="text" id="email" name="email" placeholder="Email" />
<label>Password:</label>
<input type="password" id="password1" name="password0" placeholder="Password" />
<input type="submit" id="submitbtn" placeholder="Submit" class="button"/>
</form>
Javascript:
<script type="text/javascript">
$(document).ready(function(){
$('#login_form').submit(function(){
$.post
(
$(this).attr('action'),
$(this).serialize(),
function(data){
if (data['errors'] == '') {
consle.log(data);
};
else{
console.log(data);
$('#alert_box').html(data);
};
},
"json"
);
return false;
});
});
</script>
Here is the relevant section of my validation code:
if (count($user) > 0 AND $decrypted_password == $this->input->post('password0'))
{
$this->session->set_userdata('user_session', $user);
$this->load->view('main.php');
}
else
{
$errors = "<div class='alert-box alert' id='error-box'><p>Your login information did not match our reccords. Try again</p></div>";
echo json_encode($errors);
}
I think it's because there is an error in your code. I point it out below
Here is without the error ----> WITHOUT ERRORS
Here is with the Error -----> WITH ERRORS
As you can see the return false does work without errors.
<script type="text/javascript">
$(document).ready(function(){
$('#login_form').submit(function(){
$.post
(
$(this).attr('action'),
$(this).serialize(),
function(data){
if (data['errors'] == '') {
consle.log(data);
}; <----------------------- Error Not supposed to be there
else{
console.log(data);
$('#alert_box').html(data);
}; <----------------------- I think will still work but don't need
},
"json"
);
return false;
});
});
</script>
You can't use input type submit, while calling an Ajax function, if you use it, your code will not work as expected, so change it to:
<input type="button" id="submitbtn" placeholder="Submit" class="button"/>

can not call any other function, then die my code

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();

Categories