PHPMAILER not sending select input - php

Hi my question is about the following i'm using the select tag in my form, but the value does not get passed on to the email that gets send out.
I've created an app using PHPMAILER and have added the select tag with options included. whenever I hit send I get the following error:
Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"contact-form.php","data":"inputPrice=1%20%2F%202%20hour%20%3D%2020%2C-&inputGuests=1&inputDate=Mon%20Feb%2003%201992%2010%3A10%3A00%20GMT%2B0100%20(Central%20European%20Standard%20Time)&inputMessage=Mon%20Feb%2003%201992%2010%3A10%3A00%20GMT%2B0100%20(Central%20European%20Standard%20Time)&inputName=Salman%20Mohamed&inputEmail=salmannova%40gmail.com&inputNumber=620438661","headers":{"Content-Type":"application/x-www-form-urlencoded","Accept":"application/json, text/plain, */*"}},"statusText":"","xhrStatus":"abort"}
The email does get send with all the value's added except the value from the select tag. In the error you can read that the value does get passed on, but for some reason doesn't get passed onto the email.
Does anyone know what's wrong with my code?
Select module
<select ng-model="formData.inputPrice" type="number" class="form-control inputForm fa fa-input" id="inputPrice" name="inputPrice" placeholder="How many scooters?" required>
<option value="" disabled="disabled" selected="selected">Prices</option>
<option value="1 / 2 hour = 20,-">1 / 2 hour = 20,-</option>
<option value="1 day = 30,-">1 day = 30,-</option>
<option value="2 days = 55,-">2 days = 55,</option>
<option value="3+ dagen = +20,-">3+ dagen = +20</option>
</select>
mail.html
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div ng-controller="ContactController" class="panel-body">
<form ng-submit="submit(contactform)" name="contactform" method="post" action="" class="form-horizontal" role="form">
<div class="steps stepOneWhite" id="stepOne">
<div class="form-group" ng-class="{ 'has-error': contactform.inputPrice.$invalid && submitted }">
<div class="col-lg-10">
<select ng-model="formData.inputPrice" type="number" class="form-control inputForm fa fa-input" id="inputPrice" name="inputPrice" placeholder="How many scooters?" required>
<option value="" disabled="disabled" selected="selected">Prices</option>
<option value="1 / 2 hour = 20,-">1 / 2 hour = 20,-</option>
<option value="1 day = 30,-">1 day = 30,-</option>
<option value="2 days = 55,-">2 days = 55,</option>
<option value="3+ dagen = +20,-">3+ dagen = +20</option>
</select>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputGuests.$invalid && submitted }">
<div class="col-lg-10">
<input ng-model="formData.inputGuests" type="number" class="form-control inputForm fa fa-input" id="inputGuests" name="inputGuests" placeholder="How many scooters?" required>
</div>
</div>
<h2>Pick up</h2>
<div class="form-group" ng-class="{ 'has-error': contactform.inputDate.$invalid && submitted }">
<div class="col-lg-10">
<input ng-model="formData.inputDate" type="datetime-local" class="form-control inputForm fa fa-input" id="inputDate" name="inputDate" placeholder="Your Date" required>
</div>
</div>
<h2>Return</h2>
<div class="form-group" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<div class="col-lg-10">
<input ng-model="formData.inputMessage" type="datetime-local" class="form-control inputForm fa fa-input" rows="4" id="inputMessage" name="inputMessage" placeholder="&#xf075" required></input>
</div>
</div>
</div>
<div class="steps stepTwoWhite" id="stepTwo">
<h2>Your Information</h2>
<div class="form-group" ng-class="{ 'has-error': contactform.inputName.$invalid && submitted }">
<div class="col-lg-10">
<input ng-model="formData.inputName" type="text" class="form-control inputForm fa fa-input" id="inputName" name="inputName" placeholder="&#xf007" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<div class="col-lg-10">
<input ng-model="formData.inputEmail" type="email" class="form-control inputForm fa fa-input" id="inputEmail" name="inputEmail" placeholder="&#xf0e0" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputNumber.$invalid && submitted }">
<div class="col-lg-10">
<input ng-model="formData.inputNumber" type="number" class="form-control inputForm fa fa-input" id="inputNumber" name="inputNumber" placeholder="&#xf095" required>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-primary btn-lg btn-block submitInputWhite" id="submitInput" ng-disabled="submitButtonDisabled">
Send Message
</button>
<span id="rentButton" class="btn btn-primary btn-lg btn-block rentButtonWhite" onclick="rentNowWhite()">Rent!</span>
</div>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
</div>
</div>
</div>
contact-form.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['inputNumber']) && isset($_POST['inputGuests']) && isset($_POST['inputDate']) && isset($_POST['inputMessage']) && isset($_POST['inputPrice'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputNumber']) || empty($_POST['inputGuests']) || empty($_POST['inputDate']) || empty($_POST['inputMessage']) || empty($_POST['inputPrice']) ) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress('salman-1992#hotmail.com'); //recipient
$mail->Subject = "Nieuwe reservering is binnengekomen";
$mail->Body = "Nieuwe reservering:". "\r\n\r\nNaam: " . $_POST['inputName'] . "\r\n\r\nTelefoonnummer: " . $_POST['inputNumber'] ."\r\n\r\nAantal Gasten: " . $_POST['inputGuests'] ."\r\n\r\nDatum: " . $_POST['inputDate'] . $_POST['inputMessage'] . $_POST['inputPrice']);
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
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.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';
} 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';
}
}
});

