I am able to display success and fail messages if the form has validation errors or not but I am not sure how to get the errors to display one under each other in this php code:
$errors = array();
$response = array();
if(empty($_POST['name'])) {
$errors['name'] = "Name required";
}
if(empty($_POST['email'])) {
$errors['email'] = "Email required";
}
$response['errors'] = $errors;
if($errors) {
$response['success'] = false;
$response['message'] = "Fail";
} else {
$reponse['success'] = true;
$response['message'] = "<div class='alert alert-success'>Article added</div>";
}
echo json_encode($response);
The line I need to change is probably:
$response['message'] = "Fail";
I am not sure I understand your issue, but if the goal is for the user to get the list of errors encountered, then everything you did was quite correct.
The errors are in
$response['errors']
so the json_encoded result of $response permits Javascript (client-side) to browse those errors as an array, and correctly print them.
You should not return HTML formatted text. It's the role of the View (client) to render the results, accordingly to CSS rules.
So I would say that there is nothing to change here. On success == false the client must print the errors from { 'errors' : { ... }}
If you cannot/don't want to edit the client-side Javascript / rendering page, then you have to concatenate a string with <br> or a <ul><li> and provide this one in $response['message']. It's ugly, but whoever has constraints still has solutions.
Have you tried to add the error message as you detect it
$errors = array();
$response = array();
if(empty($_POST['name'])) {
$errors['name'] = "Name required";
response['message'] = "<div class='alert alert-danger'>Name Required</div>";
}
if(empty($_POST['email'])) {
$errors['email'] = "Email required";
response['message'] = "<div class='alert alert-danger'>Email Required</div>";
}
$response['errors'] = $errors;
if($errors) {
$response['success'] = false;
// $response['message'] = "Fail"; we added the message during the error detection
} else {
$response['success'] = true;
$response['message'] = "<div class='alert alert-success'>Article added</div>";
}
echo json_encode($response);
Related
I have the following code :
if(isset($_POST['submit'])){
if (! isset($_POST['firstname'])) {
$error[] = "Please fill out all fields";
}
if (! isset($_POST['surname'])) {
$error[] = "Please fill out all fields";
}
........
with validation:
if (strlen($_POST['firstname']) < 2){
$error[] = 'First name cannot be empty';
}
if (strlen($_POST['surname']) < 2){
$error[] = 'Please provide your surname';
}
......
More checks are made with the database....
This checks for errors and displays them in one go:
if(isset($error)){
foreach($error as $error){
echo '<p class="error-login">'.$error.'</p>';
}
}
While this is working fine, I would like errors to be shown under each input box where there is an error happening.
I don't want to change the entire code, just want to make the necessary changes to this one, which I am incapable of doing myself.
Is putting them in array the only approach here or is there a simpler way ?
Thanks.
The approach is - add errors to $error under a certain key, I presume - name of the input field:
if(isset($_POST['submit'])){
// I use key `all` for errors that don't belong to any field
if (! isset($_POST['firstname'])) {
$error['all'] = "Please fill out all fields";
}
if (! isset($_POST['surname'])) {
$error['all'] = "Please fill out all fields";
}
if (strlen($_POST['surname']) < 2){
$error['surname'] = 'Please provide your surname';
}
In your html markup:
// general errors, not related to inputs
if(isset($error['all'])){
foreach($error['all'] as $err){
echo '<p class="error-login">'.$err.'</p>';
}
}
<input type="text" name="surname" />
<?php
if(isset($error['surname'])){
foreach($error['surname'] as $err){
echo '<p class="error-login">'.$err.'</p>';
}
}
I am trying to make a post request with angularjs to php. The post response is always 200 OK and the returned 'data' variable in the response is empty always. I am kind of new at this as you can see, what am I doing wrong here?
AngularJs code:
$scope.postData = function(){
$http.post('send.php', $scope.data).then(function(response){
console.log(response);
});
}
PHP:
$form_data = json_decode(file_get_contents("php://input"));
$data = array();
$error = array();
if(empty($form_data->fullName)){
$error["fullName"] = "Your name is required";
}
if(empty($form_data->email)){
$error["email"] = "Your email is required";
}
if(empty($form_data->message)){
$error["message"] = "Message is required";
}
if(!empty($error)){
$data["error"] = $error;
} else {
$data["message"] = "Ok";
}
You need to echo data back to the client, in your code you not returning anything back hence the response is empty.
<?php
$form_data = json_decode(file_get_contents("php://input"));
$data = array();
$error = array();
if(empty($form_data->fullName)){
$error["fullName"] = "Your name is required";
}
if(empty($form_data->email)){
$error["email"] = "Your email is required";
}
if(empty($form_data->message)){
$error["message"] = "Message is required";
}
if(!empty($error)){
$data["error"] = $error;
} else {
$data["message"] = "Ok";
}
echo json_encode($data); // return data back to the client
I am validating a form data using this script below.
When i submit the form if there is any errors the error message is displaying properly but if no errors and validation succeed i try to echo out the variables to test the script but the script is only displaying this : []
Please examine the code and help me solve this.
<?php
//included files
include("./includes/connect.php");
include("./includes/functions.php");
$errors = array();
//checking if user have submitted the form
if(isset($_POST['submitted'])) {
//validating and cleaning submitted form data ...
if (isset($_POST['name']) && !empty($_POST['name'])) {
if(preg_match("/^[a-zA-Z ]{2,20}$/", strip_trim($_POST['name']))) {
$cln_name = clean_data($_POST['name']);
} else {
$_POST['name'] = FALSE;
$errors[] = "The name you entered is not valid";
}
} else {
$errors[] = "You have not enter your name!";
}
if(isset($_POST['email']) && !empty($_POST['email'])) {
$cln_email = filter_var($_POST['email'] , FILTER_SANITIZE_EMAIL);
if(filter_var($cln_email, FILTER_VALIDATE_EMAIL)) {
$cln_email = clean_data($cln_email);
} else {
$_POST['email'] = FALSE;
$errors[] = "The email you entered is not valid";
}
} else {
$errors[] = "You have not provide you email!";
}
if(isset($_POST['plate_num']) && !empty($_POST['plate_num'])) {
if(ctype_alnum($_POST['plate_num']) && strlen($_POST['plate_num']) >= 5) {
$cln_plate_num = clean_data($_POST['plate_num']);
} else {
$_POST['plate_num'] = FALSE;
$errors[] = "The plate number you provided is not a valid plate number";
}
} else {
$errors[]= "You have not provide a plate number";
}
//checking for errors and printing errors..
if (count($errors > 0)) {
$errors_to_json = json_encode($errors);
echo $errors_to_json;
//foreach ($errors as $error) {
//echo $error . "<br />";
//}
} else {
echo $cln_name . "<br />";
echo $cln_email . "<br />";
echo $cln_plate_num;
}
} else {
echo "You did not submit the form!";
}
?>
This script is returning only this :
[]
Any idea please ??
functions.php :
<?php
function clean_data($data) {
if(function_exists('mysql_real_escape_string')) {
global $dbc;
$data = mysql_real_escape_string(trim($data), $dbc);
$data = strip_tags($data);
} else {
$data = mysql_escape_string(trim($data));
$data = strip_tags($data);
}
return $data;
}
function strip_trim($data) {
$data = stripslashes(trim($data));
return $data;
}
?>
you have problem in your if condition:
//checking for errors and printing errors..
if (count($errors > 0)) {
...
this will always return to TRUE because $error = [] and count([] > 0) results to TRUE
that's why you always end up in:
$errors_to_json = json_encode($errors);
echo $errors_to_json;
// Will indeed display '[]' because json_encode([]) is '[]'
i believe what you mean here is:
if (count($errors) > 0) {
...
So I am trying to make a simple e-commerce site. Once I submit the form (btn-submit), I am not able to insert any data to my database. Only the address and contact number verification works.
Here is my code:
if ( isset($_POST['btn-submit']) ) {
// clean user inputs
$oadd = trim($_POST['oadd']);
$oadd = strip_tags($oadd);
$oadd = htmlspecialchars($oadd);
$contact = trim($_POST['contact']);
$contact = strip_tags($contact);
$contact = htmlspecialchars($contact);
// address validation
if (empty($oadd)) {
$error = true;
$oaddError = "Please enter a valid address.";
} else if (strlen($oadd) < 5) {
$error = true;
$oaddError = "Please enter a valid address.";
}
// contact number validation
if (empty($contact)) {
$error = true;
$contactError = "Please enter your contact number.";
} else if (strlen($contact) < 7) {
$error = true;
$contactError = "Contact number must have atleast 7 digits.";
} else if (!preg_match("/^[0-9 ]+$/",$lname)) {
$error = true;
$lnameError = "Please enter a valid contact number.";
}
// if there's no error, continue to place order
if( !$error ) {
$query = 'INSERT INTO cust_order(Order_Date, Order_Status, Order_Total , Address, Contact_No) VALUES (CURDATE(), "in process" , (SELECT SUM(p.Product_Price) FROM cart c, product p WHERE c.Prod_ID = p.Product_ID and c. User_ID = "'.$userRow['User_ID'].'"),"'.$oadd.'","'. $contact.'")';
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Your order has been placed. To view the details, go to your order history";
unset($oadd);
unset($contact);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong. Please try again later.";
}
}
}
What could possibly be wrong with my code? I did similar queries in the other pages but this is the only one not working. Any help would be greatly appreciated! Thanks in advance!
Try to understand the code flow:
if( !$error ) {
// This will only works when **$error is false and the not of false is true**, otherwise this block does not execute
}
So this code works only when there is no validation error occurs in your code and $error contains false
//$userRow is not define any where...
//to check error occur or not :
echo $error;
if(!$error)
{
echo "IN IF";
//also go with die..
$res = mysql_query($query) or die();
}
else
{
echo "IN ELSE";
}
Right now, posting a snippet of what I wrote:
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
Every single time when I try to post the snippet above or a variation of it, it literally blanks out my page.
Question is, is the code I wrote above a good way to compare two email addresses via text fields?
And why does it blank out my entire page every time?
Here's a bit of further context if that's more helpful (let me know you want the entire page):
<?php
session_start(); //allows use of session variables
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["nights"])) {
$nightsErr = "# of nights are required";
} else {
$nights = test_input($_POST["nights"]);
}
if (empty($_POST["arrivals"])) {
$arrivalsErr = "Time of arrival is required";
} else {
$arrivals = test_input($_POST["arrivals"]);
}
if (empty($_POST["male"])) {
$maleErr = "# of people (gender female) required";
} else {
$male = test_input($_POST["male"]);
}
if (empty($_POST["female"])) {
$femaleErr = "# of people (gender female) required";
} else {
$female = test_input($_POST["female"]);
}
if (empty($_POST["rooms"])) {
$roomsErr = "# of rooms required";
} else {
$rooms = test_input($_POST["rooms"]);
}
if (empty($_POST["type"])) {
$typeErr = "type of rooms required";
} else {
$type = test_input($_POST["type"]);
}
if (empty($_POST["name"])) {
$nameErr = "name required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["address"])) {
$addressErr = "address required";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["zip"])) {
$zipErr = "zip required";
} else {
$zip = test_input($_POST["zip"]);
}
if (empty($_POST["telephone"])) {
$telephoneErr = "telephone required";
} else {
$telephone = test_input($_POST["telephone"]);
}
if (empty($_POST["email1"])) {
$email1Err = "email required";
} else {
$email1 = test_input($_POST["email1"]);
}
if (empty($_POST["email2"])) {
$email2Err = "email2 required";
} else {
$email2 = test_input($_POST["email2"]);
}
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
This is failing you and isn't the right syntax for what you want to achieve:
if (isset($_POST["email1"] != $_POST["email2"]))
What you need to do is to first check if it is set then check if both are (not) equal to, but it's best to use !empty(), then check if it is not equal to:
if (!empty($_POST["email1"]) && !empty($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "Emails don't match. Please enter the same email address.";
}
}
Plus, make sure your form elements both have the right name attributes.
Also, a blank page can mean syntax errors.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
What you are doing is assigning by using a single equals to sign rather make it a double equals to sign, I mean ==
Try:
if (isset($_POST["email1"]) && isset($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "please enter the same email address";
}
}