I'm learning AJAX/JS and once the form has been submitted, I want AJAX to fire off the POST and return the data. This has been done and the data comes back OK and sucessfully, I just cannot get the 'alert' function to show. I get redirected to my process.php with the following:
{"success":false,"errors":{"email":"Email is required.","password":"Password is required."}}
I now need to get the above to display in an 'alert', such as alert('Password is required');
This is my 'process.js' form:
$(document).ready(function()
{
event.preventDefault();
$('form').submit(function(event)
{
var formData = {
'email' : $('input[email=email').val(),
'password' : $('input[password=password').val()
};
$.ajax({
type : 'POST',
url : 'ajax/proclogin.php',
data : JSON.stringify(formData),
dataType : 'json',
encode : true
})
// using the done promise callback
.done(function(data)
{
console.log(data);
if (!data.success)
{
if(data.errors.email)
{
//toastr.error(''+data.errors.email+'', 'Oops!');
alert('Email error');
}
if(data.errors.password)
{
//toastr.error(''+data.errors.password+'', 'Oops!');
alert('Password Error');
}
}
else
{
//toastr.success('Works!', 'WooHoo!');
alert('Works.');
}
});
});
});
This is the 'proclogin.php' file:
<?php
// proc(ess)login.php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables
======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['password']))
$errors['password'] = 'Password is required.';
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors process our form, then return a message
$connection = mysqli_connect("*****","****","****","*****");
$email = mysqli_real_escape_string($connection, $_POST['email']); # Define email field
$input = mysqli_real_escape_string($connection, $_POST['password']); # Define password field
$query = mysqli_query($connection, "SELECT `Email`, `Password` FROM users WHERE Email='$email' LIMIT 1"); # Query what we need
$row = mysqli_fetch_array($query); # Fetch what we need
$p = $row['Password']; # Define fetched details
$email = $row['Email']; # Define fetched details
if(password_verify($input, $p)) # Verify input password matches hashed password in the DB.
{
#It matches, let's set a session and redirect them to the dashboard.php page.
$_SESSION['SID'] = $email;
$data['success'] = true;
$data['message'] = 'Success';
}
else
{
$data['success'] = false;
$data['message'] = 'fail';
}
// show a message of success and provide a true success variable
}
// return all our data to an AJAX call
echo json_encode($data);
?>
You have event.preventDefault(); outside of your submit handler, it should be inside.
The selector you use to get the password and email seems wrong.
You're attempting to send JSON but trying to read form data.
$(document).ready(function(){
$('form').submit(function(event) {
event.preventDefault();// prevent the form from submitting normally
var formData = {
'email' : $('input[type=email').val(), // get the value of the email input
'password' : $('input[type=password').val() // get the value of the password input
};
$.ajax({
type : 'POST',
url : 'ajax/proclogin.php',
data : formData, // send as form data
dataType : 'json',
})
...
You need to check if isset the email or password then show the alert message like this:
.done(function(data) {
if(data.errors.email) {
alert('email required');
}
else if(data.errors.password) {
alert('password required');
}
else {
alert('done');
}
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
and remove the condition if (!data.success)
Related
I tried researching a lot before posting here.
There are two files login.php and login-validation.php
Login.php file contains code including login form and jQuery AJAX script to call login.validation.php
--- Code of login.php ---
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
mobile_no = $('#mobile_no').val();
upassword = $('#upassword').val();
console.log(mobile_no, upassword);
$.ajax({
type: "POST",
url: "server/login-validation.php",
data: {
Mobile_no: mobile_no,
Password: upassword
},
cache: false,
dataType:'json',
success: function(response) {
console.log("Data gone successfully");
if(response["type"] == 'LoginSuccess'){
$('#success-message').text(response); // This works but not below ones
}
if(response["type"] == 'WrongCredentials'){
$('#success-message').text(response);
}
else{
$('#success-message').text(response);
}
},
error: function(xhr, textStatus, errorThrown){
console.log(xhr.responseText); Shows my echo message i.e. Wrong credentials for wrong credentials
console.log(textStatus); // Shows parseError
console.log(errorThrown); // Shows SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
}
});
});
});
</script>
---Code of login.validation.php---
session_start();
$message = array(); //Creating array variable to display custom messages depending on [TYPE]
//Require DB
require_once('db.php');
//Get values from the login form
$Mobile_number = $mysqlconnect->real_escape_string(trim($_POST['Mobile_no']));
$Password = $mysqlconnect->real_escape_string(trim($_POST['Password']));
//Query database for valid input match
$validation = "SELECT * from team_captain WHERE Mobile_Number = '$Mobile_number'";
$query = $mysqlconnect->query($validation);
$result = mysqli_num_rows($query);
if($result > 0){
$fetch_pass = mysqli_fetch_array($query);
$password_hash = $fetch_pass['User_Password'];
if(password_verify($Password,$password_hash))
{
$message["type"] = 'LoginSuccess';
$_SESSION['sess_username'] = $fetch_pass['Full_Name'];
}
else{
$message["type"] = 'WrongCredentials';
echo "Wrong credentials". $mysqlconnect->error;
}
}
else{
$message["type"] = 'WrongMobile';
echo "Mobile number doesn't exists";
}
header('Content-type: application/json');
echo json_encode($message);
?>
Tried dataType: 'json' - Didn't work
Tried without dataType - Didn't work
Php script is running properly with right error messages for different "if" statements but AJAX responses goes to error:function() rather than success: function()
In the network tab - The response type is JSON and it displays [type] i.e [WrongCredentials]
Not understanding what is wrong here. Any help would be appreciated.
You need to parse the JSON response using jQuery.parseJSON()
var data = jQuery.parseJSON(response);
Now, you can check it
if(data.type == "LoginSuccess"){
// do something
}elseif(data.type == "Wrong Password"){
// do something else
}
And remove echo from your php code
session_start();
$message = array(); //Creating array variable to display custom messages depending on [TYPE]
//Require DB
require_once('db.php');
//Get values from the login form
$Mobile_number = $mysqlconnect->real_escape_string(trim($_POST['Mobile_no']));
$Password = $mysqlconnect->real_escape_string(trim($_POST['Password']));
//Query database for valid input match
$validation = "SELECT * from team_captain WHERE Mobile_Number = '$Mobile_number'";
$query = $mysqlconnect->query($validation);
$result = mysqli_num_rows($query);
if($result > 0){
$fetch_pass = mysqli_fetch_array($query);
$password_hash = $fetch_pass['User_Password'];
if(password_verify($Password,$password_hash))
{
$message["type"] = 'LoginSuccess';
$_SESSION['sess_username'] = $fetch_pass['Full_Name'];
}
else{
$message["type"] = 'WrongCredentials';
}
}
else{
$message["type"] = 'WrongMobile';
}
header('Content-type: application/json');
echo json_encode($message);
?>
I am trying to make a login page for a website. I have a function that uses AJAX to send a request to a PHP script to check if the proper username and password has been entered in. I send http_response_code(200) if the the query returns a successful result, otherwise I send http_response_code(403). However, the login function seems to not return any response status. The response seems to be undefined. In this case, the function gives me the window alert for the wrong password or username even if the correct password and username is entered. What condition should I be checking to determine what the success function should do based on the http response code? Is there another way to return a condition to AJAX based on what the PHP script does?
Here it the code for the login function.
function login(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var dataString = 'username1=' + username + '&password1=' + password;
if (username == '' || login == ''){
window.alert("Please fill in username or password.");
}
else{
$.ajax({
type: "POST",
url: "login.php",
data: dataString,
cache: false,
crossDomain : true,
success: function(response) {
if (response.status == 200) {
window.location = 'http://localhost/site.html';
}
else {
window.alert("The password or username you have entered is not valid");
}
}
});
}
return false;
}
Here is my php script.
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
$password2 = $_POST['password1'];
$username2 = $_POST['username1'];
$connection = mysqli_connect("localhost", "root", "password", "database") or die("Unable to connect to MySQL");
$query = mysqli_query($connection, "SELECT * FROM users where username = '$username2' AND password = '$password2'") or die(mysqli_error($connection));
$row = mysqli_fetch_array($query, MYSQLI_BOTH) or die(mysqli_error($connection));
if(!empty($row['username']) AND !empty($row['password'])) {
session_start();
$_SESSION['username'] = $username2;
http_response_code(200);
echo "Successful Login";
exit;
}
else{
http_response_code(403);
echo "The password or username you have entered is not valid";
}
mysqli_close($connection);
?>
When you check for the response and send the get response.status you do do not actually have an array or object as a response in your hands:
So when checking for the login you can create an array with status and a message and json_encode() it so you javascript code can pick it up and read it.
<?php
// fix your query connection - you are currently vulnerable. It does go outside of the scope of your question so I am not going to tackle it here.
if(!empty($row['username']) AND !empty($row['password'])) {
session_start();
$_SESSION['username'] = $username2;
$return = array(
'status' => 200,
'message' => "Login Successful."
);
http_response_code(200);
}
else{
$return = array(
'status' => 403,
'message' => "Login attempt denied."
);
http_response_code(403);
}
print_r(json_encode($return));
Now you can get the response back in your AJAX function:
success: function(response) {
var data = $.parseJSON(response);
if (data.status == 200) {
window.location = 'http://localhost/site.html';
}
else {
window.alert(data.message);
}
}
The response argument that you are using in the success function is the returned data from the AJAX call, not the status and/or headers. You can get a string describing the status by getting the second argument to the function:
$.ajax({
...
success: function(data, status){
if(status == "success"){
// success code.
}
}
});
View the jQuery.ajax docs for more information.
I want to make the form hide and a thank you message appear instead of it after the form is successfully submitted. I've done the below code but I cannot manage to get any action performed after the form is submitted .. it's like the 'if' function is ignored.
Below is my code:
JQuery:
$('form#contactform').submit(function(event) {
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val(),
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
//Done promise callback
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (! data.success == true) {
$('section#contact form#contactform').hide;
$('section#contact div.thxform').show;
} else {
alert("An internal error has occured");
}
});
//Stop form default action
event.preventDefault();
Php:
<?php
$errors = array(); //array to hold validation errors
$data = array(); //array to pass back data
//validate variables
if (empty($_POST['name']))
$errors['name'] = 'Name is required';
if (empty($_POST['email']))
$errors['email'] = 'E-Mail is required';
if (empty($_POST['subject']))
$errors['subject'] = 'Subject is required';
if (empty($_POST['message']))
$errors['message'] = 'Please enter a message';
//Return response
if ( ! empty($errors)) { //If there are errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
//Process form
$name = $_POST['name'];
$email = $_POST['email'];
$re = $_POST['subject'];
$message = $_POST['message'];
$from = 'info#jamescremona.com';
$to = 'jmscre#gmail.com';
$subject = 'Form submission';
$body = "From: $name\n E-mail: $email\n Subject: $re\n Message: $message\n";
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
$data['success'] = true;
$data['message'] = 'Form Submitted';
}
echo json_encode($data);
Any help would be greatly appreciated. Thanks.
First error I spotted on your code :
'message' : $("#msg").val(), that is your last item in your array therefore no need for the ',' javascript expect more items after','
You need to check all you js errors in the console, they are there.
then the second error I saw,
$('section#contact form#contactform').hide;
$('section#contact div.thxform').show;
show and hide does not exist in jquery they have show(); and hide(); then here : if (! data.success == true) {}
This is how your code should look :
<script type="text/javascript">
$('form#contactform').submit(function(event) {
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val()
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (!data.success) {
$('section#contact form#contactform').hide();
$('section#contact div.thxform').show();
//check which field was wrong and show the user
if(data.errors.name){
$('section#contact div.thxform').append(data.errors.name);
}
if(data.errors.email){
$('section#contact div.thxform').append(data.errors.email);
}
if(data.errors.subject){
$('section#contact div.thxform').append(data.errors.subject);
}
if(data.errors.message){
$('section#contact div.thxform').append(data.errors.message);
}
}else{
$('#successDIV').append(data.message);
}
}),
.fail(function(data){
//debugging puporses, all your php errors will be printed in the console
console.log(data);
});
//Stop form default action
event.preventDefault();
</script>
You need to tell the browser what to expect. So add the header function before your echo
header('Content-Type: application/json'); // this line here
echo json_encode($data);
UPDATE
Also your event.preventDefault(); comes last which should be the first thing you call after $('form#contactform').submit(function(event) { since you want to prevent stuff before the ajax call.
Also you PHP is echoing stuff in either case of the mail functions return value. So the json response is messed up, thus your ajax will not get proper data back.
UPDATE 2
I have the strong feeling that your PHP script is throwing errors of some sort. The mail function could be throwing a 530 error for example. So best you disable error displaying in your PHP script.
General advice for debugging this sort of stuff is web developer browser extensions to view request/response information.
Try this refactored code please:
ini_set('display_errors',0); // disable error displaying. Rather view in logs
$errors = array(); //array to hold validation errors
$data = array(); //array to pass back data
//validate variables
if (empty($_POST['name']))
$errors['name'] = 'Name is required';
if (empty($_POST['email']))
$errors['email'] = 'E-Mail is required';
if (empty($_POST['subject']))
$errors['subject'] = 'Subject is required';
if (empty($_POST['message']))
$errors['message'] = 'Please enter a message';
//Return response
if ( ! empty($errors)) { //If there are errors
$data['errors'] = $errors; // only necessary to set errors
} else {
//Process form
$name = $_POST['name'];
$email = $_POST['email'];
$re = $_POST['subject'];
$message = $_POST['message'];
$from = 'info#jamescremona.com';
$to = 'jmscre#gmail.com';
$subject = 'Form submission';
$body = "From: $name\n E-mail: $email\n Subject: $re\n Message: $message\n";
if (mail ($to, $subject, $body, $from)) {
$data['success'] = 'Your message has been sent!'; // store to $data instead of echo out
} else {
$data['errors'] = 'Something went wrong, go back and try again!'; // store to $data instead of echo out
}
}
header('Content-Type: application/json');
echo json_encode($data);
And your javascript snippet in the done function of the ajax call:
<script type="text/javascript">
$('#contactform').submit(function(event) {
event.preventDefault(); // note this one has to be at the beginning of your submit function since you do not want to submit
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val(),
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
//Done promise callback
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (data.success) { // success either exists or not
alert("Success! Form should hide now...");
$('#contactform').hide(); // an id is (should always) be unique. So you dont need this "section#contact form#contactform". It does not make sense. Also hide and show are functions and need brackets at the end
$('div.thxform').show();
} else { // then its an error
alert("An internal error has occured");
}
});
});
</script>
And the HTML i used to test this:
<form method="post" id="contactform">
Name <input type="text" name="name" value="test"><br>
Email <input type="text" name="email" value="test#localhost.com" ><br>
Subject <input type="text" name="subject" value="subject" ><br>
Message <textarea name="message" ></textarea><br>
<input type="submit">
</form>
Its because of 2 tiny mistakes:
[js code] Replace if (! data.success == true) with if (data.success == true).
[php code] add header('Content-Type: application/json'); before echoing $data
I guess the problem is here
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
because you echo a string and then a json object. Therefore when you treat data response on Javascript, it's not a json object.
Then I would do as follow in PHP
if (#mail($to, $subject, $body, $from)) {
$data['success'] = true;
$data['message'] = 'Form Submitted';
} else {
$data['success'] = false;
$data['message'] = 'Internal error';
}
echo json_encode($data);
and in Javascript
.done(function(data) {
if (typeof data !== 'object') {
alert('Expected data as object - '+typeof data+' received');
return;
}
data = jQuery.parseJSON(data);
//Errors and validation messages
if (data.success == true) {
$('section#contact form#contactform').hide;
$('section#contact div.thxform').show;
} else {
alert(data.message);
}
});
Note that the # operator before mail function will not generate error messages to avoid sending a string on Javascript.
This my signUp.php I dont know what is wrong here that prevents my form values from being inserted into the database
<?php
$errors = array();
$data = array();
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if(empty($_POST["full_Name"])){
$errors['full_Name'] = "Please fill in yor full name";
}
else{
$full_Name = test_Inputs($_POST['full_Name']);
//using regular expression to check if the name includes only letters and whitespaces
if(#!preg_match("/^[A-z\s]*$/", $full_Name)){
$errors['full_Name'] = "Only alphabets and whitespace";
}
}
if(empty($_POST['user_phoneNumber'])){
$errors['user_phoneNumber'] = "Mobile number is required";
}
else{
$mobileNumber = test_Inputs($_POST['user_phoneNumber']);
// using regex to make sure only numbers are inputted in the field
if(#!preg_match("/^[0-9]+$/", $mobileNumber)){
$errors['user_phoneNumber'] = "Only numbers allowed";
}
}
if(empty($_POST['user_Email'])){
$errors['user_Email'] = "Please fill in your email address";
}
else{
$Email = test_Inputs($_POST['user_Email']);
//using regex to validate email input
if(#!preg_match("/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/", $Email)){
$errors['user_Email'] = "Invalid Email address";
}
}
if(empty($_POST['userName'])){
$errors['userName'] = "User name field is blank";
}
else{
$userName = test_Inputs($_POST['userName']);
if(#!preg_match("/^[A-z0-9]+$/", $userName)){
$errors['userName'] = "Only letters and numbers allowed";
}
}
if(empty($_POST['password'])){
$errors['password'] = "Password field is blank";
}
else{
$password = test_Inputs($_POST['password']);
if(#!preg_match("/^[A-z0-9]+$/", $password)){
$errors['password'] = "Only letters and numbers allowed";
}
if(strlen($password) < 8){
$errors['password'] = "Password must be at least 8 characters long";
$valid = false;
}
}
if(empty($_POST['RPassword'])){
$errors['RPassword'] = "Confirm your password";
$valid = false;
}
else{
$RPassword = test_Inputs($_POST['RPassword']);
if($RPassword != $password){
$errors['RPassword'] = "Passwords do not match";
}
}
if(!isset($_POST['terms'])){
$errors['terms'] = "Agree to the terms";
}
else {
$Terms = test_Inputs($_POST['terms']);
}
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors process our form, then return a message
// Inserting into the database
require_once ('insert_user.php');
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Success!';
}
//return all our data on AJAX call
echo json_encode($data);
//creating the test_puts functions
function test_Inputs($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
This is my dbConn.php
<?php
$host = "localhost";
$db_name = "Interns";
$username = "root";
$password = "";
try {
$dbh = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $ex){
echo "Failed to connect" .$ex->getMessage();
}
this is my insertUser.php code
<?php
require_once ('dbConn.php');
$salt = "cH!swe!retR:";
If(isset($_POST['submit'])) {
try {
$stmt = $dbh->prepare("INSERT INTO Users(FullName, MobileNumber, Email, Username, Password)
VALUES(:user_name, :user_mobile, :user_email, :user_username, :user_pass)");
$stmt->bindParam(":user_name", $full_Name);
$stmt->bindParam(":user_mobile", $mobileNumber);
$stmt->bindParam(":user_email", $Email);
$stmt->bindParam(":user_username", $userName);
$stmt->bindParam(":user_pass", $password);
$full_Name = $_POST['full_Name'];
$mobileNumber = $_POST['user_phoneNumber'];
$Email = $_POST['user_Email'];
$userName = $_POST['userName'];
$password = SHA1(($_POST['password']), $salt);
$stmt->execute();
echo "Query successful";
} catch (PDOException $ex) {
echo "Query Failed" . $ex->getMessage();
}
}
$dbh = null;
This is my signUp.js
// signUpValidation.js
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'full_Name' : $('input[name=full_Name]').val(),
'user_phoneNumber' : $('input[name=user_phoneNumber]').val(),
'user_Email' : $('input[name=user_Email]').val(),
'userName' : $('input[name=userName]').val(),
'password' : $('input[name=password]').val(),
'RPassword' : $('input[name=RPassword]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'signUpValidation.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success) {
// handle errors for name ---------------
if (data.errors.full_Name) {
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#name-group').append('<div class="help-block">' + data.errors.full_Name + '</div>'); // add the actual error message under our input
}
// handle errors for email ---------------
if (data.errors.user_phoneNumber) {
$('#mobile-group').addClass('has-error'); // add the error class to show red input
$('#mobile-group').append('<div class="help-block">' + data.errors.user_phoneNumber + '</div>'); // add the actual error message under our input
}
// handle errors for superhero alias ---------------
if (data.errors.user_Email) {
$('#email-group').addClass('has-error'); // add the error class to show red input
$('#email-group').append('<div class="help-block">' + data.errors.user_Email + '</div>'); // add the actual error message under our input
}
if (data.errors.userName) {
$('#username-group').addClass('has-error'); // add the error class to show red input
$('#username-group').append('<div class="help-block">' + data.errors.userName + '</div>'); // add the actual error message under our input
}
if (data.errors.password) {
$('#password-group').addClass('has-error'); // add the error class to show red input
$('#password-group').append('<div class="help-block">' + data.errors.password + '</div>'); // add the actual error message under our input
}
if (data.errors.RPassword) {
$('#retypePassword-group').addClass('has-error'); // add the error class to show red input
$('#retypePassword-group').append('<div class="help-block">' + data.errors.RPassword + '</div>'); // add the actual error message under our input
}
} else {
// ALL GOOD! just show the success message!
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
// usually after form submission, you'll want to redirect
// window.location = '/thank-you'; // redirect a user to another page
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
I would be glad if someone puts me through. Please note I sent the form through an AJAX call to the signUp.php.
Do you know about this in your AJAX code: url: 'signUpValidation.php',
sinse your file is signUp.php?
That is a lot of code but you are calling signUp.php then require_once ('insert_user.php'); in it and then in insert_user you are using $_POST["full_Name"] again even when you validated it already in signUp.php. Shouldn't insert_user.php just make the query in the DB?
And you are checking If(isset($_POST['submit'])) in insert_user.php. You should check it in signUp.php.
I would organize the code in functions at least if not classes: functionConnectToDB, fnInsertUser...
signUp.php:
require_once('functions.php');
if(isset($_POST['submit'])) {
validations you have
}
if (empty($errors)) {
fill $data array with $full_Name etc. cause you didn't do it!
insertUser($data);
}
functions.php:
function connectDB() {
...
}
function insertUser($data) {
connectDB();
insert DB query
...
}
I am using ajax to submit a login form in Yii. Here is my ajax function:
$("#login-form").submit(function() {
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
url: "<?php echo Yii::app()->request->baseUrl; ?>/site/validatelogin",
type: "post",
data: "email=" + email + "&password=" + password,
success: function(response) {
if (response === "1") {
window.location.href = "<?php echo Yii::app()->getBaseUrl(true); ?>/dashboard";
}
else
{
//Dispaly response errors above login form
}
},
error: function() {
alert("Could not perform the requested operation due to some error.");
return false;
}
});
});
My PHP controller function is validatelogin as follows:
$email = $_POST['email'];
$password = $_POST['password'];
$model = new LoginForm();
$model->email = $email;
$model->password = $password;
if ($model->validate() && $model->login()) {
echo "1";
} else {
print_r($model->getErrors());
}
If the user enters correct credentials I send 1 as response to view and user is redirected to dashboard.
But if user enters incorrect credentials then different errors are received in ajax response depending upon the type of error.
I want to display those errors above login form in else part of success function through a loop.
But when I run the loop over response then that array has very large length i.e for example if the error in response was "Incorrect password" then the response array has length of 18(the number of characters) in the error message. In short the response array is like:
array('I','n','c','o','r','r'....)
rather than
array([0]=>"Incorrect password")
How do I convert response array in the latter format and iterate over each index to display error message to the user above the login form?
Encode it to JSON.
In your php:
echo json_encode($model->getErrors());
In your js (in the else):
var errors = $.parseJSON(response);
Edit:
In your case it would be better to always return JSON.
Your JS could be changed to:
var jqxhr = $.post("<?php echo Yii::app()->request->baseUrl; ?>/site/validatelogin", {
email: email,
password: password
}, 'json');
jqxhr.done(function(response) {
if (response.valid) {
window.location.href = "<?php echo Yii::app()->getBaseUrl(true); ?>/dashboard";
} else {
if (response.errors) {
...
}
}
});
jqxhr.error(function(response) {
alert("Could not perform the requested operation due to some error.");
});
Your PHP:
$response = array('valid' => false);
if ($model->validate() && $model->login()) {
$response['valid'] = true;
} else {
$response['errors'] = $model->getErrors();
}
header('Content-type: application/json');
echo json_encode($response);
In addition to #sroes's answer, use Yii library for JSON
echo CJSON::encode($response);
instead of
echo json_encode($response);
why ?
Why use CJSON encode when we have json_encode