Related

inserting a blank row before inserting the correct one mysql

I am working on a angular5 / php backend project, and I am having an issue where I have a registration form, when the user registers it creates a blank row (empty strings values) in the user table followed by the correct row (colomn values).
The following is my form:
<form *ngIf="!isLogin" (submit)="onRegisterSubmit()" [formGroup]="registerForm">
<div class="form-control">
<input type="text" name="firstname" id="firstname" class="form-control" placeholder="Firstname" formControlName="fn">
<div class="throw_error" *ngIf="registerForm.controls.fn.invalid && registerForm.controls.fn.touched">
<div *ngIf="registerForm.controls.fn.errors?.required">This field is required</div>
<div *ngIf="registerForm.controls.fn.errors?.minlength">This field must be at least 3 characters</div>
<div *ngIf="registerForm.controls.fn.errors?.maxlength">This field must have at most 10 characters</div>
</div>
</div>
<div class="form-control">
<input type="text" name="lastname" id="lastname" class="form-control" placeholder="Lastname" formControlName="ln">
<div class="throw_error" *ngIf="registerForm.controls.ln.invalid && registerForm.controls.ln.touched">
<div *ngIf="registerForm.controls.ln.errors?.required">This field is required</div>
<div *ngIf="registerForm.controls.ln.errors?.minlength">This field must be at least 3 characters</div>
<div *ngIf="registerForm.controls.ln.errors?.maxlength">This field must have at most 10 characters</div>
</div>
</div>
<div class="form-control">
<input type="email" name="email2" id="email2" class="form-control" placeholder="Email Address" formControlName="email2">
<div class="throw_error" *ngIf="registerForm.controls.email2.invalid && registerForm.controls.email2.touched">
<div *ngIf="registerForm.controls.email2.errors?.required">This field is required</div>
<div *ngIf="registerForm.controls.email2.errors?.email && !registerForm.controls.email2.errors?.required">This email is invalid</div>
</div>
</div>
<div class="form-control">
<input type="password" name="password2" id="password2" class="form-control" placeholder="Password" formControlName="password2">
<div class="throw_error" *ngIf="registerForm.controls.password2.invalid && registerForm.controls.password2.touched">
<div *ngIf="registerForm.controls.password2.errors?.required">This field is required</div>
<div *ngIf="registerForm.controls.password2.errors?.minlength">This field must be at least 6 characters</div>
<div *ngIf="registerForm.controls.password2.errors?.maxlength">This field must have at most 15 characters</div>
</div>
</div>
<div class="form-control">
<input type="password" name="confirmPassword" id="confirm-password" class="form-control" placeholder="Confirm Password" formControlName="confPass">
<div class="throw_error" *ngIf="registerForm.controls.confPass.touched && registerForm.controls.confPass.errors?.MatchPassword">Passwords do not match</div>
</div>
<div class="form-control">
<div class="row">
<div class="col-sm-3"></div>
<div class="col-sm-6">
<input type="submit" name="register-submit" id="register-submit" [disabled]="registerForm.invalid"
class="form-control btn btn-register" value="Submit">
<span class="throw_error" id="success">{{resultReg}}</span>
</div>
<div class="col-sm-3"></div>
</div>
</div>
</form>
This is my typescript code for the registration function:
onRegisterSubmit() {
const regFormValue = this.registerForm.value;
this.http.post("http://localhost/ProjetErgonomie/RegUser.php", regFormValue)
.subscribe(data => {
this.receivedData = data;
if (this.receivedData.success) {
this.resultReg = "User added successfully";
} else {
this.resultReg = this.receivedData.errors;
}
}, (error) => {
console.log(error);
});
}
And this is my RegUser.php page:
<?php
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Origin: *");
require_once ('./DBConnect.php');
$conn = mysqli_connect($servername, $username, $password, $db ,$port);
$regUserData = json_decode(file_get_contents("php://input"),true);
$fn = $regUserData['fn'];
$ln = $regUserData['ln'];
$email = $regUserData['email2'];
$pass = $regUserData['password2'];
$confPass = $regUserData['confPass'];
$errorsReg = "";
$dataReg=array();
if($fn === '' || $ln === '' || $email === '' || $pass === '' || $confPass === ''){
$errorsReg = 'Please fill all fields';
$dataReg['success'] = FALSE;
}
else{
$checkUserQuery = "select * from user where Email = '".$email."'";
$result = $conn->query($checkUserQuery);
if(mysqli_num_rows($result)>0){
$errorsReg = 'User already exists';
$dataReg['success'] = FALSE;
}
else{
$sql = "INSERT INTO user (Firstname, Lastname, Email, Password, NewUser)
VALUES ('".$fn."','".$ln."','".$email."','".md5($pass)."',1)";
mysqli_query($conn,$sql);
$dataReg['success'] = TRUE;
}
}
$dataReg['errors']=$errorsReg;
echo json_encode($dataReg);
can you please tell me why am I getting a blank row before having the correct row inserted?

