My php vairables are not working properly beacuse of jQuery - php

Whenever I hit submit button my first name, last name and email are empty even when they are filled up properly so they return red color fonts.
Here is the PHP code:
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$college = mysqli_real_escape_string($conn, $_POST['college']);
$pwd = mysqli_real_escape_string($conn, $_POST['password']);
// Error handlers
$errorfirst=false;
$erroremail=false;
$errorlast=false;
$errorpwd=false;
// Check for empty fields
if (empty($first) || empty($email) || empty($pwd)) {
echo "
<span class='form-error'>*Please check one of the fields before submitting<br></span>
<span class='form-error'>*Please check first name <br></span>
<span class='form-error'>*Please check last name <br></span>
<span class='form-error'>*Please check email <br></span>
";
$errorfirst=true;
$erroremail=true;
} else {
// Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
echo "<span class='form-error'>*write properly</span>";
$errorfirst=true;
$errorlast=true;
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>*write a proper email</span>";
} else {
$sql = "SELECT * FROM name WHERE user_email='$email'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
echo "<span class='form-error'>This E-mail ID is already existed</span>";
} else {
//Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
// Insert the user into the database
$sql = "INSERT INTO name (id,user_first, user_last, user_email, user_uid, user_pwd) VALUES (NULL,'$first', '$last', '$email', '$uid', '$hashedPwd');";
mysqli_query($conn, $sql);
}
}
}
}
} else {
header("Location: ../signupform.php");
exit();
}
?>
<script type="text/javascript">
$('.first-input,.last-input,.email-input').removeClass('input-error');
var errorfirst="<?php echo '$errorfirst'; ?>";
var errorlast="<?php echo '$errorlast'; ?>";
var erroremail="<?php echo '$erroremail'; ?>";
if (errorfirst==true) {
$('.first-input').addClass('input-error');
}
if (errorlast==true) {
$('.last-input').addClass('input-error');
}
if (erroremail==true) {
$('.email-input').addClass('input-error');
}
if (erroremail==false && errorfirst==false && errorlast==false) {
$('.first-input,last-input,.email-input').val('');
}
</script>
It is not sending any value to the database. I used jQuery to validate form without refreshing but I think because of jQuery my form is not working
Here is my jQuery code
<script>
$(document).ready(function () {
$('.signup-Form').submit(function(event){
event.preventDefault();
var first=$(".first-input").val();
var last=$(".last-input").val();
var email=$(".email-input").val();
var college=$(".college-input").val();
var password=$(".password-input").val();
var submit=$(".signup-btn").val();
$(".form-message").load("includes/signup.inc.php", {
first:first,
last:last,
email:email,
college:college,
password:password,
submit:submit
})
});
});
</script>
And here is my HTML form
<form class="signup-Form" action="includes/signup.inc.php" method="post">
<div class="first-input">
<input type="text" name="first" placeholder="First Name">
</div>
<div class="last-input">
<input type="text" name="last" value="" placeholder="Last Name">
</div>
<div class="email-input">
<input type="text" name="email" value="" placeholder="E-mail">
</div>
<div class="college-input">
<input type="text" name="college" value="" placeholder="College Name">
</div>
<div class="password-input">
<input type="password" name="password" value="" placeholder="Password">
</div>
<p class="form-message"></p>
<div class="signup-btn">
<button type="submit" name="button">sign-up</button>
</div>
</form>
Help me over this issue and I also don't know about security in PHP forms so you can aslo suggest me some tips over that, I will really appreciate because I am want to be a professional back-end developer and now I am a newbie

Your jQuery uses $(".first-input").val(), but you have class="first-input" on the DIV, not the input.
Either move the class attribute to the inputs, or change the selector to $(".first-input input").val() (and similarly for all the other inputs).

