PHP Response line break - php

Yes, I am mentally challenged tonight.
If anyone could help, that'd be very cool.
I just need to add a line break to the php string of a return message after the 'out'.
PHP FILE
// CHANGE THE TWO LINES BELOW
$email_to = "m.wolf#me.com";
$email_subject = "message submission";
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$message = $_POST['message']; // required
$email_message = "Form details below.nn";
$email_message .= "Name: ".$name."n";
$email_message .= "Email: ".$email_from."n";
$email_message .= "Message: ".$message."n";
$headers = 'From: '.$email_from."rn".
'Reply-To: '.$email_from."rn" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
}
// return all our data to an AJAX call
echo json_encode($data);
JS FILE
scotchApp.controller('FormController',function($scope, $http) {
// creating a blank object to hold our form information.
//$scope will allow this to pass between controller and view
$scope.formData = {};
// submission message doesn't show when page loads
$scope.submission = false;
// Updated code thanks to Yotam
var param = function(data) {
var returnString = '';
for (d in data){
if (data.hasOwnProperty(d))
returnString += d + '=' + data[d] + '&';
}
// Remove last ampersand and return
return returnString.slice( 0, returnString.length - 1 );
};
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'process.php',
data : param($scope.formData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorName = data.errors.name;
$scope.errorEmail = data.errors.email;
$scope.errorTextarea = data.errors.message;
$scope.submissionMessage = data.messageError;
$scope.submission = true; //shows the error message
} else {
// if successful, bind success message to message
$scope.submissionMessage = data.messageSuccess;
$scope.formData = {}; // form fields are emptied with this line
$scope.submission = true; //shows the success message
}
});
I just can't seem to make it work.
terribly entry level, I know.
If it helps: I am using php/angular/bootstrap.
Anyway. thanks.

One way would be using PHP_EOL constant and nl2br function:
<?php
$data['messageSuccess'] = 'Thanks for reaching out'.PHP_EOL.' We will contact you shortly. ';
echo nl2br($data['messageSuccess']);
?>
or using \n :
<?php
$data['messageSuccess'] = "Thanks for reaching out.\n We will contact you shortly.";
echo nl2br($data['messageSuccess']);
?>
If you don't have error reporting enabled, and it seems you don't, you can do it like this:
<?php
// Turn off error reporting
error_reporting(0);
// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>

Use <br /> or \n to "force" a new line. Or you can wrap your sentence into <p> tags like this:
$data['messageSuccess'] = '<p>Thanks for reaching out.</p> <p>We will contact you shortly. </p>';

Related

AngularJS PHP contact cannot read property name

