Check captcha does not work - php

Help please deal with CAPTCHA. At me all is normal it is drawn, through Ajax the entered code is sent to file insert.php where at me the form handler. But the check does not work there. What do not enter in the input field, everything is considered correct
My form and ajax
<form action="/data/insert.php" method="POST" id="guest-form" name="reg">
<input id="username" type="text" name="name" placeholder="Username">
<input id="email" type="text" name="email" placeholder="E-mail">
<textarea id="message" type="text" name="text" placeholder="Your message"></textarea>
<img src="data/captcha.php" alt="Картинка" /><br />
<input id ="captcha" type="text" name="captcha" /><br />
<input id="submit" class="btn btn-default" type="button" value="Submit">
</form>
Ajax
$(document).ready(function() {
$('#submit').click(function() {
var username = $('#username').val();
var email = $('#email').val();
var message = $('#message').val();
var captcha = $('#captcha').val();
if(username || email || message || captcha === ''){
alert('Please input data in all fields');
}
else{
$.ajax({
type: "POST",
cache: false,
url: '/data/insert.php',
data: {username: username, email: email, message: message, captcha: captcha},
success: function(data) {
}
});
}
});
});
The php handler
require_once 'db.php';
require_once 'captcha.php';
session_start();
if (isset($_SESSION["captcha"]) && $_SESSION["captcha"]===$_POST["captcha"]){ echo "Текст введен верно"; }
else {
echo "Текст введен не верно";
}
unset($_SESSION["captcha"]);
if (isset($_POST['username']) && isset($_POST['email']) && isset($_POST['message'])){
$username = $_POST['username'];
$email = $_POST['email'];
$message = $_POST['message'];
$db_host = "localhost";
$db_user = "alekspvn"; // Логин БД
$db_password = "123"; // Пароль БД
$db_table = "book"; // Имя Таблицы БД
$connect_db=mysql_connect(HOST, MYSQL_USER, MYSQL_PASS)
or die("No connection with SQL");
mysql_select_db("guests_db",$connect_db);
mysql_query("SET NAMES 'utf8'",$connect_db);
$result = mysql_query ("INSERT INTO ".$db_table." (username,email,message) VALUES ('$username','$email','$message')");
if ($result = 'true'){
echo "Информация занесена в базу данных";
}else{
echo "Информация не занесена в базу данных";
}
}
?>

Related

using ajax to login with php