Internal Server Error while doing an insertion in Codeigniter

I am working on a simple CRUD application using Codeigniter, and this section of code was working perfectly well until I added more functions.
Here is the problem:
I was adding 3 items to the database from user inputs, and it had no error. But when I added more input fields to get more inputs from the user, I ended up getting an Internal Server Error when I click on the "Add Item" button.
Below is the View Code:
<?php
if ($_SESSION[AppStrings::$NOMENCLATURE] != AppStrings::$SERVICE) {
if ($_SESSION[AppStrings::$SIZE] != AppStrings::$MICRO) {
?>
<form data-toggle="validator" class="form-horizontal form-material" method="post" action="#" onsubmit="addProduct(); return false;">
<div class="form-group m-t-40">
<div class="col-xs-12">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-barcode-scan"></i></div>
<input class="form-control" type="text" required="" placeholder=" <?= $nomenclature ?> Code" id="product_code" required/>
</div>
</div>
</div>
<div class="form-group m-t-40">
<div class="col-md-6">
<input class="form-control" type="text" required="" placeholder="<?= $nomenclature ?> Name" id="product_name" required/>
</div>
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-currency-ngn"></i></div>
<input class="form-control" type="number" required="" placeholder=" <?= $nomenclature ?> Cost Price" name="product_cp" id="product_cp" required/>
</div>
</div>
</div>
<div class="form-group m-t-40">
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-currency-ngn"></i></div>
<input class="form-control" type="number" required="" placeholder=" <?= $nomenclature ?> Selling Price" name="product_sp" id="product_sp" required/>
</div>
</div>
</div>
<div class="form-group m-t-40">
<div class="col-md-6">
<textarea class="form-control" type="text" required="" placeholder=" <?= $nomenclature ?> Description" id="product_des" required/></textarea>
</div>
<div class="col-md-6">
<input class="form-control" type="text" required="" placeholder=" <?= $nomenclature ?> Expiry Date" id="product_exp" onfocus="(this.type = 'date')" onblur="if (this.value == '') {
this.type = 'text'
}" required/>
</div>
</div>
<div class="form-group m-t-40">
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-clipboard-account"></i></div>
<select name="supplier" class="form-control form-control-line" type="text" id="supplier" placeholder="<?= $nomenclature ?> Supplier">
<option value="">Supplier</option>
<?php
foreach ($suppliers as $supplier) {
?>
<option value='<?= $supplier[DbStrings::$SUPPLIER_NAME] ?>'><?= $supplier[DbStrings::$SUPPLIER_NAME] ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-chevron-double-up"></i></div>
<select name="department" class="form-control form-control-line" type="text" id="department" placeholder="<?= $nomenclature ?> Department">
<option value="">Department</option>
<?php
foreach ($departments as $department) {
?>
<option value='<?= $department[DbStrings::$DEPARTMENT_NAME] ?>'><?= $department[DbStrings::$DEPARTMENT_NAME] ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="form-group m-t-40">
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-chevron-up"></i></div>
<select name="sub_departments" class="form-control form-control-line" type="text" id="sub_department" placeholder="<?= $nomenclature ?> Department">
<option value="">Sub-Department</option>
<?php
foreach ($sub_departments as $sub_department) {
?>
<option value='<?= $sub_department[DbStrings::$SUB_DEPARTMENT_NAME] ?>'><?= $sub_department[DbStrings::$SUB_DEPARTMENT_NAME] ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-cash"></i></div>
<input class="form-control" type="number" placeholder=" <?= $nomenclature ?> Vat" id="vat"/>
</div>
</div>
</div>
<div class="form-group text-center m-t-20">
<div class="col-xs-12">
<button class="btn btn-primary btn-login btn-lg btn-block text-uppercase waves-effect waves-light" type="submit" name="product-btn">Add <?= $nomenclature ?></button>
</div>
</div>
</div> <!-- added in the edit -->
</div> <!-- added in the edit -->
</form>
<?php
}
}
?>
Here is the AJAX code:
function addProduct() {
var product_code = $("#product_code").val();
var product_name = $("#product_name").val();
var product_cp = $("#product_cp").val();
var product_sp = $("#product_sp").val();
var product_des = $("#product_des").val();
var product_exp = $("#product_exp").val();
var supplier = $("#supplier").val();
var department = $("#department").val();
var sub_department = $("#sub_department").val();
var vat = $("#vat").val();
var addUrl = "home/addproduct";
addUrl += "/" + product_code;
addUrl += "/" + product_name;
addUrl += "/" + product_cp;
addUrl += "/" + product_sp;
addUrl += "/" + product_des;
addUrl += "/" + product_exp;
addUrl += "/" + supplier;
addUrl += "/" + department;
addUrl += "/" + sub_department;
addUrl += "/" + vat;
$.ajax({type: 'GET', url: addUrl, data: {},
success: function (result) {
$.alert({
content: result
});
$("#product_code").val("");
$("#product_name").val("");
$("#product_cp").val("");
$("#product_sp").val("");
$("#product_des").val("");
$("#product_exp").val("");
$("#supplier").val("");
$("#department").val("");
$("#sub_department").val("");
$("#vat").val("");
location.reload();
},
error: function (xhr, status, error) {
$.alert({
content: 'Could not complete the process. ' + error
});
}
});
}
Here is the Controller Function:
private function addproduct($product_code = null, $product_name = null, $product_cp = null, $product_sp = null, $product_des = null, $product_exp = null, $supplier = null, $department = null, $sub_department = null, $vat = null) {
if (isset($product_code, $product_name, $product_cp, $product_sp, $product_des, $product_exp, $supplier, $department, $sub_department, $vat)) {
$email = $_SESSION[DbStrings::$EMAIL];
$product_code = $this->test_input($product_code);
$product_name = $this->test_input($product_name);
$product_cp = $this->test_input($product_cp);
$product_sp = $this->test_input($product_sp);
$product_des = $this->test_input($product_des);
$supplier = $this->test_input($supplier);
$department = $this->test_input($department);
$sub_department = $this->test_input($sub_department);
$vat = $this->test_input($vat);
$product_exp = strtotime($product_exp);
$insertedProduct = $this->member->insertProduct($email, $product_code, $product_name, $product_cp, $product_sp, $product_des, $supplier, $department, $sub_department, $vat, $product_exp);
if ($insertedProduct) {
echo "Your " . $_SESSION[AppStrings::$NOMENCLATURE] . " has been added succesfully";
} else {
echo "There was a problem inserting your " . $_SESSION[AppStrings::$NOMENCLATURE] . ". Please try again.";
}
} else {
echo 'Please fill all fields';
}
}
And this is the Model that does the insertion before sending back a result:
public function insertProduct($email, $product_code, $product_name, $product_cp, $product_sp, $product_des, $supplier, $department, $sub_department, $vat, $product_exp) {
$data = array(
DbStrings::$PRODUCTID => "",
DbStrings::$EMAIL => $email,
DbStrings::$PRODUCT_CODE => $product_code,
DbStrings::$PRODUCT_NAME => $product_name,
DbStrings::$PRODUCT_COST => $product_cp,
DbStrings::$PRODUCT_SELLING => $product_sp,
DbStrings::$PRODUCT_MARKUP => 9,
DbStrings::$PRODUCT_DESCRIPTION => $product_des,
DbStrings::$SUPPLIER => $supplier,
DbStrings::$DEPARTMENT => $department,
DbStrings::$SUB_DEPARTMENT => $sub_department,
DbStrings::$VAT => $vat,
DbStrings::$STOCK_BALANCE => 1,
DbStrings::$MIN_LEVEL => 1,
DbStrings::$MAX_QUANTITY => 1,
DbStrings::$QUANTITY_SOLD => 1,
DbStrings::$EXPIRY_DATE => $product_exp,
DbStrings::$DATE_CREATED => time(),
DbStrings::$DATE_STOCKED => time()
);
return $this->db->insert(DbStrings::$PRODUCTS_TABLE_NAME, $data);
}
I still get an error from the server, and don't know what else to do.
Correcting the above issue, the code works fine. I used: $this->output->enable_profiler(TRUE); and i was able to see the MySQL query sent by the model to the server, and when i copied the query and pasted it in my localhost:phpmyadmin, i got flagged for errors and there seem to be no syntax error.
Now this is creeping me out, as i can't fix it.

Angular ajax submit form

I am having problem with ajax submit form with angular, when i click submit my entire page is reloaded?
Where can be the problem, here is my code
/*
Create the controller and inject Angular's $scope
*/
// resource2Controller
(function () {
'use strict';
angular.module("aluPlanetApp").controller('resource2Controller', resource2Controller);
resource2Controller.$inject = ['$scope'];
resource2Controller.$inject = ['$http'];
function resource2Controller($scope, $http) {
activate();
function activate() {
$scope.title = 'Contact';
$scope.id = '2';
$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.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';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result = 'bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed <img src="http://www.chaosm.net/blog/wp-includes/images/smilies/icon_sad.gif" alt=":(" class="wp-smiley"> Please fill out all the fields.';
$scope.result = 'bg-danger';
}
}
}
}
})();
And contact-form.php
<?php
require_once 'phpmailer/PHPMailerAutoload.php';
if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['inputSubject']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress('something#test.com'); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\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' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
HTML
<div ng-controller="resource2Controller" class="panel-body">
<form ng-submit="submit(contactform)" name="contactform" method="post" action="" class="form-horizontal" role="form">
<div class="form-group" ng-class="{ 'has-error': contactform.inputName.$invalid && submitted }">
<label for="inputName" class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input ng-model="formData.inputName" type="text" class="form-control" id="inputName" name="inputName" placeholder="Your Name" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<label for="inputEmail" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email" >
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<label for="inputSubject" class="col-lg-2 control-label">Subject</label>
<div class="col-lg-10">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<label for="inputMessage" class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-default" ng-disabled="submitButtonDisabled">
Send Message
</button>
</div>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
</div>
Mhh I belive that maybe your problem is in the HTML which I can't see right now so make sure that you are not using the submit button. I mean Instead of <input type="submit"... use <input type="button"...Here is a reference How do I make an HTML button not reload the page
On your HTML, you call your controller ContactController while at the Angular side you call it resource2Controller. Those two should match or Angular doesn't know what to do.

