POST contact form missing data when special character is used - php

I am using a simple contact form: http://luiszuno.com/previews/formy/
and the issue is that whenever the character "&" is typed on the form the rest of the message after "&" is not received on the email. Edit: Added the code, form works correctly other than the missing data issue. What could be causing this issue?
jQuery(document).ready(function($) {
$("#formy").on( "submit", function( event ) {
$(this).serialize();
});
// Hide messages
$("#formy-success").hide();
$("#formy-error").hide();
$("input,textarea").blur(function(){
$(this).css("border-color","#596a87");
});
// on submit...
$("#formy #submit").click(function() {
$(this).serialize();
// Required fields:
//name
var name = $("#name").val();
if(name == "" || name == "Name *"){
$("#name").focus();
$("#formy-error").fadeIn().text("Name required");
$("#name").css("border-color","#a22528");
return false;
}
else {$("#name").css("border-color","#596a87");}
// email
var email = $("#email").val();
if(email == "" || email == "Email *"){
$("#email").focus();
$("#formy-error").fadeIn().text("Email required");
$("#email").css("border-color","#a22528");
return false;
}
else {$("#email").css("border-color","#596a87");}
// email validation
function validateEmail(email) {
var filter = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return filter.test(email);
}
if (!validateEmail(email)) {
$("#formy-error").fadeIn().text("Invalid email address");
$("#email").css("border-color","#a22528");
return false;
}
//budget
var budget = $("#budget").val();
if(budget == "" || budget == "Budget"){
return false;
}
// comments
var comments = $("#comments").val();
if(comments == "" || comments == "Message *"){
$("#comments").focus();
$("#formy-error").fadeIn().text("Message required");
$("#comments").css("border-color","#a22528");
return false;
}
else {$("#comments").css("border-color","#596a87");}
// send mail php
var sendMailUrl = $("#sendMailUrl").val();
// Retrieve values for to, from & subject at the form
var to = $("#to").val();
var from = $("#from").val();
var subject = $("#subject").val();
// Create the data string
var dataString = 'name=' + name
+ '&email=' + email
+ '&comments=' + comments
+ '&to=' + to
+ '&from=' + from
+ '&budget=' + budget
+ '&subject=' + subject;
// ajax
$.ajax({
type:"POST",
url: sendMailUrl,
data: dataString,
success: success()
});
});
// On success...
function success(){
$("#formy-success").fadeIn(250).text("Thanks, I will contact you soon!");
$("#formy-error").hide();
$("#formy fieldset").slideUp(250);
}
return false;
});
send-mail.php
<?php header("Content-Type: text/html; charset=utf-8");
//vars
$subject = $_POST['subject'];
$to = explode(',', $_POST['to'] );
$from = $_POST['email'];
//data
$msg = "NAME: " .$_POST['name'] ."<br>\n";
$msg .= "EMAIL: " .$_POST['email'] ."<br>\n";
$msg .= "BUDGET: " .$_POST['budget'] ."<br>\n";
$msg .= "COMMENTS: " .$_POST['comments'] ."<br>\n";
//Headers
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: <".$from. ">" ;
//send for each mail
foreach($to as $mail){
mail($mail, $subject, $msg, $headers);
}
?>