I am trying to use window.location = "userpage.php"; after a successful login but the page does not redirect.
I am using Ajax and a modal form in my code
Everything works fine. I don't get any errors. I check the network headers. and there is no response in the network
I have not been able to figure out the issue.
I have tried
window.location.href
window.location.replace.
Nothing is working
need help
Thanks
This is part of the js file
$("#loginform").submit(function(event) {
//prevent default php processing
event.preventDefault();
//collect user inputs
var datatopost = $(this).serializeArray();
//send them to login.php using AJAX
$.ajax({
url: "login.php",
type: "POST",
data: datatopost,
success: function(data) {
if (data == "success") {
window.location = "user_page.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 part of my login.php file
//Start session
session_start();
//Connect to the database
include("connection.php");
...
$email = mysqli_real_escape_string($conn, $email);
$password = mysqli_real_escape_string($conn, $password);
$password = hash('sha256', $password);
//Run query: Check combinaton of email & password exists
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password' AND activation='activated'";
$result = mysqli_query($conn, $sql);
if (!$result) {
echo '<div class="alert alert-danger">Error running the query!</div>';
exit;
}
//If email & password don't match print error
$count = mysqli_num_rows($result);
if ($count !== 1) {
echo '<div class="alert alert-danger">Wrong Username or Password</div>';
} else {
//log the user in: Set session variables
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
if (empty($_POST['remember'])) {
echo "success";
} else {
// todo logic for remember me
}
}
This is the form modal
//Start session
session_start();
//Connect to the database
include("connection.php");
...
<form method="post" class="login_form modal" id="loginform">
<div class="form-body">
<div class="form-head"><h3>Login form</h3></div>
<div class="form-logo"><img src="/dist/img/logo.svg" alt="" /></div>
<div id="loginmessage"></div>
<div class="form-inputs">
<p><input type="email" name="email" placeholder="email" /></p>
<p><input type="password" name="password" placeholder="Password" /></p>
</div>
<div class="login-session">
<div class="remember">
<input type="checkbox" id="remember" name="remember" value="remember" />
<label for="remember">Remember me</label>
</div>
<div class="">
Forgot my password
</div>
</div>
<div class="form-submit">
<input class="btn btn-primary" type="submit" value="log in"/>
<a class="btn btn-small" href="#signupform" rel="modal:open">register</a>
</div>
</div>
</form>
I finally found the solution to the issue.
In the index.js file:
success: function(data) {
if (data == "success") {
window.location = "user_page.php";`
was changed to:
success: function(data) {
if ($.trim(data) == "success") {
window.location = "user_page.php";`
Because the response message success for some reason had whitespace in it. I trimmed all whitespace and it worked.

PHP echoing JQuery on failed form submit

I'm working on a signup form in PHP. The form is a div which opens when you click on a button. Here's my code:
if(!$fieldsFilled){
$unfilledFormsError = '<br><font class="text-error" id="unfilled-forms-error">One of more of the fields are empty.</font><br>';
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
console.log('test passed');
});
</script>";
}
This all executes after my form is submitted:
if (isset($_POST['signUp']))
Full PHP code:
<?php require 'dbconnect.php'; ?>
<?php
//Error message variable declarations
$unmatchedPasswordsError = "";
$unfilledFormsError = "";
$emailError = "";
//If sign up submit POST recieved
if (isset($_POST['signUp']))
{
//Start session
session_start();
$email = $connection->real_escape_string($_POST['suEmail']);
$result = mysqli_query($connection, "SELECT * FROM users WHERE email='".$email."'");
if ($result->num_rows)
{
$emailInUse = true;
}
else
{
$emailInUse = false;
}
//Search for empty fields
$required = array('suFirstName', 'suLastName', 'suEmail', 'suPassword', 'suVerifyPassword', 'suDisplayName');
$fieldsFilled = true;
foreach($required as $field)
{
if (empty($_POST[$field]))
{
$fieldsFilled = false;
}
else
{
$fieldsFilled = true;
}
}
if ($emailInUse)
{
$emailError = "The email is already in use.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
if(!$fieldsFilled)
{
$unfilledFormsError = '<br><font class="text-error" id="unfilled-forms-error">One of more of the fields are empty.</font><br>';
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
console.log('test passed');
});
</script>";
}
else
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailError = "The email is not valid.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
//Check for unverified password
if ($_POST['suPassword']!= $_POST['suConfirmPassword'])
{
$unmatchedPasswordsError = "The passwords do not match.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
//Variable declaration for sign up POST values
$suFirstName = $_POST['suFirstName'];
$suLastName = $_POST['suLastName'];
$suEmail = $_POST['suEmail'];
$suPassword = $_POST['suPassword'];
$suDisplayName = $_POST['suDisplayName'];
//Insert POST values into database
$sql = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
//Redirect to 'email sent' webpage
header('Location: emailSent.php');
}
}
}
}
}
//If log in submit POST recieved
if (isset($_POST['logIn']))
{
//Variable declaration for log in POST values
$liEmail = $_POST['liEmail'];
$liPassword = $_POST['liPassword'];
//Search for log in credentials in dabase
$result = $connection->query("select * from users where email = '$liEmail' AND password = '$liPassword'");
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
//TODO: CHECK FOR REMEMBER ME CHECK
session_start();
$_SESSION['userID'] = $row['userID'];
}?>
HTML sign up div/form code:
<!-- Sign Up Box -->
<div class="sign-up-box" id="home-sign-up-box">
<img src="images/icons/x-close.png" class="x-close" id="home-sign-up-close" src="x-close">
<font class="subheader-bold font-raleway" id="box-sign-up-text">Sign Up</font>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input" value="<?php if(isset($_POST['suFirstName'])){echo $_POST['suFirstName'];}?>">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input" value="<?php if(isset($_POST['suLastName'])){echo $_POST['suLastName'];}?>">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input"value="<?php if(isset($_POST['suEmail'])){echo $_POST['suEmail'];}?>">
<?php
echo '<br><font class="text-error" id="email-error">',$emailError,'</font>';
?>
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<?php
echo '<br><font class="text-error" id="passwords-unmatched-error">',$unmatchedPasswordsError,'</font>';
?>
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input" value="<?php if(isset($_POST['suDisplayName'])){echo $_POST['suDisplayName'];}?>">
<?php
echo $unfilledFormsError;
?>
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<font class="text-minor" id="agree-tos-pp-text">By signing up, you agree to our terms of service and <br>privacy policy.</font>
</div>
The "test passed" does log to the console, however the div is not showing after the page refresh (due to form submission). Any help is appreciated! Thank you so much!
I have customized as your requirement and database connection i have used
Mysqli replace whatever you want also change database credentials.
Full code will be in same page. Try and comment if you don't understand anything.
<?php
session_start();
//require 'dbconnect.php';
$connection=mysqli_connect("localhost","root","","test"); // I have use it for testing
$errors = array();
if (isset($_POST['signUp'])) {
$email = mysqli_real_escape_string($connection, $_POST['suEmail']);
$result = mysqli_query($connection, "SELECT * FROM users WHERE email='".$email."'");
//email check
if(mysqli_num_rows($result)>0){
$errors[] = "The email is already in use.";
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors[] = "The email is not valid.";
}
//Search for empty fields
$required = array('suFirstName', 'suLastName', 'suEmail', 'suPassword', 'suConfirmPassword', 'suDisplayName');
foreach($required as $field){
if (empty($_POST[$field])){
$errors[] = $field." Cannot be empty.";
}
}
if(count($errors)==0){
if($_POST['suPassword']!=$_POST['suConfirmPassword']){
$errors[] = "The passwords do not match.";
}else{
$suFirstName = $_POST['suFirstName'];
$suLastName = $_POST['suLastName'];
$suEmail = $_POST['suEmail'];
$suPassword = $_POST['suPassword'];
$suDisplayName = $_POST['suDisplayName'];
//$sql = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
$sql = mysqli_query($connection, "INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
if($sql){
header('Location: emailSent.php');
}else{
$errors[] = "Failed to insert.";
}
}
}
}
if (isset($_POST['logIn'])){
$liEmail = $_POST['liEmail'];
$liPassword = $_POST['liPassword'];
//$result = $connection->query("select * from users where email = '$liEmail' AND password = '$liPassword'");
$result = mysqli_query($connection, "select * from users where email = '$liEmail' AND password = '$liPassword'");
if($result){
$row = mysqli_fetch_assoc($result);
$_SESSION['userID'] = $row['userID'];
}
}
?>
<?php
if(!empty($errors)){
foreach ($errors as $value) {
echo "<span style='color:red;'>".$value."</span><br>";
}
}
?>
<button type="button" id="showSignup">Show Sign-up</button><br><br>
<!-- Sign Up Box -->
<div class="sign-up-box" id="home-sign-up-box">
<img src="images/icons/x-close.png" class="x-close" id="home-sign-up-close" src="x-close">
<font class="subheader-bold font-raleway" id="box-sign-up-text">Sign Up</font>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input" value="<?php if(isset($_POST['suFirstName'])){echo $_POST['suFirstName'];}?>">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input" value="<?php if(isset($_POST['suLastName'])){echo $_POST['suLastName'];}?>">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input"value="<?php if(isset($_POST['suEmail'])){echo $_POST['suEmail'];}?>">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input" value="<?php if(isset($_POST['suDisplayName'])){echo $_POST['suDisplayName'];}?>">
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<font class="text-minor" id="agree-tos-pp-text">By signing up, you agree to our terms of service and <br>privacy policy.</font>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
<?php if(isset($_POST['signUp']) && count($errors)>0){ ?>
$('#home-sign-up-box').show();
<?php }elseif(isset($_POST['signUp']) && count($errors)==0){ ?>
//$('#home-sign-up-box').hide();
<?php }else{?>
//$('#home-sign-up-box').show();
<?php }?>
$("#showSignup").click(function(){
$('#home-sign-up-box').toggle();
visible_check();
});
visible_check();
});
function visible_check(){
var isVisible = $( "#home-sign-up-box" ).is( ":visible" );
if(isVisible){
$("#showSignup").html("Hide Sign-up");
}else{
$("#showSignup").html("Show Sign-up");
}
}
</script>

Inserting the image name into the database using file upload method

I had previously mentioned about my registration code. I now want to save the image name into the database.The image is to be uploaded using file upload. The validation is done using jquery and the form has to be submitted using ajax.Now i had read that file uploads cannot be performed using ajax.And that is the problem with my code.
Following is my code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
function ValidateEmail(email) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)| (([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
};
$(document).ready(function(){
$('#submit').on('click', function() {
//e.preventDefault();
valid = true;
if ($('#name').val() == '') {
alert ("please enter your name");
//$('#errorMsg1').css('color','red');
//$('#errorMsg1').html('Please enter your name');
//document.getElementById("errorMsg1").innerHTML = "You must enter a name";
valid = false;
}
if ($('#email').val() == '') {
alert ("please enter your email");
//$('#errorMsg2').css('color','red');
//$('#errorMsg2').html('Please enter your emailid');
//document.getElementById("errorMsg2").innerHTML = "You must enter a email";
valid = false;
}
if (!ValidateEmail($("#email").val())) {
alert("Invalid email address.");
//document.getElementById("errorMsg2").innerHTML = "Invalid email address.";
}
if ($('#bday').val() == '') {
alert ("please enter your birth date");
//$('#errorMsg3').css('color','red');
//$('#errorMsg3').html('Please enter your birth date');
//document.getElementById("errorMsg3").innerHTML = "You must enter your birth-date";
valid = false;
}
if ($('#gender').val() == '') {
alert ("please select your gender");
//$('#errorMsg4').css('color','red');
//$('#errorMsg4').html('Please select your gender');
//document.getElementById("errorMsg4").innerHTML = "You must select your gender";
valid = false;
}
if ($('#image').val() == '') {
alert ("please select an image");
//$('#errorMsg5').css('color','red');
//$('#errorMsg5').html('Please select an image');
//document.getElementById("errorMsg5").innerHTML = "You must select an image";
valid = false;
}
});
return false;
$("#multiform").submit(function (e)
{
var formObj=$(this);
var formURL=formObj.attr("action");
var formData=new formData(this);
$ajax({
URL:formURL,
type:'POST',
data:formData,
mimeType:"multipart/form-data",
contentType:false,
cache:false,
processData:false,
success:function(data,textStatus,jqXHR){
},
error:function(jqXHR,textStatus,errorThrown){
}
});
e.preventDefault();
e.unbind();
}
);
return true;
$("#multiform").submit();
});
</script>
</head>
<body>
<form name="multiform" id="multiform" action="save_data.php" method="POST" enctype="multipart/form-data">
<h4>Name:</h4> <input type="text" name="name" id="name" autofocus>
<br><br>
<h4>E-mail:</h4> <input type="text" name="email" id="email" autofocus>
<br><br>
<h4>Birth-date:</h4> <input type="text" name="bday" id="bday" autofocus>
<br><br>
<h4>Gender:</h4>
<input type="radio" name="gender" id="gender" value="female" autofocus>Female
<input type="radio" name="gender" id="gender" value="male" autofocus>Male
<br><br>
Select Image:<input type="file" name="image" id="image"><br><br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
</body>
</html>
save_data.php:
<!DOCTYPE html>
<html>
<body>
<?php
error_reporting( E_ALL & ~E_NOTICE );
// define variables and set to empty values
$name = $email = $bday = $gender = $image="";
//$image=$_FILES["image"]["name"];
if(isset($_POST['submit'])){
$name = $_POST["name"];
$email = $_POST["email"];
$bday=$_POST["bday"];
$gender = $_POST["gender"];
$image =$_POST["image"];
$servername = "localhost";
$username = "mvs1";
$password = "";
$dbname="scootsy_categories";
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
$sql = "INSERT INTO user_details(name,email,bday,gender,image) VALUES ('$name','$email','$bday','$gender','$image')";
if ($conn->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
//if($name !="" || $email !="" || $bday !="" || $gender !="" || $image !="" )
//{
// $sql="DELETE FROM user_details where name='$name' || email='$email' || bday='$bday' || gender='$gender' || image='$image'";
//}
$conn->close();
}
echo "Successful";
?>
</body>
</html>
You can't save images into a database, but you can save the path url and before you save the image into a folder with php. For do this, you have to modify your ajax code and your php file because for do all this, we have to use $_FILES for extract the name, type, size and temp_folder for move it into a filder.
Rewrite your ajax code.
Get with $_FILES the properties of the file
<script type="text/javascript">
$('body').on('click','#submit', function() {
$.ajax({
type:'POST',
url:'save_data.php',
data: new FormData($('#your_id_form')[0]),
contentType:false,
cache:false,
processData:false,
success:function(upload) {
$('#multiform').html(upload):
}
});
});
</script>
<form id="your_id_form" method="POST" action="save_data.php">
<input type="name" placeholder="Your name">
<input type="file" name="file">
<input type="button" id="submit">
</form>
<div id="multiform"></div>
//save_data.php
$name = $_POST['name'];
$file_name = $_FILES['file'];
$file_size = $file_name['size'];
$file_type = $file_name['type'];
$file_tmp = $file_name['tmp_name'];
list($name,$type) = explode('/',$file_type);
$save_temp = $file_tmp;
//create a new folder named images into your root page
$new_path = 'images/'.$name.$type;
//we move the file from the temporal folder to a new folder
move_uploaded_file($save_temp, $new_path);
$file_url = 'images/'.$file_type;
$sql = "INSERT INTO database (name,file_url) VALUES ('$name', '$new_path')";
//do stuffs for connect your query to your database
echo 'Uploaded!';
?>

AJAX > PHP Log in not working

I'm trying to create a log in form using html > ajax > php, the problem is the php is not working, I don't know where is the problem, I think the ajax cannot execute my php file. I need help. Thanks in advance.
Here is my HTML code: my form and inputs are below
<form id="loginForm">
<input type="text" data-clear-btn="true" name="username" id="username" value="" placeholder="Username / ID No.">
<input type="password" data-clear-btn="true" name="password" id="password" value="" placeholder="Password">
<input type="checkbox" name="rem_user" id="rem_user" data-mini="true">
<label for="rem_user">Remember me</label>
<input type="submit" name="login" id="login" value="Log in" class="ui-btn" />
</form>
<div class="err" id="add_err"></div>
AJAX script that sends request on my php file
<script>
$(document).ready(function(){
$("#loginForm").submit(function(){
var username = $("#username").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is in database.
var dataString = 'username=' + username + '&password=' + password;
if (username == '' || password == ''){
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "php/login-action.php",
data: dataString,
success: function(result){
window.location="#report_page";
}
});
}
return false;
});
});
</script>
PHP File
<?php
require "includes/connection.php";
include "includes/function.php";
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = sanitize($username);
$password = sanitize($password);
$pass2 = md5($password);
$salt = "sometext";
$validateHash = $salt.$pass2;
$pass = hash("sha512", $validateHash);
$sql = "SELECT * FROM user_login WHERE username='".$username."' and password='".$password."'";
$result = mysqli_query($con,$sql) or die("Error: ". mysqli_error($con));
$count=mysqli_num_rows($result);
while($row=mysqli_fetch_array($result))
{
$id = $row['user_id'];
$username = $row['username'];
$name = "".$row['firstname']." ".$row['lastname']."";
$acc_type = $row['Acc_Type'];
}
if($count==1){
if($acc_type == 'user') {
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
$_SESSION["name"] = $name;
echo 'true';
}
else {
echo 'false';
}
}
}
?>
as Cattla mentioned in comments.
Your PHP is looking for $_POST['login'], and your $.ajax call didn't pass that in.
so here is the answer
var dataString = 'login=login&username=' + username + '&password=' + password;
Debug tips
Did ajax send all required inputs to PHP (you can inspect this from browser developer tool)
Did php receive all required inputs (you could var_dump($_POST)
Did php connect to mysql successfully
Did ajax receive data from PHP (use alert or console.log)
try this, and if you get error state what it is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#loginForm").submit(function(){
if (username == ' ' || password == ' '){
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "php/login-action.php",
data: $(this).serialize(),
success: function(result){
alert('sucess'); //window.location="#report_page";
}
});
}
return false;
});
});
</script>