Contactform.php not sending all inputs

I have a contact form that is working fine, it sends the email except that it doesn't post the email address of the person that sends it. I have no idea why, I tried changing the $from variable and nothing changes. Is there something obvious I am missing?
It is the input with the id c_email which is put into the $from variable that I do not receive in the emails sent by this form.
My contactform.php:
<?php
// Contact
$to = 'myemail#gmail.com';
$subject = 'Portfolio ContactForm';
if(isset($_POST['c_name']) && isset($_POST['c_email']) && isset($_POST['c_message'])){
$name = $_POST['c_name'];
$from = $_POST['c_email'];
$message = $_POST['c_message'];
if (mail($to, $subject, $from, $name, $message)) {
$result = array(
'message' => 'Sent, thanks!',
'sendstatus' => 1
);
echo json_encode($result);
} else {
$result = array(
'message' => 'Ooops, problem..',
'sendstatus' => 1
);
echo json_encode($result);
}
}?>
On my html page:
<form id="contact-form" role="form">
<div class="form-group">
<label class="sr-only" for="c_name">Name</label>
<input type="text" id="c_name" class="form-control" name="c_name" placeholder="Nom">
</div>
<div class="form-group">
<label class="sr-only" for="c_email">Email address</label>
<input type="email" id="c_email" class="form-control" name="c_email" placeholder="E-mail">
</div>
<div class="form-group">
<textarea class="form-control" id="c_message" name="c_message" rows="7" placeholder="Votre message"></textarea>
</div>
<button type="submit" class="btn btn-custom-1">
<i class="fa fa-bullhorn icon-before"></i> Envoyer
</button>
</form>
Your values is not posting because in your form you not mention method="POST".Just try like this.it should work
<form id="contact-form" role="form" action="" method="POST">
<div class="form-group">
<label class="sr-only" for="c_name">Name</label>
<input type="text" id="c_name" class="form-control" name="c_name" placeholder="Nom">
</div>
<div class="form-group">
<label class="sr-only" for="c_email">Email address</label>
<input type="email" id="c_email" class="form-control" name="c_email" placeholder="E-mail">
</div>
<div class="form-group">
<textarea class="form-control" id="c_message" name="c_message" rows="7" placeholder="Votre message"></textarea>
</div>
<button type="submit" class="btn btn-custom-1">
<i class="fa fa-bullhorn icon-before"></i> Envoyer
</button>
</form>
<script>
$('button').click(function() {
var c_name = $("#c_name").val();
var c_email = $("#c_email").val();
var c_message = $("#c_message").val();
$.ajax({//create an ajax request to load_page.php
type: "POST",
url: "assets/php/contactForm.php",
data:{"c_name":c_name,"c_email":c_email,"c_message":c_message},
success: function(data) {
if (data) {
alert(data);
}
else {
alert('Successfully not posted.');
}
}
});
});
</script>