Basically I have a contact form made with angularJS and PHP. and thats hosted on 000webhost. When I'm sending a mail the mail goes through but it also gives me an error. I think thats the reason it doesnt display MessageSuccess or MessageError messages.
TypeError: Cannot read property 'name' of undefined
at app.js:119
at angular.min.js:81
at angular.min.js:112
at m.$get.m.$eval (angular.min.js:126)
at m.$get.m.$digest (angular.min.js:123)
at m.$get.m.$apply (angular.min.js:127)
at l (angular.min.js:81)
at P (angular.min.js:85)
at XMLHttpRequest.H.onload (angular.min.js:86)
the HTML:
<div id="websiteApp" class="contactRow" style="display: none;">
<form ng-submit="submitForm()" ng-controller="FormController" novalidate class="contactForm" name="form" ng-hide="loaded">
<input class="input" type="text" name="name" placeholder="SINU NIMI" ng-model="formData.name" ng-class="{'error' : errorName}">
<input class="input2" type="email" name="email" placeholder="SINU E-MAIL" ng-model="formData.email" ng-class="{'error' : errorEmail}">
<textarea name="message" ng-class="{'error' : errorTextarea}" placeholder="KIRJUTA MEILE" ng-model="formData.message" rows="5"></textarea>
<input class="saada" type="submit" value="SAADA!" name="submit">
<div ng-class="{'submissionMessage' : submission}" ng-bind="submissionMessage"></div>
</form>
</div>
App.js
var app = angular.module('kaidoweb', ['ngRoute', 'ngAnimate']).
config(['$routeProvider','$locationProvider', function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/', {
templateUrl: 'pages/index.html',
activetab: 'index',
controller: HomeCtrl
}).
otherwise({ redirectTo: '/' });
}]).run(['$rootScope', '$http', '$browser', '$timeout', "$route", function ($scope, $http, $browser, $timeout, $route) {
$scope.$on("$routeChangeSuccess", function (scope, next, current) {
$scope.part = $route.current.activetab;
});
}]);
/*app.config(['$locationProvider', function($location) {
$location.hashPrefix('!');
}]);*/
//Contact form
app.controller('FormController',function($scope, $http) {
// creating a blank object to hold our form information.
//$scope will allow this to pass between controller and view
$scope.formData = {};
// submission message doesn't show when page loads
$scope.submission = false;
// Updated code thanks to Yotam
var param = function(data) {
var returnString = '';
for (d in data){
if (data.hasOwnProperty(d))
returnString += d + '=' + data[d] + '&';
}
// Remove last ampersand and return
return returnString.slice( 0, returnString.length - 1 );
};
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'process.php',
data : param($scope.formData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorName = data.errors.name;
$scope.errorEmail = data.errors.email;
$scope.errorTextarea = data.errors.message;
$scope.submissionMessage = data.messageError;
$scope.submission = true; //shows the error message
} else {
// if successful, bind success message to message
$scope.submissionMessage = data.messageSuccess;
$scope.formData = {}; // form fields are emptied with this line
$scope.submission = true; //shows the success message
}
});
};
});
and the PHP
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['message']))
$errors['message'] = 'Message is required.';
// return a response ===========================================================
// response if there are errors
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
$data['messageError'] = 'Vaata üle punased alad!';
} else {
// if there are no errors, return a message
$data['success'] = true;
$data['messageSuccess'] = 'Tänan, et kirjutasid. Võtan ühendust nii pea kui saan.';
// CHANGE THE TWO LINES BELOW
$email_to = "email.to#khk.ee";
$email_subject = "KaidoWeb kiri";
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$message = $_POST['message']; // required
$email_message = "Form details below.nn";
$email_message .= "Name: ".$name."n";
$email_message .= "Email: ".$email_from."n";
$email_message .= "Message: ".$message."n";
$headers = 'From: '.$email_from."rn".
'Reply-To: '.$email_from."rn" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
}
// return all our data to an AJAX call
echo json_encode($data);
Also another thing is I also host this site on GoDaddy when trying to send a mail there it says: POST http://www.kaidoweb.com/process.php 403 (Forbidden).
I would be immensely grateful if someone could give me some sort of solution here and if you need to see something more just ask.
This is how your PHP is setting the errors object it is returning to your Angular App:
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['message']))
$errors['message'] = 'Message is required.';
As you can see, in each case it is setting a different key inside of the errors array. In your Angular code you don't account for this, you just assume that all of the keys will be set:
$scope.errorName = data.errors.name;
$scope.errorEmail = data.errors.email;
$scope.errorTextarea = data.errors.message;
You can fix this either in your PHP or in your Angular App. In PHP, you could use an integer array rather than an associative array:
if (empty($_POST['name']))
$errors[] = 'Name is required.';
if (empty($_POST['email']))
$errors[] = 'Email is required.';
if (empty($_POST['message']))
$errors[] = 'Message is required.';
Then in Angular just set the scope variable and modify the view with how it's displayed:
$scope.errors = data.errors;
<ul><li data-ng-repeat="error in errors">{{ error }}</li></ul>
Alternatively, in Angular just check if the keys are set before attempting to access them:
if(data.errors.hasOwnProperty('name') {
$scope.errorName = data.errors.name;
}
Update
I'm talking about this section of your angular code, specifically the case in the success callback where data.success is falsey:
$scope.submitForm = function() {
$http({
method : 'POST',
// ...
})
.success(function(data) {
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errors = data.errors;
$scope.submission = true; //shows the error message
} else {
// ...
}
});
};
Since you're probably binding to e.g. {{ errorName }} in your view template, wherever that is, that will also have to be updated with what I have above if you switch your $error array to return with numerical indices.

Send data from php back to Ajax