Ajax to PHP form submission. Keep getting "parsererror"

ajaxSubmit.js:
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#reg').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
login : $('input#login').val(),
pass : $('input#pass').val(),
pass1 : $('input#pass1').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#reg').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text(textStatus).show(500);
$('#reg').show(500);
}
});
return false;
});
});
HTML Form:
<div id="message" style="display: none;">
</div>
<div id="waiting" style="display: none;">
Please wait<br />
<img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
<br />
</div>
<form id="reg" class="form with-margin" name="reg" method="post" action="">
<br />
<p class="inline-small-label">
<label for="login"><span class="big">Email</span></label>
<input type="text" name="login" id="login" value="">
</p>
<p class="inline-small-label">
<label for="pass"><span class="big">Password</span></label>
<input type="password" name="pass" id="pass" value="">
</p>
<p class="inline-small-label">
<label for="pass1"><span class="big">Password Again</span></label>
<input type="password" name="pass" id="pass1" value="">
</p>
<div align="center"><button type="submit" name="submit" id="submit" >Register</button></div>
</form>
<script type="text/javascript" src="js/ajaxSubmit.js"></script>
post.php:
<?php
sleep(3);
$login = $_POST['login'];
$pass = $_POST['pass'];
$pass1 = $_POST['pass1'];
$login = mysql_real_escape_string($login);
$pass = mysql_real_escape_string($pass);
$pass1 = mysql_real_escape_string($pass1);
if (empty($login)) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else if (empty($pass)) {
$return['error'] = true;
$return['msg'] = 'You did not enter you password.';
}
else if ($test == false) {
$return['error'] = true;
$return['msg'] = 'Please enter a correct email. This will be verified';
}
else if (empty($pass)) {
$return['error'] = true;
$return['msg'] = 'You did not enter you password twice.';
}
else if ($pass != $pass1) {
$return['error'] = true;
$return['msg'] = 'Your passwords dont match.';
}
else {
$return['error'] = false;
$return['msg'] = 'Thanks! Please check your email for the verification code!';
}
echo json_encode($return);
?>
Any ideas why I keep getting the parsererror?
you have a $test variable else if ($test == false) that is undefined.
I'd suggest that if you are having parse errors through ajax, that you just load up the .php file manually and then php will point you to the line that the error is occurring on.

Categories