Your problem is that you are building your data string manually and not URI-encoding the data values you insert into the string. Therefore any raw & character in your text will be assumed to be part of the URI and not the data, meaning that it will be interpreted as indicating the start of the next parameter, rather than just a character in the text. URI-encoding this data will convert this and other special characters into their encoded equivalents, so they will not be mis-interpreted.
Now, you can certainly fix this by wrapping every field variable with encodeURIComponent(), but this is verbose and tedious:
var dataString = 'name=' + encodeURIComponent(name)
+ '&email=' + encodeURIComponent(email)
+ '&comments=' + encodeURIComponent(comments)
+ '&to=' + encodeURIComponent(to)
+ '&from=' + encodeURIComponent(from)
+ '&budget=' + encodeURIComponent(budget)
+ '&subject=' + encodeURIComponent(subject);
There are better ways:
Currently, your $(this).serialize(); will not work because this represents the clicked button, not the form. However if you point it at the form, you can use it to easily serialise the fields within it automatically, and jQuery will handle any encoding issues on your behalf. This saves on manual encoding, and on code to fetch each field value individually (although I note you currently need this for your validation, although there are other ways to implement validation which would remove that need, but that's another topic entirely).
$.ajax({
type:"POST",
url: sendMailUrl,
data: $("#formy").serialize(),
success: success //Unrelated: I also removed the brackets here, so it becomes a _reference_ to the "success" function - writing success() as you did means the function is immediately executed, and what gets passed to jQuery is the _result_ of the function, which isn't what you want in this case
});
As you can see this is much less hassle. And if you ever add more fields to your form in future, you won't have to change this bit of code at all.
Another side point - you're going to a lot of trouble to validate the form input using JavaScript. This is nice and user-friendly, but it provides no security whatsoever. On the server side you appear to be happily inserting whatever values the browser sends directly into your email. Any user with a small amount of knowledge can either modify your JavaScript with their developer tools, or turn off JS, or just use another tool entirely (e.g. PostMan, or a custom application) to fire HTTP requests at your server without ever touching your form. They could potentially send problematic values which might screw up your email - e.g. a different "from" value, or some nasty HTML, or if you're interacting with a database anywhere in your application, carry out SQL Injection attacks to mess that up. You should always validate all incoming data in your PHP code for security issues, and to ensure it meets your business rules, before using it for anything else.

Using the encodeURIComponent() as #ADyson recommended fixed the missing data/urls from received email when using the contact form.
var comments = $("#comments").val();
var e_comments = encodeURIComponent(comments);

Related

How would I strip any harmful characters from this form?

I have tried both real escape string and other php methods but I am not sure I am using them correctly. This code shows my input and then the ajax post, where and how would I preform the sanitation?
Please note there is no data base connection so all the character stripping would have to be done in jQuery somehow.
Would this be more of the correct direction to go in?
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$message = $_POST["message"];
$msg = "
Name:$name
Email:$email
Phone:$phone
Comment:
$message";
function checkInput($msg) {
$msg = #strip_tags($msg);
$msg = #stripslashes($msg);
$invalid_characters = array("$", "%", "#", "<", ">", "|");
$msg = str_replace($invalid_characters, "", $msg);
return $msg;
}
$to = "email address";
$subject = "name";
$message = $msg;
$headers = "Contact form enquiry";
mail($to,$subject,$message,$headers);
?>
You perform sanitation immediately before you put the text into some code or specific data format.
So in the code you have here:
var dataString = 'name=' + name + '&email=' + email + '&phone=' + phone + '&message=' + message;
You would escape each variable before you put it into the URL. You can do that with encodeURIComponent. However, you are using jQuery ajax so you shouldn't be doing that by hand in the first place.
data: { 'name': name, 'email': email, 'phone': phone, 'message': message},
And in the HTML you are generating:
.append("<h2 class='text-center form_submit_text'>Hi " + name + ", we will contact you soon </p>")
should be:
var heading = jQuery("<h2>").addClass('text-center').addClass('form_submit_text').text("Hi " + name + ", we will contact you soon);
$('#thanks').empty().append(heading);
You might also need to do some escaping in your PHP, such as before putting data into SQL.
You validate and sanitize in bin/mail.php. See filter_var for the built in ways to validate and sanitize incoming data. For example, for email you can do
if (filter_var($_POST['email']), FILTER_VALIDATE_EMAIL)) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL));
}
Phone numbers would required a regular expression to validate and sanitize (so it only contains numbers and/or re-formats to your preferred format). Free text like $message should use FILTER_SANITIZE_STRING.

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

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!

PHP variable from external file?

