Displaying JSON encoded Error Messages with AngularJS - javascript

I have a form as below, and I used angularJs SPA for this application. This is the one form of my SPA among lot of forms.I need to point out how to display error messages responded from corresponding php process file via angularJs
My lends.php page is below,
<?php
$userid= $_POST['userid'];
$copyid = $_POST['copyid'];
//$set_success = array($userid,$copyid);
require_once '../../../core/database/connect.php';
$errors = array();
$data = array();
//.... queries......
if(empty($userid) || empty($copyid)){
$data['success'] = false;
$data['errors'] = "Fill both fields";
}else if($numrows == 0){
//internal codes ...........
}else{
$enterdeal = "INSERT INTO user_lends_copies(id,user_id,copy_id,date_lend,due_date,status) VALUES (NULL,'$userid','$copyid','$dateb','$dated','open')";
if($connection->query($enterdeal) === TRUE){
$data['success'] = true;
$data['message'] = "New record created successfully";
}else{
$errors = $connection->error;
$data['success'] = false;
$data['errors'] = $errors;
}
$connection->close();
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, return a message
$data['success'] = true;
$data['message'] = 'Success!';
}
}
echo json_encode($data);
?>
And here is my app.js file
dash.controller('lendingController',['$scope','$log','$http',function($scope,$log,$http){
$scope.formData = {};
$scope.processFormLends = function(){
$http({
method: "POST",
url: "../admin/pages/processing/lends.php",
data: $.param($scope.formData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(function(data){
console.log(data);
if(data.success == false){
$scope.errorCopy = data.errors;
}else{
$scope.message = data.message;
$scope.errorCopy= "";
$scope.errorUser = "";
}
});
};
}]);
// PS: Top of the SPA index page I have like below //
<body ng-app="dash">
And I have attached my lending page,(view page of the app) below,
div class="dashtitle">
<h2>Lending</h2>
</div><br/>
<h4>Lend book</h4>
<form ng-submit="processFormLends()">
<div class="row">
<div class="col-md-6">
<div class="form-group" ng-class="{ 'has-error' : errorCopy }">
<label for="Title">Copy ID:</label>
<input type="number" ng-minlength="1" class="form-control" name="copyid" ng-model="formData.copyid">
<span class="help-block" ng-show="errorCopy">{{ errorCopy }}</span>
</div>
</div>
<div class="col-md-6">
<div class="form-group" ng-class="{ 'has-error' : errorUser }">
<label for="Title">User ID:</label>
<input type="number" ng-minlength="1" class="form-control" name="userid" ng-model="formData.userid">
<span class="help-block" ng-show="errorUser">{{ errorUser }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<span id="errMessage" ng-show="message">{{ message }}</span>
<span id="errMessage" ng-show="data">{{ errorCopy }}</span>
<input type="submit" value="Lend Book" class="form-control blue" name="submit" ng-click=".success()">
</div>
</div>
</form>
<pre>{{ formData }}</pre>
And I have getting corresponding error messages successfully in Console log, but it is not displayed on the browser page. And Only when no error messages and have only a success message the "Success!" message is displayed. Please give me a tip to correct this! Big help!

Related

Undefined array key pageType when login, even if it's added to a page

I'm trying to log in and then redirect to a custom page, based on user type. My problem is that when I'm pressing the login button, on the console I get that that I have a Undefined array key pageType, and I don't understand why... If I'm for example on teacher page, I set $_SESSION['pageType'] = 'teacher';
This my login.html page:
<img class="wave" src="img/wave.png">
<div class="container_main" onsubmit="redirect();">
<div class="img">
<img src="img/bg.svg">
</div>
<div class="login-content">
<form onsubmit="redirect();">
<img src="img/avatar.svg">
<h2 class="title">Quiz Website</h2>
<div class="input-div one">
<div class="i">
<i class="fas fa-user"></i>
</div>
<div class="div">
<input type="text" class="input" id="enterID" placeholder="Username">
</div>
</div>
<div class="input-div pass">
<div class="i">
<i class="fas fa-lock"></i>
</div>
<div class="div form-group">
<input id="password" type="password" class="form-control" placeholder="Password" value="" required/>
</div>
</div>
Don't have an account?
<div class="form-group">
Trouble logging in?
</div>
<input type="submit" class="btn" value="Login" onclick="login();" readonly >
<div class="error-message" id="errorMessage"></div>
</form>
</div>
</div>
</html>
This is checklogin.js:
function login() {
var enterID = document.getElementById("enterID").value;
var password = document.getElementById("password").value;
if ((password != "") && (enterID != "")) {
var info = "?enterID=" + enterID + "&password=" + password;
$.ajax
({
type: "GET",
async: true,
url: "php/login.php" + info,
success: function (respond) {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student") {
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher") {
window.location.href = "page/teacher-dashboard.php";
} else {
document.getElementById("errorMessage").innerText = respond;
}
}
});
}
else {
document.getElementById("errorMessage").innerText = "Please fill in all the fields.";
}
}
function redirect() {
$.ajax
({
type: "GET",
async: true,
url: "php/redirect.php",
success: function (respond) {
if (respond != "not logged.") {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student") {
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher") {
window.location.href = "page/teacher-dashboard.php";
}
}
console.log(respond)
}
});
}
And this is my redirect.php file:
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isset($_SESSION["type"])){
if ($_SESSION["type"] != $_SESSION["pageType"]){
$alert_message = "You cannot access this page using your account!";
$link = "../login.html";
echo "<script type='text/javascript'>alert('$alert_message'); window.setTimeout(function(){ if ('".$_SESSION["type"]."'=='admin'){ window.location.href = '../page/admin-system-management.php';} else if ('".$_SESSION["type"]."'=='student'){ window.location.href = '../page/student-dashboard.php';} else if ('".$_SESSION["type"]."'=='teacher'){ window.location.href = '../page/teacher-dashboard.php';} }, 0);</script>";
}
} else {
$alert_message = "Your login period has expired! Please login again!";
$link = "../login.html";
echo "<script type='text/javascript'>alert('$alert_message'); window.setTimeout(function(){ window.location.href = '$link'; }, 0);</script>";
}
?>
What I suspect is that the redirect() function it's not even loaded, so that's why I think I'm getting this error... Sometimes I'm seeing ,,XHR failed loading: GET"
I modified a code in order to have another login.html page, this is my old login.html code:
<body class="jumbotron vertical-center" onload="redirect();">
<div class="container login-container">
<div class="row">
<div class="col-md-4 login-form mx-auto">
<h3>Login</h3>
<h6>Don't have an account? Register</h6>
<form>
<div class="error-message" id="errorMessage"></div>
<div class="form-group">
<input id="enterID" type="text" class="form-control" placeholder="Your User ID *" value="" required/>
</div>
<div class="form-group">
<input id="password" type="password" class="form-control" placeholder="Your Password *" value="" required/>
</div>
<div class="form-group">
<input class="btn btn-block btn-primary" value="Login" onclick="login();" readonly />
</div>
<div class="form-group">
Trouble logging in?
</div>
</form>
</div>
</div>
</div>
</body>
Inside redirect() function add this line at the start.
This will stop the forms default action of redirecting/refreshing the page
event.preventDefault();
Then your redirect function / respond variable should work
If you return this from php it will be ignored by javascript
echo "<script type='text/javascript'>code here\</script>";
To make your redirect.php easier to debug output the data as a json encoded array instead of a string that way you can view/test more data.
inside redirect.php try add this code straight after the session_start() line just as a first test
$data = [
'session' => $_SESSION,
'response' => 'place your response here',
];
echo json_encode($data);
exit;
Ok here is the update i think you need.
redirect.php
<?php
if(!session_id()) {
session_start();
}
// you can change this line to this once you have debugged your code - $data = [];
$data = ['session' => $_SESSION];
// place code here to get the user type from the database
// then use $_SESSION['type'] = '{database response}';
if(!isset($_SESSION['type']))
{
$_SESSION['type'] = null;
}
switch($_SESSION['type']) {
case 'admin':
header('Location: /page/admin-system-management.php'); // this is the php way to redirect
break;
case 'student':
header('Location: /page/student-dashboard.php');
break;
case 'teacher':
header('Location: /page/teacher-dashboard.php');
break;
default:
$data['alert_message'] = 'Your login period has expired! Please login again!';
}
echo json_encode($data);
exit;
?>
Javascript redirect function
function redirect() {
$.ajax
({
type: "GET",
async: true,
url: "php/redirect.php",
success: function (response) {
console.log(response);
if(response.alert_message) {
alert(response.alert_message);
}
}
});
}

Ajax Login Response Error

i'm traying to login with ajax and php, in that situation i'm logging succesfuly actually. But i'm trying to make an alert and refresh the page when logged in.
When i attempt to login, its gives me error and no refreshing. But if i refresh the page, i see i have session in php. I don't understand why.
Here is my code;
<script>
$(document).ready(function(){
$('#login_btn').click(function(){
var email = $('#email').val();
var password = $('#password').val();
if(email == '' || password == ''){
$("#login_error").html("*** Please enter your email / password");
}else{
$('#login_error').html("<strong class='text-success'>Validating...</strong>");
$.ajax({
url: "login.php",
method: "post",
data:{email:email, password:password},
success: function(data){
if (data === 'yes') {
window.location.reload();
}else{
$('#login_error').html("<strong class='text-danger'>ERROR...</strong>");
}
}
});
}
});
});
</script>
login php:
<?php
session_start();
include ('../config/setup.php'); #database connection
if(isset($_POST['email'])){
$q = "SELECT * FROM users WHERE email = '$_POST[email]' AND password = '$_POST[password]'";
$r = mysqli_query($dbc, $q);
if(mysqli_num_rows($r) > 0){
$_SESSION['email'] = $_POST['email'];
echo "yes";
}else{
echo "no";
}
}
?>
Html: (Using login form inside a modal)
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
<label for="email" class="col-sm-4 control-label">Email</label>
<div class="col-sm-8">
<input type="email" class="form-control" name="email" id="email" placeholder="Account Email">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-4 control-label">Password</label>
<div class="col-sm-8">
<input type="password" class="form-control" name="password" id="password" placeholder="Account Password" >
</div>
</div>
<div class="form-group">
<div class="col-sm-1"></div>
<div align="center" class="col-sm-10">
<button name="login_btn" id="login_btn" class="btn btn-success btn-block text-center"><span id="loader_before" class="glyphicon glyphicon-log-in" aria-hidden="true"></span><i id="loader" class="fa fa-spinner fa-spin fa-x fa-fw"></i> Log in to Account</button>
</div>
<div class="col-sm-1"></div>
</div>
</div>
<div align="center" class="container-fluid">
<h6><strong class="text-danger">Forgot your password? Click here..</strong></h6>
</div>
<h5><div id="login_error" class="text-warning"></div></h5>
</div>
You just need to update your if block in response as below
`
if (data === 'yes') {
alert("You message here!");
window.location.reload();
}else{
$('#login_error').html("<strong class='text-danger'>ERROR...</strong>");
}
`
When you call echo on php, it will write the value, but not return it. That's the problem.
You are not returning "yes" or "no" from login.php, you're just doing echo, which will only write the value but not return it to the caller.
The ajax call is waiting for a response to process it with the 'success' callback. Since login.php is not returning anything, it will always fall into the else clause.
The solution is to change this on login.php
if(mysqli_num_rows($r) > 0){
$_SESSION['email'] = $_POST['email'];
return "yes";
}else{
return "no";
}

jQuery script not writing values in database Mysql

My database has a table called utilizatori and has id,username,nume_prenume,parola,locatie,sambata columns.
Through the form, I am trying to add new entries in database but when I submit the form, it doesn`t add any entry.
A demo can be found HERE.
The update and delete operations are working fine.
HTML form:
<script src="js/jQuery/jquery.min.js"></script>
<!-- Include AngularJS library -->
<script src="lib/angular/angular.min.js"></script>
<!-- Include Bootstrap Javascript -->
<script src="js/bootstrap.min.js"></script>
<form class="form-horizontal alert alert-warning" name="empList" id="empForm" ng-submit="insertInfo(empInfo);" hidden>
<h3 class="text-center">Insert Employee Details Into Database</h3>
<div class="form-group">
<label for="Username">Nume utilizator:</label>
<input type="text" name="username" class="form-control" placeholder="Enter Employee Name" ng-model="empInfo.username" value="" autofocus required />
</div>
<div class="form-group">
<p class="text-danger" ng-show="empList.username.$invalid && empList.username.$dirty">Name field is Empty!</p>
</div>
<div class="form-group">
<label for="Nume_prenume">Nume angajat:</label>
<input type="text" name="nume_prenume" class="form-control" placeholder="Enter Employee Email Address" ng-model="empInfo.nume_prenume" autofocus required />
</div>
<div class="form-group">
<p class="text-danger" ng-show="empList.nume_prenume.$invalid && empList.nume_prenume.$dirty">Invalid Email!</p>
</div>
<div class="form-group">
<label for="Parola">Parola cont:</label>
<input type="text" name="parola" class="form-control" placeholder="Enter Employee Name" ng-model="empInfo.parola" value="" autofocus required />
</div>
<div class="form-group">
<p class="text-danger" ng-show="empList.parola.$invalid && empList.parola.$dirty">Name field is Empty!</p>
</div>
<div class="form-group">
<label for="Rol_user">Rol:</label>
<input type="text" name="rol_user" class="form-control" placeholder="Enter Employee Address" ng-model="empInfo.rol_user" autofocus required />
</div>
<div class="form-group">
<p class="text-danger" ng-show="empList.rol_user.$invalid && empList.rol_user.$dirty">Address field is Empty!</p>
</div>
<div class="form-group">
<button class="btn btn-warning" ng-disabled="empList.$invalid">Add Into Database</button>
</div>
</form>
<script src="js/angular-script.js"></script>
Angular JS script:
// Application module
var crudApp = angular.module('crudApp', []);
crudApp.controller("DbController", ['$scope', '$http', function($scope, $http) {
// Function to get employee details from the database
getInfo();
function getInfo() {
// Sending request to EmpDetails.php files
$http.post('databaseFiles/empDetails.php').success(function(data) {
// Stored the returned data into scope
$scope.details = data;
});
}
// Setting default value of gender
$scope.empInfo = {
'rol_user': 'Operator receptie'
};
// Enabling show_form variable to enable Add employee button
$scope.show_form = true;
// Function to add toggle behaviour to form
$scope.formToggle = function() {
$("#empForm").slideToggle();
$("#editForm").css('display', 'none');
}
$scope.insertInfo = function(info) {
$http.post('databaseFiles/insertDetails.php', {
"username": info.username,
"nume_prenume": info.nume_prenume,
"parola": info.parola,
"rol_user": info.rol_user
}).success(function(data) {
if (data == true) {
getInfo();
$("#empForm").css('display', 'none');
}
});
}
$scope.deleteInfo = function(info) {
$http.post('databaseFiles/deleteDetails.php', {
"del_id": info.id
}).success(function(data) {
if (data == true) {
getInfo();
}
});
}
$scope.currentUser = {};
$scope.editInfo = function(info) {
$scope.currentUser = info;
$('#empForm').slideUp();
$('#editForm').slideToggle();
}
$scope.UpdateInfo = function(info) {
$http.post('databaseFiles/updateDetails.php', {
"id": info.id,
"username": info.username,
"nume_prenume": info.nume_prenume,
"parola": info.parola,
"rol_user": info.rol_user
}).success(function(data) {
$scope.show_form = true;
if (data == true) {
getInfo();
}
});
}
$scope.updateMsg = function(emp_id) {
$('#editForm').css('display', 'none');
}
}]);
Insert info PHP script:
<?php
// Including database connections
require_once 'database_connections.php';
// Fetching and decoding the inserted data
$data = json_decode(file_get_contents("php://input"));
// Escaping special characters from submitting data & storing in new variables.
$username = mysqli_real_escape_string($con, $data->username);
$nume_prenume = mysqli_real_escape_string($con, $data->nume_prenume);
$parola = mysqli_real_escape_string($con, $data->parola);
$rol_user = mysqli_real_escape_string($con, $data->rol_user);
// mysqli insert query
$query = "INSERT into utilizatori (username,nume_prenume,parola,rol_user) VALUES ('$username','$nume_prenume','$parola','$rol_user')";
// Inserting data into database
mysqli_query($con, $query);
echo true;
?>
And database_connections.php script:
<?php
$con = mysqli_connect("localhost", "user", "pasword", "database");
?>
I found the issue. I was trying to write in 4 columns, but there are 6 (excluding id which is auto increment.
If I rewrite this query to write in all 6 or I remove the other 2 columns from database, will work.
// mysqli insert query
$query = "INSERT into utilizatori (username,nume_prenume,parola,rol_user) VALUES ('$username','$nume_prenume','$parola','$rol_user')";

ajax contact form does not send email

All day i trying to solve the problem but without success.
The form does not send a message and not written an error.
form.html
<div class="ok" id="ok"></div>
<div id="data">
<div id="alert" class="alert_ig"></div>
<form id="form" class=" clearfix" method="POST" action="">
<div class="col-sm-12">
<div class="form-group">
<input name="name" type="text" id="name" value="{$smarty.cookies.nameuser}" class="form-control" placeholder="Name"/>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input name="email" type="email" id="email" value="{$smarty.cookies.emailuser}" class="form-control" placeholder="E-mail"/>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<textarea id="message" class="form-control" rows="5" name="text" placeholder="Message"></textarea>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<button style="margin-top:10px" id="submit" type="submit" class="bot_g">Send</button>
</div>
</div>
</form>
<script>
$(document).ready(function() {
$('#submit').click(function(e){
var form = $(this);
var error = false;
if (!error) {
var data = form.serialize();
$.ajax({
type: 'POST',
url: '{$home}/system/modules/contacts/send.php',
dataType: 'json',
data: data,
success: function(data){
if (data.error.length > 0) {
$('#alert').html(""+data['error']+"");
$('#email').addClass("fill");
} else {
$('#ok').html('send.');
$( "#data" ).css( "display","none" );
}
},
return false;
)};
});
</script>
</div>
send.php
<?php
require_once '../../inc/core.php';
$name=Text(trim($_POST['name']));
$email=Text(trim($_POST['email']));
$subject=Text(trim($_POST['subject']));
$text=Text(trim($_POST['text']));
if(empty($name)){
$json['error'] = 'Come on, you have a name don\'t you?';
echo json_encode($json);
exit;
}
if (mb_strlen($name) < 2 || mb_strlen($name) > 250){
$json['error'] = 'Your name must consist of at least 2 characters!';
echo json_encode($json);
exit;
}
if(empty($email)){
$json['error'] = 'No Email, No Message!';
echo json_encode($json);
exit;
}
if (mb_strlen($email) < 5 || mb_strlen($email) > 64){
$json['error'] = 'Your email must consist of at least 5 characters!';
echo json_encode($json);
exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$json['error'] = 'Unknown characters in your e-mail!';
echo json_encode($json);
exit;
}
if(empty($subject)){
$json['error'] = 'Um...yea, you have to write something to send this form.';
echo json_encode($json);
exit;
}
if (mb_strlen($subject) < 5 || mb_strlen($subject) > 250){
$json['error'] = 'Your subject must consist of at least 5 characters!';
echo json_encode($json);
exit;
}
if (mb_strlen($text) < 2 || mb_strlen($text) > 10000){
$json['error'] = 'Thats All? Really?';
echo json_encode($json);
exit;
}
$mailer = new phpmailer();
$mailer->ContentType = "text/html";
$mailer->From = $email;
$mailer->Subject = 'New message from '.$home;
$mailer->Body ="Subject: ".$subject."<br/>
Name: ".$name."<br/>
E-mail: ".$email."<br/>
".nl2br($text);
$mailer->AddAddress($setup['emailadmin'], '');
$mailer->Send();
$json['error'] = 0;
echo json_encode($json);
?>
When is my problem with this code?
I must use this send.php format, but may to change ajax and html form to working...
thanks
var form = $(this);
In this line $(this); refers to the submit button so var form, stores your submit button instead of the form element itself.
You may not see an error on the client-side, but if you try to debug the data sent to your server-side you will see something is wrong.
Try replacing $(this) with the selector that matches your form element.
Also, if you want to inform your users when the server returns an error like a 500 error for example, you can add an error callback to your $ajax function, along with the success callback you already have.
Have a look here http://api.jquery.com/jquery.ajax/ for the documentation.
Also add e.preventDefault() at the end of your event handler, to prevent the default action of submitting the form if you want to do an ajax submit.

ng-select just return the word 'array"

i have a ng-select in a contact form, I recieve correctly the form except ng-select.
The system just return me the word "array", but I need the selected option from the ng-select.
This is my portion of html
<div ng-controller="ContactController" class="panel-body">
<form ng-submit="submit(contactform)" name="contactform" method="post" action="" class="form-horizontal" role="form">
<div class="row half" ng-class="{ 'has-error': contactform.inputName.$invalid && submitted }">
<div class="12u">
<input ng-model="formData.inputName" type="text" class="form-control" id="inputName" name="inputName" placeholder="Nombre" required>
</div>
</div>
<div class="row half" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<div class="12u">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Email de contacto" required>
</div>
</div>
<!-- select -->
<div class="row half" ng-class="{ 'has-error': contactform.myDepartment.$invalid && submitted }">
<div class="12u">
<select ng-model="formData.myDepartment" ng-options="departamento.name for departamento in departamento" id="myDepartment" name="myDepartment">
<option value="">-- Tipo de mensaje --</option>
</select>
</div>
</div>
<!-- select -->
<div class="row half" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<div class="12u">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Asunto del mensaje" required>
</div>
</div>
<div class="row half" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<div class="12u">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Mensaje" required></textarea>
</div>
</div>
<div class="row">
<div class="12u">
<input type="submit" name="submit" id="submit_btn" value="Enviar mensaje" ng-disabled="submitButtonDisabled"/>
</div>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
</div>
This is the code of controller.js
app.controller('ContactController', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.departamento = [
{name:'Selecciona departamento'},
{name:'RRHH'},
{name:'Soporte'},
{name:'Postventa'},
{name:'Comercial'},
{name:'Desarrollo'}
];
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method : 'POST',
url : '/contact-form.php',
data : $.param($scope.formData), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
$scope.myDepartment = $scope.departamento.name; // red
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed :( Please fill out all the fields.';
$scope.result='bg-danger';
}
}
});
And this is the Php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'phpmailer/PHPMailerAutoload.php';
if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['myDepartment']) && isset($_POST['inputSubject']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['myDepartment']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Completa el formulario antes de enviar');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress('xxxx#xxx.com'); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nDepartment: " . $_POST['myDepartment'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'El mensaje no puede ser enviado. Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Gracias, hemos recibido tu mensaje.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Rellena el formulario completamente.');
echo json_encode($data);
}
Can you help me?
Thanks, Luiggi
You are having the entire object be set for $scope.myDepartment. Instead of
ng-options="departamento.name for departamento in departamento"
try using
ng-options="departamento.name as departamento.name for departamento in departamento"
this should set $scope.myDepartment to the actual string selected, rather than an object of {name: selection}
Firstly, your ng-options syntax is wrong. It should be
ng-options="singular.title for singular in plural"
If you had an array of objects like this:
$scope.departamento = [{name: dep1}, {name: dep2}]
You would write ng-options like this:
ng-options="d.name for d in departamento"
Where d is any variable name.
Also I don't think you should be doing this
data : $.param($scope.formData)
Because $scope.formData is already a javascript object, and $http, unlike $.ajax automatically stringify's your objects.

Categories

Resources