AngularJs - PHP POST issue - php

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

Related

php script is displaying a weired results

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) {
...

ajax and json_encode() form validation error

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

read JSON input in slim framework

i am new to slim framework following a tutorial i managed to get post data to my API.but when i tried to send data as JSON it gives me an error.I tried to accpt JSON request as follows what is the correct syntax to achive this.i get error as Required field(s) name, email, password is missing or empty
$app->post('/login', function() use ($app) {
// check for required params
$json = $app->request->getBody();
$data = json_decode($json, true);
verifyRequiredParams(array('name','email', 'password'));
how i can get json data from a post request in my API from an JSON array like
{
"name":"usertest",
"email":"xxxx#xxx.xxx",
"password":"xxxxxx"
}
can i use verifyRequiredParams(array('name','email', 'password')); and $name = $app->request->post('name'); if request come as a JSON.
To read the request data you can use your $data property. It should be an object so you can use it like this:
$name = $data->name;
$email = $data->email;
EDIT:
Use $data = json_decode($json) instead of $data = json_decode($json, true) to convert the json data to object instead of an associative array.
the problem was with placing my verifyRequiredParams function i think.i fixed the issue from following code in case any one had same issue.
$app->post('/login', function() use ($app) {
if($app->request->headers->get('Content-Type')=='application/json'){
$json = $app->request->getBody();
verifyRequiredParamsjson(array('email','password'),$json);
$data = json_decode($json);
// check for required params
$email = $data->email;
$password = $data->password;
}
else{
// check for required params
verifyRequiredParams(array('email', 'password'));
// reading post params
$email = $app->request->post('email');
$password = $app->request->post('password');
}
$response = array();
$db = new DbHandler();
// check for correct email and password
if ($db->checkLogin($email, $password)) {
// get the user by email
$user = $db->getUserByEmail($email);
if ($user != NULL) {
$response["error"] = false;
$response['name'] = $user['name'];
$response['email'] = $user['email'];
$response['apiKey'] = $user['api_key'];
$response['createdAt'] = $user['created_at'];
} else {
// unknown error occurred
$response['error'] = true;
$response['message'] = "An error occurred. Please try again";
}
}
else{
$response['error'] = true;
$response['message'] = 'Login failed. Incorrect credentials';
}
echoRespnse(200, $response);
});
required parameter check,
function verifyRequiredParams($required_fields) {
$error = false;
$error_fields = "";
$request_params = array();
$request_params = $_REQUEST;
// Handling PUT request params
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
$app = \Slim\Slim::getInstance();
parse_str($app->request()->getBody(), $request_params);
}
foreach ($required_fields as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields .= $field . ', ';
}
}
if ($error) {
// Required field(s) are missing or empty
// echo error json and stop the app
$response = array();
$app = \Slim\Slim::getInstance();
$response["error"] = true;
$response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
echoRespnse(400, $response);
$app->stop();
}
}

trying to compare two email fields - page blanks out

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";
}
}

PHP Form Validation and Submit to Database

I would like to ask how do I set PHP "form validation" and "submit to database" in one single php file? This is what I tried to do in PART 1 and PART 2.
$latErr = $lngErr = $messageErr = "";
$lat = $lng = $message = "";
$tbl_name="stickers";
$datetime=date("d-m-y H:i:s");
//PART 1 - form validation method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["inputfield1"])) {
$latErr = "* Latitude is required. Please enable your browser geolocation settings.";
} else {
$lat = test_input($_POST["inputfield1"]);
}
if (empty($_POST["inputfield2"])) {
$lngErr = "* Longitude is required. Please enable your browser geolocation settings.";
}else{
$lng = test_input($_POST["inputfield2"]);
}
if (empty($_POST["message"])) {
$messageErr = "* Please enter your message.";
} else {
$message = test_input($_POST["message"]);
}
}
//PART 2 - check if all 3 parameters are filled, if yes then insert into database
if (isset($lat, $lng, $message)){
$sql="INSERT INTO $tbl_name(username, message, datetime, lat, lng )VALUES('$user- >username','$message', '$datetime', '$lat', '$lng')";
$result=mysql_query($sql);
//check if query successful
if($result){
$post_info = "Your msg is successfully posted!";
}else{
$post_info = "Oops, there is an error posting the msg.";
}
mysql_close();
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
It doesn't work. It just insert blanks into the database. Something is wrong but I dunno what is it? Anyone can advice. Thanks.
Maybe you need to use empty() instead of isset()?
//PART 1 - form validation method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["inputfield1"])) {
$latErr = "* Latitude is required. Please enable your browser geolocation settings.";
} else {
$lat = test_input($_POST["inputfield1"]);
}
if (empty($_POST["inputfield2"])) {
$lngErr = "* Longitude is required. Please enable your browser geolocation settings.";
}else{
$lng = test_input($_POST["inputfield2"]);
}
if (empty($_POST["message"])) {
$messageErr = "* Please enter your message.";
} else {
$message = test_input($_POST["message"]);
}
}
//PART 2 - check if all 3 parameters are filled, if yes then insert into database
if ( !empty($lat) && !empty($lng) && !empty($message) ){
$sql="INSERT INTO $tbl_name(username, message, datetime, lat, lng )VALUES('$user- >username','$message', '$datetime', '$lat', '$lng')";
$result=mysql_query($sql);
//check if query successful
if($result){
$post_info = "Your msg is successfully posted!";
}else{
$post_info = "Oops, there is an error posting the msg.";
}
}
else {
$post_info = "Empty content.";
}
mysql_close();

Categories