*EDIT / FINISHED SOLUTION / WORKING CODE
So, this is what a friend of mine helped me come up with.
Here is the part I use in my K2 "items.php" file:
<div class="fb-comments" data-href="<?php echo JURI::current(); ?>" data-num-posts="8" notify="true" data-width="580"></div>
<input id="authname" style="display: none;" type="text" value="<?php echo $this->item->author->name; ?>" />
<input id="authmail" style="display: none;" type="text" value="<?php echo $this->item->author->email; ?>" />
<input id="link" style="display: none;" type="text" value="<?php echo JURI::current(); ?>" />
<script>
window.fbAsyncInit = function() {
FB.Event.subscribe('comment.create', function (response) {
var commentQuery = FB.Data.query("SELECT text, fromid FROM comment WHERE post_fbid='" + response.commentID +
"' AND object_id IN (SELECT comments_fbid FROM link_stat WHERE url='" + response.href + "')");
var userQuery = FB.Data.query("SELECT name FROM user WHERE uid in (select fromid from {0})", commentQuery);
FB.Data.waitOn([commentQuery, userQuery], function () {
var commentRow = commentQuery.value[0];
var userRow = userQuery.value[0];
console.log(userRow.name + " (id: " + commentRow.fromid + ") posted the comment: " + commentRow.text);
trackcomments(response['commentID'], response['href'], 'create', commentRow.text, userRow.name, commentRow.fromid);
});
});
};
function trackcomments(_commentid, _address, _action, _commentMessage, _userName, _userId) {
var authname = document.getElementById('authname').value;
var authmail = document.getElementById('authmail').value;
var link = document.getElementById('link').value;
$.ajax({
type: 'POST',
url: 'http://mydomain.com/dostuff.php',
data: {'commentMessage': _commentMessage, 'userName': _userName, 'authname': authname, 'authmail': authmail, 'link': link},
cache: false
});
};
</script>
And this is the do_stuff.php:
<?php
//Handle some weird letters and stuff
setlocale(LC_TIME, 'swedish');
//creating an $author variable and populating it from $_POST
$author = $_POST['authname'];
$authoremail = $_POST['authmail'];
$link = $_POST['link'];
$commentMessage = $_POST['commentMessage'];
$userName = $_POST['userName'];
$date = strftime('%A %e %b %Y %H.%M', time());
//getting author email
$to = $authoremail;
//subject of email
$subject = "New comment posted on mydmomain.com";
//email content
$message = "On $date $userName wrote\n\n$commentMessage\n\non your entry $link#comments\n\nUse the above link to answer on the comment.";
//who the mail is from
$from = "admin#mydomain.com";
//header
$headers = "From:" . $from;
//send the email
mail($to,$subject,$message,$headers);
?>
Turns out, there was a simple reason it wasn't working... JavaScript doesn't seem to handle PHP!
So the "do_stuff.php" (earlier named sendmail.php) was never executed with the echo JURI::base();.
Even then though. The var = $this->item... was also trying to get data from PHP variables which wasn't working. So, to combat that the values of those variables where put in hidden input forms to retrieve them thru getObjectById.
Like my friend stated, don't know if this is the most elegant or sophisticated solution... but it does the trick and fills it's purpose.
However, if someone has a better more "correct" way of achieving this, I'm all ears :)
Thank you #jack for your help! And anyone else contributing to this subject in the future.
- ORIGINAL POST -
Still learning about PHP and Joomla and K2. Been sitting upp for days now trying to figure out how I can have specific authors receive emails when comments are made using fb:comments.
So far so good...
FB.event.subscribe comment.create acting without action from user
Now, the only thing missing is the referens to the variable "$item->author->name". Since this is usable in the original file (item.php) where I'm calling for the sendmail.php
<script>
window.fbAsyncInit = function() {
/* All the events registered */
FB.Event.subscribe('comment.create', function (response) {
$.get('<?php echo JURI::base(); ?>sendmail.php');
});
};
</script>
and this is the "sendmail.php" file
<?php
if ($item->author->name == "Firstname1 Lastname1"){
$to = "author1#mydomain.com";
}else if ($item->author->name == "Firstname2 Lastname2"){
$to = "author2#mydomain.com";
};
$subject = "New comment";
$message = "A new comments has been made.";
$from = "admin#mydomain.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
?>
I don't know how I can get the $item->author->name to work. Since I need to make sure that it somehow checks to see what the name is (since it's showing on the generated page I have to be able to use it somehow) to specify which email to send TO.
I have no idea if this has already been asked, but I don't even know what to search for to get me started here. I can't imagine that this would be to difficult to solve (if you only know what you need to change). :)
You can try passing the author name as a parameter in your ajax call. Something along these lines:
FB.Event.subscribe('comment.create', function (response) {
var name = $item->author->name;
$.get('<?php echo JURI::base(); ?>sendmail.php'), new {'authorName': name};
});
Then in your sendmail script you should be able to access the passed authorName parameter...
if (authorName == "Firstname1 Lastname1"){...
You could also use $.post to send the parameter to the sendmail script.
Note: This is untested and from memory, but hopefully it will point you in the right direction. It's also been a while since I last worked with Joomla, and there is likely a better Joomla-specific way to accomplish this.
EDIT: here's an example of using POST to pass the variable to the sendmail script:
FB.Event.subscribe('comment.create', function (response) {
var name = $item->author->name;
$.ajax({
type: "POST",
url:'<?php echo JURI::base(); ?>sendmail.php'),
data: authorName,
cache: false,
});
});
...and in your sendmail.php file:
<?php
//creating an $author variable and populating it from $_POST
$author = $_POST['authorName'];
if ($author == "Firstname1 Lastname1"){
$to = "author1#mydomain.com";
}else if ($author == "Firstname2 Lastname2"){
$to = "author2#mydomain.com";
};
$subject = "New comment";
$message = "A new comments has been made.";
$from = "admin#mydomain.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
?>
Again this is untested, but should give you an idea. Since you're using Joomla you should also look into Joomla's com_mailto component, it may or may not be easier. You can search for further info with "pass parameter to external PHP script via ajax" or something along those lines.
Also, here's a reference for jQuery ajax