You need to grab the input, not the container
<form class="signup-Form" action="includes/signup.inc.php" method="post">
<div class="first-input">
<input id="first-input" type="text" name="first" placeholder="First Name">
</div>
<div class="last-input">
<input id="last-input" type="text" name="last" value="" placeholder="Last Name">
</div>
<div class="email-input">
<input id="email-input" type="text" name="email" value="" placeholder="E-mail">
</div>
<div class="college-input">
<input id="college-input" type="text" name="college" value="" placeholder="College Name">
</div>
<div class="password-input">
<input id="password-input" type="password" name="password" value="" placeholder="Password">
</div>
<p class="form-message"></p>
<div class="signup-btn">
<button id="signup-btn" type="submit" name="button">sign-up</button>
</div>
</form>
<script>
$(document).ready(function () {
$('.signup-Form').submit(function(event){
event.preventDefault();
var first=$("#first-input").val();
var last=$("#last-input").val();
var email=$("#email-input").val();
var college=$("#college-input").val();
var password=$("#password-input").val();
var submit=$("#signup-btn").val();
$(".form-message").load("includes/signup.inc.php", {
first:first,
last:last,
email:email,
college:college,
password:password,
submit:submit
})
});
});
</script>

Related

What's wrong with my AJAX and PHP whern I call it to login?

I have some trouble with my login form using ajax and php, could somebody con solve this??
This is code html:
login.html
<div id="id01" class="modal">
<form class="modal-content animate" action="" method="POST" id="login-form">
<div class="container">
<label for="login-email"><b>Username</b></label>
<input type="text" placeholder="Enter Email" id="login-email" name="login-email" required>
<label for="login-password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" id="login-password" name="login-password" required>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label><br>
<span id="showError"></span>
<button type="submit" id="btn-login" name="btn-login">Login</button>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancel-btn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
<script>
$(document).ready(function(){
$("#btn-submit").click(function{
var login-email = $("#login-email").val();
var login-password = $("#login-password").val();
var error = $("#showError");
if(login-email != "" && login-password != ""){
$.ajax({
url: "checkLogin.php",
type: "POST",
data: { login-email: login-email, login-password: login-password},
success: function(response){
var msg = "";
if(response == "success"){
window.location = 'profile.php';
} else {
msg = "Tên đăng nhập hoặc mật khẩu không chính xác.";
}
$('#id01').css({"display": "block"});
error.html(msg);
}
});
} else {
error.html("Email đăng nhập hoặc mật khẩu không được bỏ trống.");
return false;
}
});
});
</script>
and this is code php
login.php
if(isset($_POST["btn-login"])){
$email = trim($_POST["login-email"]);
$password = trim($_POST["login-password"]);
$sql_login = "SELECT email, password, permission FROM users where email='$email' and password='$password'";
$db->query($sql_login);
$rows = $db->findOne();
$permission = $rows['permission'];
if($rows['email'] == $email && $rows['password'] == $password){
echo "success";
} else {
echo "fail";
}
exit();
}
It seem to be not to load into ajax and php code cause i've try so many time but i didn't know the bugs in here.
you call checkLogin.php but the code php is in login.php
In the login.php code, you check the btn-login but the post data from client have no btn-login
{ login-email: login-email, login-password: login-password}
so the if block will never work.
if(isset($_POST["btn-login"])){
...
}
you can change like this
if(isset($_POST["login-email"]) && isset($_POST["login-password"])){
...
}
It appears at first glance that your jQuery is referencing btn-submit but your html defines this as btn-login instead.

if statement not working inside ajax

I'm trying to redirect a user after he presses a sign-in button. So it happens, and the if condition is not met, and the data itself is correct with no extra characters and contains a single one "A". for some reason it won't work.
I have tried to use the trim() function but to no avail.
Here is my code:
$("#login").click(function(event){
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url: "login.php",
method: "POST",
data: {userLogin: 1, userEmail:email, userPassword:pass},
success: function(data){
if(data!= "A"){
alert(data);
}else{
window.location.href="profile.php";
}
}
})
})
And this is the PHP:
<?php
include 'connection/connect.php';
session_start();
if(isset($_POST["userLogin"])){
$email = mysqli_real_escape_string($con, $_POST["userEmail"]);
$password = md5($_POST["userPassword"]);
$sql = "SELECT * FROM user_info WHERE email = '$email' AND password = '$password'";
$run_query = mysqli_query($con, $sql);
$count = mysqli_num_rows($run_query);
if($run_query===false){
echo mysqli_error($con);
}
elseif ($count == 1){
$row = mysqli_fetch_array($run_query);
$_SESSION["uid"] = $row["user_id"];
$_SESSION["name"] = $row["first_name"];
echo trim("A");
}
}
?>
And the HTML:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<li>SignIn
<ul class="dropdown-menu">
<div style="width: 300px;">
<div class="panel panel-primary">
<div class="panel-heading">Login</div>
<div class="panel-heading">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" required />
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" required />
<p><br/></p>
Forgotten Password<input type="submit" class="btn btn-success" id="login" value="Login">
</div>
<div class="panel-footer" id="e_msg"></div>
</div>
</div>
</ul>
</li>
</body>
</html>
furthermore, when i go directly to the page "profile.php", the user is logged in. That means that the data is passed correctly.
What can be the problem? Thanks.
Edit, the alert prints "A".
try javascript trim() method to compare string.
if(data.trim()=="A"){
window.location.href="profile.php";
}else{
alert(data);
}