So I submit my form with Ajax like so
$("#submitform").click(function(e){
e.preventDefault();
var form_data = $("#contactfrm").serialize();
$.ajax({
type: "POST",
url: "/ltlcreation-new/wordpress/wp-content/themes/LTLCreation/includes/form-handler.php",
data: form_data,
error: function(){
alert("failed");
},
success: function(json_data){
console.log(json_data);
alert("success");
},
})
});
In my form-handler.php i catch the from errors
<?php
if(isset($_POST['submit'])) {
//include validation class
include 'validate.class.php';
//assign post data to variables
$name = #($_POST['name']);
$email = #($_POST['email']);
$message = #($_POST['message']);
$phone = #($_POST["phone"]);
//echo $name, $email, $message, $phone;
//start validating our form
$v = new validate();
$v->validateStr($name, "name", 3, 75);
$v->validateEmail($email, "email");
$v->validateStr($message, "message", 5, 1000);
$v->validateStr($phone, "phone", 11, 13);
if(!$v->hasErrors()) {
$to = "lukelangfield001#googlemail.com";
$subject = "Website contact form ";
$mailbody = $message . "\n" . "from " . $name . "\n" . $phone;
$headers = "From: $email";
mail($to, $subject, $mailbody, $headers);
echo "success";
} else {
//set the number of errors message
$message_text = $v->errorNumMessage();
//store the errors list in a variable
$errors = $v->displayErrors();
//get the individual error messages
//$nameErr = $v->getError("name");
//$emailErr = $v->getError("email");
//$messageErr = $v->getError("message");
//$phoneErr = $v->getError("phone");
echo $message_text; echo $errors;
$output = array($message_text);
echo json_encode($output);
}//end error check
}// end isset
These errors usually look like something like this
There were 4 errors sending your message!
Name must be at least 3 characters long.
Please enter an Email Address.
Message must be at least 5 characters long.
Phone must be at least 11 characters long.
["There were 4 errors sending your message!\n"]
I've tried to jSon encode the output and the in the success in ajax pull the json data out, however it just keeps returning an empty string like so
(an empty string)
My question is can you send data back from PHP to Ajax, if so I am doing this completely wrong?
You can output anything other than the json string so echo "success"; would make t. Use your debuggers Network response output tab to see that this is properly encoded.
Also don't use
$name = #($_POST['name']);
use instead
$name = isset($_POST['name']) ? $_POST['name'] : '';
If you still have a blank page make sure you have display errors set.
error_reporting(E_ALL);
ini_set('display_errors', 1);
I am an idiot I still had this in my PHP file which means the form wasn't firing or returning a response, silly me, glad i finally figured it out though
if(isset($_POST['submit'])) {
Thanks for the help guys
Here is an example of an Ajax contact form you can use:
Ajax.js
$(document).ready(function(){
$("#btn").click(function(){
var username=$("#name").val();
var email=$("#email").val();
var dis=$("#dis").val();
var process=true;
if(username=="")
process=false;
if(email=="")
process=false;
if(dis=="")
process=false;
if(process){
var dataString="name="+username + "&email="+email+ "&message="+dis;
$("#res").html('<span>Sending...</span><img src="a.gif">');
$.ajax({
url:"b.php",
type:"POST",
data:dataString,
success:function(data){
document.getElementById("name").value='';
document.getElementById("email").value='';
document.getElementById("dis").value='';
$("#res").html(data);
}
});
}else{
alert("fill all fields");
}
});
});
and b.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajax") || die("erro");
if(isset($_POST['name'])){
mysql_real_escape_string(htmlentities($name=$_POST['name']));
mysql_real_escape_string(htmlentities($email=$_POST['email']));
mysql_real_escape_string(htmlentities($message=$_POST['message']));
if(!empty($name) && !empty($email) && !empty($message)){
if(mysql_query("INSERT INTO `users` (name,email,message) VALUES('$name','$email','$message') ")){
echo 'The massage has been send';
}else{
echo mysql_error();
}
}
}
?>
enjoy that....
You have the following:
success: function(json_data){
While json_data is simply nothing. It should be
success: function(data){

Post error report by pressing a button jQuery not working

Small problem here, I need to place a button on my 404 page to ask people to submit an error.
The problem is that nothing is actually happens, I mean no mail is received and no errors are displayed, so I am confused.
My report is very basic, it collects all data of what my user did before getting 404
$site = "mySite.com";
$email = "donotreply#mySite.com";
$http_host = $_SERVER['HTTP_HOST'];
$server_name = $_SERVER['SERVER_NAME'];
$remote_ip = $_SERVER['REMOTE_ADDR'];
$request_uri = $_SERVER['REQUEST_URI'];
$cookie = $_SERVER["HTTP_COOKIE"];
$http_ref = $_SERVER['HTTP_REFERER'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$error_date = date("D M j Y g:i:s a T");
$subject = "404 Alert";
$headers = "Content-Type: text/plain"."\n";
$headers .= "From: ".$site." <".$email.">"."\n";
$message = "404 Error Report for ".$site."\n";
$message .= "Date: ".$error_date."\n";
$message .= "Requested URL: http://".$http_host.$request_uri."\n";
$message .= "Cookie: ".$cookie."\n";
$message .= "Referrer: ".$http_ref."\n";
$message .= "User Agent: ".$user_agent."\n";
$message .= "IP Address: ".$remote_ip."\n";
$message .= "Whois: http://ws.arin.net/cgi-bin/whois.pl?queryinput=".$remote_ip;
this is my form, all fields are hidden that are placed in the same file along with php code above
<form name="form" method="POST" id="report-form">
<div class="form">
<input type="hidden" name="message" value="$message">
<div class="done">
<p><strong>Thank you!</strong></p>
</div>
<div class="error">
<p><strong>Error!</strong> Sorry, something went wrong, please try again.</p>
</div>
<input type="hidden" name="visitor" value="">
<input type="hidden" name="submitted" value="submitted">
<input type="submit" name="submit" value="Submit" class="formSubmit" />
</div>
</form>
<script type="text/javascript" src="js/report_validation.js"><\/script>
here is my jQuery validation script, which I am trying to use, which is in the separate file named report_validation.js in js folder
$(document).ready ( function() {
$('.formSubmit').click(function() {
// Store values in variables
var form = $(this).closest('form');
var message = form.find('input[name=message]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
// Organize data
var data = 'message=' + message.val() + '&submitted=' + submitted.val() + '&visitor=' + visitor.val();
var request = $.ajax({
type: "POST",
url: "includes/report_form_mail.php",
data: data,
cache: false,
success: function (html) {
if (html == "true") {
form.find('.done').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function(jqXHR, textStatus, error) {
alert("Form Error: " + error);
}
});
return false;
});
});
here is my mailing script, which is also placed in the separate file and named report_form_mail.php in my incudes folder
// Check if form was submitted
if ($_POST['submitted'] && $_POST['visitor'] == '') {
// If valid, store values in variables
$site = "mySite.com";
$email = "donotreply#mySite.com";
$mes = stripslashes($_POST['message']);
$subject = "404 Alert";
$headers = "Content-Type: text/plain"."\n";
$headers .= "From: ".$site." <".$email.">"."\n";
$message = "Message: $mes";
// Send email
$sent = mail($email, $subject, $message, $headers);
if($sent) {
echo json_encode(true);
} else {
echo "Error: Mail could not be send.";
exit();
}
} else {
echo "Error: There was a problem with submitting the form";
exit();
}
Please help me to figure it all out
I have actually found an error myself.
The jQuery was not loaded to the page correctly so I have corrected it and my form works perfectly fine.
Thanks to all

jQuery Post via Ajax to PHP Validation Script

I know I can use the form validation plugin with jQuery UI but for the sake of teaching myself some new tricks I'm taking this approach.
I have a jQuery script that posts a form to a PHP script via Ajax. The script then validates the input and sends a JSON encoded string back to the script. At this point, based on the status a validation message should be placed into a modal dialog and then opened to tell the user what happened.
Issue
It seems the script is returning a "null" status. In Chrome's JavaScript console the following line appears after clicking on the submit button of the form:
Uncaught TypeError: Cannot read property 'status' of null
Here's my validate_form.js
$(document).ready(function() {
$("#contact_submit").on("click", function(e){
e.preventDefault();
var dataString = $("#frm_contact").serialize();
console.log(dataString);
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
console.log(data);
if(!data){
alert("null value returned");
}else if(data.status > 0){
$("#response").dialog({
autoOpen: false,
modal: true,
height: 240,
width: 320
});
$("#response").dialog("open");
};
}
});
});
});
And here is contact.php
<?php
if(isset($_POST['contact_submit'])){
$name = trim($_POST['contact_name']);
$name = ucwords($name);
$email = trim($_POST['contact_email']);
$email = strtolower($email);
$dept = trim($_POST['contact_dept']);
$dept = ucwords($dept);
$notes = trim($_POST['contact_notes']);
// Patterns and Comparison Qualifiers
$name_pattern = "/^[a-z][a-z ]*$/i";
$email_pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/";
$avail_depts = array("General", "Sales", "Support");
$notes_minlength = 25;
$notes_maxlength = 500;
if(!preg_match($name_pattern, $name)){
$resp = array("status"=>1, "message"=>"Names may only contain letters and spaces");
}else{
if(!preg_match($name_pattern, $name)){
$resp = array("status"=>2, "message"=>"Invalid e-mail address");
}else{
if(!in_array($dept, $avail_depts)){
$resp = array("status"=>3, "message"=>"Please select a department");
}else{
if(strlen($notes) < $notes_minlength || strlen($notes) > $notes_maxlength){
$resp = array("status"=>4, "message"=>"Comments must be between 25 and 500 characters");
}else{
// Build the message and e-mail it
$to = "info#mydomain.com";
$headers = "From: ".$name." <".$email.">";
$message .= "Contact Form Submission\n";
$message .= "==========================\n\n";
$message .= "Contact Name: ".ucwords($name)."\n\n";
$message .= "Contact E-mail: ".$email."\n\n";
$message .= "Category: ".$dept."\n\n";
$message .= "Comments: ".$notes."\n\n";
$message .= "\n";
if(mail($to, $subject, $message, $headers)){
$resp = array("status"=>5, "message"=>"Thanks! We'll be in touch soon!");
}else{
$resp = array("status"=>6, "message"=>"Something went wrong, please try again");
}
}
}
}
}
}
echo json_encode($resp);
?>
UPDATE 1
Adding console.log(dataString); yields the following in the console:
contact_name=Test&contact_email=testaccount%40mydomain.com&contact_dept=general&contact_notes=this+is+a+test+
As you can see it should've failed on the notes not being between 25 and 500 characters and returned the proper error message. Instead I still see the "cannot read property 'status' of (null)"
UPDATE 2
Here is exactly what I see in the JavaScript Console
UPDATE 3
I decided to remove the prevent default and actually post directly to the contact page through a traditional <form> statement that includes the method="post" action="contact.php" to see if the script itself was properly generating the JSON string and it is; here's what it generated on my most recent test:
{"status":4,"message":"Comments must be between 25 and 500 characters"}
So either it's not sending it back to the ajax handler or something else is missing.
UPDATE 4
I modified the script to handle a null value and alert me if no value was passed. So it's obvious now that the script isn't passing a json string back to the ajax call even though in update 3 I've verified that it's echoing one to the screen. I'm at a loss... (Update script above)
UPDATE 5
So I've made some progress. It turns out that the null was being returned because in my PHP script I was checking if the submit button was set and part of the $_POST array. But, because I'm preventing the default action of the form through jQuery it's not being passed. Only the form values that are serialized are being sent in the dataString. So now I'm getting the errors back in the console that I expect but I'm not getting the modal dialog to show up. The drama continues.
Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is simple:
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
For the browsers that don't you can implement it using json2.js.
As noted you're already using jQuery, there is a $.parseJSON function that maps to JSON.parse if available or a form of eval in older browsers. However, this performs additional, unnecessary checks that are also performed by JSON.parse, so for the best all round performance I'd recommend using it like so:
var json = '{"result":true,"count":1}',
obj = JSON && JSON.parse(json) || $.parseJSON(json);
This will ensure you use native JSON.parse immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.
Below i've mentioned some points try this to sort out your problem
1.change your method to get and try.
2.put die() after last echo and check what the exactly output.
So after more hours tweaking, testing, and pulling my hair out, here's the working script.
jQuery
$(document).ready(function() {
$("#contact_submit").on("click", function(e){
e.preventDefault();
var dataString = $("#frm_contact").serialize();
console.log(dataString);
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
console.log(data);
if(!data){
alert("null value returned");
}else if(data.err > 0){
var $response = $("<div></div>")
.dialog({
resizable: false,
autoOpen: false,
modal: true,
height: "auto",
width: "auto",
buttons: { "ok": function() { $(this).dialog("close"); } }
});
$response.html("Error:");
$response.html(data.message);
$response.dialog("open");
$(".ui-dialog-titlebar").hide();
};
}
});
});
});
And for the PHP script I had to tweak it slightly as well to process it properly.
<?php
$name = trim(urldecode($_POST['contact_name']));
$name = ucwords($name);
$email = trim(urldecode($_POST['contact_email']));
$email = strtolower($email);
$dept = trim($_POST['contact_dept']);
$dept = ucwords($dept);
$notes = trim(urldecode($_POST['contact_notes']));
// Patterns and Comparison Qualifiers
$name_pattern = "/^[a-z][a-z ]*$/i";
$email_pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/";
$avail_depts = array("General", "Sales", "Support");
$notes_minlength = 25;
$notes_maxlength = 500;
if(!preg_match($name_pattern, $name)){
$resp = array("err"=>1, "message"=>"Names may only contain letters and spaces");
}else{
if(!preg_match($email_pattern, $email)){
$resp = array("err"=>2, "message"=>"Invalid e-mail address");
}else{
if(!in_array($dept, $avail_depts)){
$resp = array("err"=>3, "message"=>"Please select a department");
}else{
if(strlen($notes) < $notes_minlength || strlen($notes) > $notes_maxlength){
$resp = array("err"=>4, "message"=>"Comments must be between 25 and 500 characters");
}else{
// Build the message and e-mail it
$headers = "From: ".$name." <".$email.">";
$message .= "Contact Form Submission\n";
$message .= "==========================\n\n";
$message .= "Contact Name: ".ucwords($name)."\n\n";
$message .= "Contact E-mail: ".$email."\n\n";
$message .= "Category: ".$dept."\n\n";
$message .= "Comments: ".$notes."\n\n";
$message .= "\n";
if(mail($to, $subject, $message, $headers)){
$resp = array("err"=>5, "message"=>"Thanks! We'll be in touch soon!");
}else{
$resp = array("err"=>6, "message"=>"Something went wrong, please try again");
}
}
}
}
}
echo json_encode($resp);
?>
Everything works perfectly, modal alerts and all to the user. Thanks to those who attempted to help!

Why is this AJAX call to the correct php script not returning anything?

I posted a similar question earlier, just I did not realize that the code I put had an obvious bug in it (not supplying the data) which I new existed. Now I am redoing it with that because I am still having the problem.
I have this AJAX:
function sendMail(){
$.ajax({
type: "POST",
url: "../prestige-auto/php/sendMail.php",
data: {"message" : $('#contactMessage').html(),
"email" : $('#contactEmail').val(),
"name" : $('#contactName').val()},
success: function(result){
if (result == 'success') {
alert(result);
} else {
alert(result);
}
}
});
};
$('#submitContact').click(function(){
sendMail();
})
and this PHP:
<?php
$trimmed = array_map('trim', $_POST);
$message = $trimmed['message'];
$email = $trimmed['email'];
$name = $trimmed['name'];
if (empty($message)) {
$message = FALSE;
}
if (empty($email)) {
$message = FALSE;
}
if (empty($name)) {
$message = FALSE;
}
if ($message && $email && $name){
$body = "From: $name.\n \n $message";
mail(/*some email*/, 'Website Contact Form Submission', $body, "From: $email");
echo ('success');
}
echo($message.' '.$email.' '.$name);
?>
All the html elements defined exist. When I run it all that returns is a blank alert box (meaning that the PHP script did not print out success). Any idea why it is not sending the mail?
You didn't exit after echoing out the 'success' - PHP hasn't stopped processing yet, so it just continues to the next line, and renders out echo($message.' '.$email.' '.$name); as well.
This means your JS test is comparing success with success$message $email $name, which is always false.
If you want to stop processing, you have two choices: either exit or die (don't do this), or wrap the rest of the code in an else tag, like this:
if ($message && $email && $name){
$body = "From: $name.\n \n $message";
mail(/*some email*/, 'Website Contact Form Submission', $body, "From: $email");
echo ('success');
} else {
echo($message.' '.$email.' '.$name);
}
Also, make sure you don't end your PHP scripts with ?> ! This almost always leads to problems later where the PHP script renders out some unwanted white space at the end, which would also fail.
Don't use array_map('trim', $_POST) http://www.php.net/manual/en/function.trim.php#96246
check ajax response first to see if there is any error occurs.

Categories