E-mail form won't send when using certain characters

I have been on this for days and days, and am at the point that I have pulled out so many hairs that I now have just one hair left on my head. That hair is my last bit of pride. But seriously though, I have found dozens of answers but none seem to apply to my problem!
I have an e-mail form for a website I made. The site and form are made in Flash (AS3), the script for processing the e-mail is an external php file. The e-mail form works just fine, except for when I use certain characters:
% is not shown in the e-mail, including any text directly behind it
when a &, < or > is present, the form will say 'sending..' but not go beyond that point; I don't receive any e-mail.
All (or most at least) other characters like !##$^*_+-=~` are no problem.
I have already made sure both AS3 and php codes have
"MIME-Version: 1.0; Content-Type: text/html; charset=utf-8" is included in my sending if check in the php file;
the textfields in AS3 are set to htmlText instead of just text.
My scripts:
mail.php
if( $yourName == true ) {
$sender = $fromEmail;
$yourEmail = "myemail#example.com"; // Here i of course use my own email address
$ipAddress = $_SERVER['REMOTE_ADDR']; // This gets the user's ip Address
$emailMsg = "Van: $sender\r\n" .
"Name: $yourName\r" .
"Subject: $yourSubject\n\n" .
"$yourMsg\n\n\n\n" .
"------------------------------\r" .
"Sent from IP-address $ipAddress\r" .
"X-Mailer: PHP/" . phpversion();
# these are three (out of many) things I tried to work around the problem #
//$emailMsg = str_replace( '&', "&", $emailMsg );
//$emailMsg = htmlspecialchars($emailMsg, ENT_QUOTES);
//$emailMsg = mysql_real_escape_string($emailMsg);
$return = "From: $sender\r\n";
if( mail($yourEmail, "$yourSubject", $emailMsg, $return, "MIME-Version: 1.0; Content-Type: text/html; charset=utf-8")) {
echo "sentStatus=yes";
}
else {
echo "sentStatus=no";
}
}
?>
FormScript.as
package {
/*required imports*/
public class FormScript extends Sprite {
/*here are the variable declarations*/
public function FormScript() {
sendbtn.buttonMode = true;
sendbtn.addEventListener(MouseEvent.CLICK, submit);
resetbtn.buttonMode = true;
resetbtn.addEventListener(MouseEvent.CLICK, reset);
urlRequest.method = URLRequestMethod.POST;
/*here are are some positionings and addchilds*/
function init():void {
//Set all fields to empty
yourName.htmlText = "";
fromEmail.htmlText = "";
yourSubject.htmlText = "";
yourMsg.htmlText = "";
valid.text = "";
}
function submit(e:MouseEvent):void {
//Check to see if any of the fields are empty
if(yourName.htmlText == "" || fromEmail.htmlText == "" ||
yourSubject.htmlText == "" ||yourMsg.htmlText == "" ) {
valid.text = "All fields must be filled in";
}//Check if you're using a valid email address
else if(!checkEmail(fromEmail.htmlText)) {
valid.text = "Please enter a valid e-mail address";
}
else {
valid.text = "Sending..";
var emailData:String =
"name=" + yourName.htmlText +
"&from=" + fromEmail.htmlText +
"&subject=" + yourSubject.htmlText +
"&msg=" + yourMsg.htmlText;
var urlVars:URLVariables = new URLVariables(emailData);
urlVars.dataFormat = URLLoaderDataFormat.TEXT;
urlRequest.data = urlVars; varLoad.load( urlRequest );
varLoad.addEventListener(Event.COMPLETE, thankYou );
}
}
function reset(e:MouseEvent):void {
init(); //call the initial clear function
}
function checkEmail(s:String):Boolean {
//yourMsg.text = escape("&");
//This tests for correct email address
var p:RegExp = /(\w|[_.\-])+#((\w|-)+\.)+\w{2,4}+/;
var r:Object = p.exec(s);
if( r == null ) {
return false;
}
return true;
}
function thankYou(e:Event):void {
var loader:URLLoader = URLLoader(e.target);
var sent = new URLVariables(loader.data).sentStatus;
//valid.text = sent;
if( sent == "yes" ) {
valid.text = "Thank you for your e-mail!"; timer = new Timer(500);
timer.addEventListener(TimerEvent.TIMER, msgSent);
timer.start();
}
else {
valid.text = "Something went wrong, please try again";
}
}
function msgSent(te:TimerEvent):void {
if(timer.currentCount >= 10) {
init();
timer.removeEventListener(TimerEvent.TIMER, msgSent);
}
}
}
}
}
Keywords:ampersand special characters symbols less-than less than greater-than greater than please don't edit this, it's for others to find this question because you can't search for an '&' and such.
The most obvious culprit here is messy way you're creating the emailData string. As a first step I'd recommend reformatting it to the following:
var urlVars:URLVariables = new URLVariables();
urlVars.name = yourName.htmlText;
urlVars.from = fromEmail.htmlText;
urlVars.subject = yourSubject.htmlText;
urlVars.msg = yourMsg.htmlText;
I think this will automatically URI encode the values, but if not, use encodeURI() as suggested by Mark Knol.
Within Flash, the values need to be encoded, otherwise the querystring could be corrupted.
var emailData:String =
"name=" + encodeURI(yourName.htmlText) +
"&from=" + encodeURI(fromEmail.htmlText) +
"&subject=" + encodeURI(yourSubject.htmlText) +
"&msg=" + encodeURI(yourMsg.htmlText);
Try to use
$emailMsg = utf8_decode($emailMsg);
I decode all my strings I get from Flash.
If this doesn't help, use
$emailMsg = urldecode($emailMsg);
Or both :D

Categories