$_POST array is empty and I got undefined variable errors

Sorry to ask it again, but I checked almost all the q&a's on the topic and still couldn't solve it. Here is my form.php and creditform.php
Edit1.Changed the .get to .post
Edit2.I'm getting errors of undefined variable "name" "email" "address" "income" etc (in short for all of them) in creditform.php
What I want to do is just insert all the inputs into the table in db.
HTML
<!-- End crumbs-->
<div class="container wrap wow fadeInUp">
<div class="row">
<div class="col-sm-5 col-md-6 left-app">
<form id="form" action="php/creditform.php" method="post">
<input type="text" placeholder="Name" name="name" required>
<input type="email" placeholder="Email" name="email" required>
<input type="text" placeholder="Address" name="address" required>
<input type="number" placeholder="Monthly income before taxes" name="income" required>
<input type="number" placeholder="Amount Needed" name="amount_needed" required>
<input type="number" placeholder="Phone" name="phone" required>
<div class="row">
<div class="container">
<input type="submit" name="submit" value="Submit" class="button"></div></div>
<div id="result"></div>
</form>
</div>
<script>
$(document).ready(function($) {
'use strict';
$('#form').submit(function(event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = $(this).serialize();
$.post(url, datos, function(resultado) {
$('#result').html(resultado);
});
});
</script>
FORM.PHP
<?php
include('db.config.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $email = $address = $income = $amount_needed = $phone = '';
if(isset($_POST['submit'])){
$name = addslashes($_POST['name']);
$email = addslashes($_POST['email']);
$address = addslashes($_POST['address']);
$income = addslashes($_POST['income']);
$amount_needed = addslashes($_POST['amount_needed']);
$phone = addslashes($_POST['phone']);
// check form fields
if(empty($name)){
$error .= 'Enter name <br />';
}
if(empty($email)){
$error .= 'Enter email <br />';
}
// check if errors exist
if(!empty($error)){
echo $error;
} else {
// process form as normal
$sql = "INSERT INTO `" . DBN . "`.`creditapp` (`name`, `email`, `address`, `income`, `amount_needed`, `phone`) VALUES ('$name', '$email', '$address', '$income', '$amount_needed', '$phone')";
$db->Query($sql);
}
}
}
print_r($_POST);
?>
CREDITFORM.PHP
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$address = $_POST['address'];
$income = $_POST['income'];
$amount_needed = $_POST['amount_needed'];
$phone = $_POST['phone'];
}
print_r($_POST);
?>
It's obvious that I'm missing something, please correct me...
Thanks for your time
You need to send a POST request for the $_POST array to have anything in it.
$.get(url, datos, function(resultado) {
$('#result').html(resultado);
});
This sends a GET request (check $_GET). You want to use $.post here instead.
$.post(url, datos, function(resultado) {
$('#result').html(resultado);
});
Here is a simple Ajax call to a Php File by an event : Click on a button.
In your example you must use POST method because you use :
$_POST['something'];
Javascript client side :
$("body").on("click", "#mybutton", function() {
var mydata = $("#form").serialize();
$.ajax({
type: "POST",
url: "/api/api.php",
data: {data : mydata},
timeout: 6e3,
error: function(a, b) {
if ("timeout" == b) $("#err-timedout").slideDown("slow"); else {
$("#err-state").slideDown("slow");
$("#err-state").html("An error occurred: " + b);
}
},
success: function(a) {
var e = $.parseJSON(a);
if (true == e["success"]) {
$("#result").html(e['message']);
// here is what you want, callback Php response content in Html DOM
}
}
});
return false;
});
Next in your Php code simply do after any success function :
if ($result) {
echo json_encode(array(
'success' => true,
'msg' => "Nice CallBack by Php sent to client Side by Ajax Call"
));
}
Okay, I practiced more on ajax - json - php and in the end this was my solution and my latest code.
Thanks for all answers and suggestions. Hope this also helps to someone.
Still open to any kind of advice to improve.
<?php
include('db.config.php');
if(isset($_POST['submit'])){
$name = addslashes($_POST['name']);
$email = addslashes($_POST['email']);
$address = addslashes($_POST['address']);
$income = addslashes($_POST['income']);
$amount_needed = addslashes($_POST['amount_needed']);
$phone = addslashes($_POST['phone']);
// process form as normal
$sql = "INSERT INTO `" . DBN . "`.`creditapp` (`name`, `email`, `address`, `income`, `amount_needed`, `phone`) VALUES ('$name', '$email', '$address', '$income', '$amount_needed', '$phone')";
$db->Query($sql);
die();
<div class="container wrap wow fadeInUp">
<div class="row">
<div class="col-sm-5 col-md-6 left-app">
<form id="form" action="creditapp.php" method="post">
<input type="text" placeholder="Name" name="name" id="name" required>
<input type="email" placeholder="Email" name="email" id="email" required>
<input type="text" placeholder="Address" name="address" id="address" required>
<input type="text" placeholder="Monthly income before taxes" id="income" name="income" required>
<input type="text" placeholder="Amount Needed" name="amount_needed" id="amount_needed" required>
<input type="text" placeholder="Phone" name="phone" id="phone" required>
<div class="row">
<div class="container">
<input type="submit" name="submit" value="Submit" class="button sub"></div>
</div>
</form>
</div>
<script>
$(document).ready(function() {
$('.sub').click(function(e){
e.preventDefault();
var name = $('#name').val(),
email = $('#email').val(),
address = $('#address').val(),
income = $('#income').val(),
amount_needed = $('#amount_needed').val(),
phone = $('#phone').val();
$.ajax({
url: "creditapp.php",
type: "POST",
data: {
name: name,
email: email,
address: address,
income: income,
amount_needed: amount_needed,
phone: phone,
submit: "submit"
}
}).done(function(msg){
$('.right-info').html('<pre>' + msg + '</pre>');
})
})
});
</script>
The problem you are having is with your javascript. You wait for the submit and than you do an ajax GET request, you need a POST.
<script>
$(document).ready(function($) {
'use strict';
$('#form').submit(function(event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = $(this).serialize();
$.post(url, datos, function(resultado) {
$('#result').html(resultado);
});
});
</script>

form data saved in localstorage and post to php

I am working on a simple login form for a mobile site that will save the form data in local storage but will also post data to a php file for url redirection with appended form data. I need help as the storage is working but the post for this is not.
Html
<form class="form-signin" action="siteurl/processing/login-app.php" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" class="input-block-level" placeholder="Eventname" id='eventname'>
<input type="text" class="input-block-level" placeholder="Username" id='username'>
<input type="password" class="input-block-level" placeholder="Password" id="password">
<label class="checkbox">
<input type="checkbox" value="remember-me" id="remember_me"> Remember me
</label>
<button class="btn btn-large btn-primary" type="submit">Sign in</button>
</form>
Now the script
<script>
$(function() {
if (localStorage.chkbx && localStorage.chkbx != '') {
$('#remember_me').attr('checked', 'checked');
$('#username').val(localStorage.usrname);
$('#pass').val(localStorage.pass);
} else {
$('#remember_me').removeAttr('checked');
$('#username').val('');
$('#pass').val('');
}
$('#remember_me').click(function() {
if ($('#remember_me').is(':checked')) {
// save username and password
localStorage.usrname = $('#username').val();
localStorage.pass = $('#pass').val();
localStorage.chkbx = $('#remember_me').val();
} else {
localStorage.usrname = '';
localStorage.pass = '';
localStorage.chkbx = '';
}
});
});
</script>
And the php
<?php
if (isset($_POST["eventname"]) && isset($_POST["username"]) && isset($_POST["password"])) {
$eventname = $_POST["eventname"];
$username = $_POST["username"];
$password = $_POST["password"];
$url = "siteurl/index.php/$eventname?user=$username&passw=$password";
header( "Location: $url" ) ;
} else {
echo "Username and Password not found";
}
?>
What am I missing?
Your POST variables work off the input names, not ids.
Add a name attribute to your inputs and access them.

Problem with form validation

Im using jquery valid8 plugin to validate a register form. problem is i cant get the unique user name check to work.
Register.php code
<?php include ("db.php"); ?>
<script src='js/jquery-1.4.2.min.js' type='text/javascript'></script>
<script src="js/jquery.valid8.js" type="text/javascript" charset="utf-8"></script>
<?php
$username = mysql_real_escape_string($_POST['username']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$act=isset($_GET['act'])?$_GET['act']:"";
if($act=='sub'){
$result = mysql_query ("INSERT INTO users (username, email, password) VALUES ('".$username."','".$email."','".$password."')") or die (mysql_error());
echo "Data Updated";
}
?>
<form class="form_user" method="post" action="register.php?act=sub">
<section>
<label for="user">
Username
</label>
<div>
<input type="text" tabindex="1" class="input" id="inputUsername" name="username" onblur="check(this)" value="" />
</div>
</section>
<!--#-->
<section>
<label for="user_mail">
Email
</label>
<div>
<input type="text" tabindex="2" class="input" id="inputEmail" name="email" value="" />
</div>
</section>
<!--#-->
<section>
<label for="pass">
Password
</label>
<div>
<input type="password" tabindex="3" class="input" id="inputPassword" name="password" value="" />
</div>
</section>
<!--#-->
<section>
<label for="pass">
Re-type Password
</label>
<div>
<input type="password" tabindex="4" class="input" id="inputConfirmPassword" name="password" value="" />
</div>
</section>
<!--#-->
<br />
<input type="submit" tabindex="5" id="buttonSignup" value="Regisiter" />
</form>
</div>
</div>
</section>
<script type="text/javascript">
// <![CDATA[
$(document).ready(function(){
// Set focus to first input
$('#inputUsername').focus();
// Custom validator (checks if password == confirm password)
function confirmPassword(args){
if(args.password == args.check)
return {valid:true}
else
return {valid:false, message:'Passwords does not match'}
}
// Username is required
$('#inputPassword, #inputUsername').valid8();
// Confirm password must match Password
$('#inputConfirmPassword').valid8({
regularExpressions: [
{expression: /^.+$/, errormessage: 'Required'}
],
jsFunctions:[
{ 'function': confirmPassword, 'values': function(){
return {password: $('#inputPassword').val(), check: $('#inputConfirmPassword').val()}
}}
]
});
$('#inputUsername').valid8({
regularExpressions: [
{expression: /^.+$/, errormessage: 'Required'}
],
ajaxRequests: [
{ url: 'class/isUsernameUnique.php'}
]
});
$('#inputPolicy').valid8();
$('#inputEmail').valid8({
regularExpressions: [
{expression: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel.ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|.fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|.il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\b$/, errormessage: 'You sure it is valid? The next step in this registration will be sent to the email you enter here.'}
]
});
// Check if all input fields are valid
$('#buttonSignup').click(function(){
alert('Are input fields valid? ' + $('input').isValid());
});
});
// ]]>
</script>
<span id="msgbox" ></span>
isUsernameUnique.php Code
<?php
include ("../db.php");
$username = $_GET['username'];
if(!isUsernameUnique($username)){
$json["valid"] = false;
$json["message"] = 'username is already in use';
}
else {
$json["valid"] = true;
}
function isUsernameUnique($username){
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
$result = mysql_num_rows($query);
if ($result > 0) {
$vl = '0';
}
if ($result < 1){
$vl = '1';}
return ($vl);
}
print json_encode($json);
?>
results always comes out "TRUE" (username avalable). where did i do wrong
Link to valid8: http://unwrongest.com/projects/valid8/
try this
function isUsernameUnique($username){
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
$result = mysql_num_rows($query);
if ($result == 0)
{
$vl = 0;
}
else
{
$vl = 1;
}
return $vl;
}
and let me know if that makes a differance.
This helped me:
Change:
$username = $_GET['username'];
To:
$username = $_POST['value'];
Variable name is value

Categories