Succeeding submission of contact form

Hi I have a contact form using PHP AJAX but filling the form, it is successful but when I try to fillup again the form it is not submitting unless I refresh the page, it will go back to normal again. What will be the problem of this?
Thanks
HTML Code
<form role="form" id="feedbackForm" method="POST">
<div class="col-lg-6">
<div class="form-group">
<label class="control-label" for="textinput">First Name<span class="required">*</span></label>
<input type="text" class="form-control required" id="first_name" name="first_name" placeholder="Enter your First Name"/>
<span class="help-block" style="display: none;">Please enter your first name.</span>
</div>
<div class="form-group">
<label class="control-label" for="textinput">Last Name<span class="required">*</span></label>
<input type="text" class="form-control" id="last_name" name="last_name" placeholder="Enter your Last Name"/>
<span class="help-block" style="display: none;">Please enter your last name.</span>
</div>
<div class="form-group">
<label class="control-label" for="textinput">Email Address<span class="required">*</span></label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter your email address"/>
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
</div>
<div id="companyname_con" class="form-group">
<label class="control-label" for="textinput">Company Name</label>
<input type="text" class="form-control" id="company_name" name="company_name" placeholder="Enter your company name">
</div>
<div class="form-group">
<label class="control-label" for="textinput">Message<span class="required">*</span></label>
<textarea rows="10" cols="100" class="form-control" id="contact_message" name="contact_message" placeholder="Enter your message"></textarea>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="selectbasic">How did you hear about us?</label>
<select id="selectbasic" name="selectbasic" class="form-control">
<option value="None">Select</option>
<option value="Search Engine">Search engine</option>
<option value="Microsoft DPE">Microsoft DPE</option>
<option value="Microsoft Event">Microsoft event</option>
<option value="Social Media">Social media</option>
<option value="Word of Mouth">Word of mouth</option>
<option value="Other">Other</option>
</select>
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="emailUpdates" name="emailUpdates" value="Yes"> Please keep me informed of kinectAPI product updates and news
</label>
</div>
<img id="captcha" src="library/vender/securimage/securimage_show.php" alt="CAPTCHA Image" />
Show a Different Image<br/>
<div class="form-group" style="margin-top: 10px;">
<input type="text" class="form-control" name="captcha_code" id="captcha_code" placeholder="For security, please enter the code displayed in the box." />
<span class="help-block" style="display: none;">Please enter the code displayed within the image.</span>
</div>
<span class="help-block" style="display: none;">Please enter a the security code.</span>
<button type="submit" id="feedbackSubmit" class="btn btn-purple btn-md message-btn">Submit Message</button>
</div>
</form>
PHP Code
<?php
//start a session -- needed for Securimage Captcha check
session_start();
//add you e-mail address here
define("MY_EMAIL", "dummy#email.com");
/**
* Sets error header and json error message response.
*
* #param String $messsage error message of response
* #return void
*/
function errorResponse ($contact_message) {
header('HTTP/1.1 500 Internal Server Error');
die(json_encode(array('message' => $contact_message)));
}
/**
* Return a formatted message body of the form:
* Name: <name of submitter>
* Comment: <message/comment submitted by user>
*
* #param String $name name of submitter
* #param String $messsage message/comment submitted
*/
function setMessageBody ($first_name, $last_name, $email, $company_name,
$contact_message, $selectbasic) {
$message_body .= "First Name: " . $first_name."\n\n";
$message_body .= "Last Name: " . $last_name."\n\n";
$message_body .= "Email: " . $email."\n\n";
$message_body .= "Company Name:" . $company_name."\n\n";
$message_body .= "Message:" . $contact_message. "\n\n";
$message_body .= "How did you hear about us?" . $selectbasic."\n\n";
return $message_body;
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$company_name = $_POST['company_name'];
$contact_message = $_POST['contact_message'];
$selectbasic = $_POST['selectbasic'];
header('Content-type: application/json');
//do some simple validation. this should have been validated on the client-side also
if (empty($email) || empty($contact_message)) {
errorResponse('Email or message is empty.');
}
//do Captcha check, make sure the submitter is not a robot:)...
include_once './vender/securimage/securimage.php';
$securimage = new Securimage();
if (!$securimage->check($_POST['captcha_code'])) {
errorResponse('Invalid Security Code');
}
//try to send the message
if(mail(MY_EMAIL, "Contact Form Results", setMessageBody($_POST["first_name"],
$_POST["last_name"], $_POST["email"], $_POST["company_name"], $_POST["contact_message"],
$_POST["selectbasic"]), "From: $email")) {
echo json_encode(array('message' => 'Your message was successfully sent'));
} else {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(array('message' => 'Unexpected error while attempting to send e-
mail.'));
}
?>
JS code
$(document).ready(function() {
$("#feedbackSubmit").click(function() {
//clear any errors
contactForm.clearErrors();
//do a little client-side validation -- check that each field has a value and e-mail field is in proper format
var hasErrors = false;
$('#feedbackForm input,textarea').each(function() {
if (!$(this).val()) {
hasErrors = true;
contactForm.addError($(this));
}
});
var $email = $('#email');
if (!contactForm.isValidEmail($email.val())) {
hasErrors = true;
contactForm.addError($email);
}
//if there are any errors return without sending e-mail
if (hasErrors) {
return false;
}
//mailchimp trigger
if($('#emailUpdates').prop('checked')) {
$.ajax({
type: "POST",
url: 'subscribe.php',
data: 'ajax=true&email=' + escape($('#email').val())
});
}
//send the feedback e-mail
$.ajax({
type: "POST",
url: "library/sendmail.php",
data: $("#feedbackForm").serialize(),
success: function(data)
{
contactForm.addAjaxMessage(data.message, false);
//get new Captcha on success
$('#captcha').attr('src', 'library/vender/securimage/securimage_show.php?' +
Math.random());
},
error: function(response)
{
contactForm.addAjaxMessage(response.responseJSON.message, true);
}
});
$('#feedbackForm input,textarea,select').val('');
return false;
});
});
//namespace as not to pollute global namespace
var contactForm = {
isValidEmail: function (email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
},
clearErrors: function () {
$('#emailAlert').remove();
$('#feedbackForm .help-block').hide();
$('#feedbackForm .form-group').removeClass('has-error');
},
addError: function ($input) {
$input.siblings('.help-block').show();
$input.parent('.form-group').addClass('has-error');
},
addAjaxMessage: function(msg, isError) {
$("#feedbackSubmit").after('<div id="emailAlert" class="alert alert-' + (isError ?
'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() +
'</div>');
}
};

Categories