So I have a form that is submitted through jQuery AJAX and around 18 arguments are passed to a php file. Now whenever I try to submit the form, stack limit is reached with that many arguments. But the moment I cut off like half the arguments, the forms works fine and email is received. But the email I receive does not have any body.
AJAX:
$.ajax({
url: "sendemail.php",
method: "post",
data: {
name: name,
email: email,
number: number,
username: username,
country: country,
cname: cname,
ctype: ctype,
ctheme: ctheme,
domainname: domainname,
webhosting: webhosting,
seo: seo,
gadvertising: gadvertising,
cmarketing: cmarketing,
ptech: ptech,
details: details,
description: description
},
success: function () {
alert("Hey brotha");
}
}).fail(function () {
$("#confdiv").html("<p class='alert alert-danger'>There was an error submitting your form. Please try again later or contact us at <a href='mailto:sobanr4#gmail.com'>EMAIL</a></p>");
window.scrollTo(0, 100);
});
the php script is:
<?php
if (isset($_POST['name']) && $_POST['name'] != "") {
$to = "sobanr4#gmail.com";
$subject = "Website Order Request";
$headers = "From: <".$_POST['email'].">\r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$body = "<html>
<head>
<title>Order Request - ".$_POST['name']."</title>
</head>
<body>
<p>NAME: ".$_POST['name']."</p>
<p>EMAIL: ".$_POST['email']."</p>
<p>NUMBER: ".$_POST['number']."</p>
<p>USERNAME: ".$_POST['username']."</p>
<p>COUNTRY: ".$_POST['country']."</p>
<p>COMPANY NAME: ".$_POST['cname']."</p>
<p>TYPE: ".$_POST['ctype']."</p>
<p>THEME: ".$_POST['ctheme']."</p>
<p>DOMAIN NAME: ".$_POST['domainname']."</p>
<p>WEB HOSTING: ".$_POST['webhosting']."</p>
<p>SEO: ".$_POST['seo']."</p>
<p>GOOGLE ADVERTISING: ".$_POST['gadvertising']."</p>
<p>CONTENT MARKETING: ".$_POST['cmarketing']."</p>
<p>PERMANENT TECHNICIAN: ".$_POST['ptech']."</p>
<br><br><br>
<p>DETAILS: ".$_POST['details']."</p>
<br><br><br>
<p>DESCRIPTION: ".$_POST['description']."</p>
</body>
</html>";
if (mail($to,$subject,$$body,$headers)) {
echo 1;
} else {
echo 0;
};
}
?>
The form can be found here: http://www.henryspike.tk/testform
Ok, I think it must be the radio buttons.
You get their value like this:
var seo = $("#seo").val();
var gadvertising = $("#gadvertising").val();
var cmarketing = $("#cmarketing").val();
var ptech = $("#ptech").val();
But it should be like this:
var seo = $("#seo:checked").val();
var gadvertising = $("#gadvertising:checked").val();
var cmarketing = $("#cmarketing:checked").val();
var ptech = $("#ptech:checked").val();
I have not tested this... but it is easy for you to try.
SOLUTION:
All this mess and in the end the problem was that one of the variables in my javascript were misspelled as 'ctheme' instead of 'theme'.
And the blank email issue was resolved because I typed '$$body' instead of '$body'.
Anyways, thanks every one for help, especially #KIKOSoftware
P.S: I guess its a welcome to the world of programming.
Related
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!
I am using a jQuery Mobile Form script I found online. Everything is working fine, except the input="radio" buttons. I am not a jQuery expert by any means, so I am hoping someone here can help me.
THE SETUP
The form script contains 3 files: send.php, contact.js, and the mobile markup. Examples of the problematic pieces of code are below:
Mobile Markup:
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Doctor Type:</legend>
<input type="radio" name="doctortype" id="dmd" value="dmd"/>
<label for="dd">D.D.</label>
<input type="radio" name="doctortype" id="dds" value="dds" />
<label for="do">D.O.</label>
</fieldset>
</div>
Contact.js
$('#send-feedback').live("click", function() {
var url = 'api/send.php';
var error = 0;
var $contactpage = $(this).closest('.ui-page');
var $contactform = $(this).closest('.contact-form');
$('.required', $contactform).each(function (i) {
if ($(this).val() === '') {
error++;
}
}); // each
if (error > 0) {
alert('Please fill in all the mandatory fields. Mandatory fields are marked with an asterisk *.');
} else {
var doctortype = $contactform.find('input[name="doctortype"]').val();
var firstname = $contactform.find('input[name="firstname"]').val();
var surname = $contactform.find('input[name="surname"]').val();
var dob = $contactform.find('input[name="dob"]').val();
var zip = $contactform.find('input[name="zip"]').val();
var how = $contactform.find('select[name="how"]').val();
var email = $contactform.find('input[name="email"]').val();
var message = $contactform.find('textarea[name="message"]').val();
//submit the form
$.ajax({
type: "GET",
url: url,
data: {doctortype:doctortype, firstname:firstname, surname:surname, dob:dob, zip:zip, how:how, email:email, message:message},
success: function (data) {
if (data == 'success') {
// show thank you
$contactpage.find('.contact-thankyou').show();
$contactpage.find('.contact-form').hide();
} else {
alert('Unable to send your message. Please try again.');
}
}
}); //$.ajax
}
return false;
});
Send.php
<?php
header('content-type: application/json; charset=utf-8');
if (isset($_GET["firstname"])) {
$doctortype = strip_tags($_GET['doctortype']);
$firstname = strip_tags($_GET['firstname']);
$surname = strip_tags($_GET['surname']);
$dob = strip_tags($_GET['dob']);
$zip = strip_tags($_GET['zip']);
$how = strip_tags($_GET['how']);
$email = strip_tags($_GET['email']);
$message = strip_tags($_GET['message']);
$header = "From: ". $firstname . " <" . $email . ">";
$ip = $_SERVER['REMOTE_ADDR'];
$httpref = $_SERVER['HTTP_REFERER'];
$httpagent = $_SERVER['HTTP_USER_AGENT'];
$today = date("F j, Y, g:i a");
$recipient = 'MYEMAIL#gmail.com';
$subject = 'Contact Form';
$mailbody = "
Doctor Type: $doctortype
First Name: $firstname
Last Name: $surname
Date of Birth: $dob
Zip Code: $zip
How Did You Learn About Us: $how
Message: $message
IP: $ip
Browser info: $httpagent
Referral: $httpref
Sent: $today
";
$result = 'success';
if (mail($recipient, $subject, $mailbody, $header)) {
echo json_encode($result);
}
}
?>
THE RUB
The form works fine by itself. User fills out info, clicks "Send", and I receive an email with the information. However, I am not able to get the value of the checked radio to parse and send.
I've spent numerous hours trying to get the checked radio value to pass through the necessary steps.
And therein lies the problem. I've looked at countless similar posts on SO and other various places online, including the jQuery Mobile documentation. To no avail.
Any help is much appreciated!
What is your jQuery doing? It seems unnecessary to do any jQuery/JavaScript. The form should send the value of your radio button to $_GET['doctortype'] without it (assuming your form method is get).
I'm working with the tutorial here: http://designwoop.com/2012/07/tutorial-coding-a-jquery-popup-modal-contact-form/ and the form sending the data correctly. However, after clicking submit, the form just shows the "sending" message rather than showing the confirmation message. This happens when I test locally and on my development environment. I don't see any error messages in my console.
This is my first time working with ajax and I am a newbie with jQuery/JavaScript. Not sure what the problem is here. It seems that it is not reading the data as true. I changed True to False to see what would happen and it still doesn't work. Can anyone help, please?
FYI I am implementing this on a site that already calls the 1.3.2 jQuery library and can not remove the reference, so I have to use noConflict. This doesn't work when I reference only the older library.
My goal is to create a modal that pops up when a user enters the website, but not if a cookie is set or if there is already a specific div on the page they enter through.
Here are the scripts:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="/wcsstore/CVWEB/images/home/js/jquery.fancybox.js?v=2.0.6"></script>
<script type="text/javascript">
var jQuery_1_7_2 = jQuery.noConflict(true);
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
jQuery_1_7_2(document).ready(function(){
var emailFormExists = jQuery_1_7_2('#e2ma_signup_form');
if (document.cookie.indexOf('visited=true') == -1 && !(emailFormExists.length)){
var fifteenDays = 1000*60*60*24*15;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
jQuery_1_7_2.fancybox({width:"100%", inline:true, href:"#inline"});
}
else
{
jQuery_1_7_2('#e2ma_signup_form').length
var fifteenDays = 1000*60*60*24*15;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
}
jQuery_1_7_2("#contact").submit(function() { return false; });
jQuery_1_7_2("#send").on("click", function(){
var emailval = jQuery_1_7_2("#email").val();
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
jQuery_1_7_2("#email").addClass("error");
}
else if(mailvalid == true){
jQuery_1_7_2("#email").removeClass("error");
}
if(mailvalid == true) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
jQuery_1_7_2("#send").replaceWith("<em>sending...</em>");
jQuery_1_7_2.ajax({
type: 'POST',
url: 'http://lcoawebservices.com/scripts/email-opt-in.php',
data: jQuery_1_7_2("#contact").serialize(),
success: function(data) {
if(data == "true") {
jQuery_1_7_2("#contact").fadeOut("fast", function(){
jQuery_1_7_2(this).before("<p><strong>Thanks for opting in!</strong></p>");
setTimeout("jQuery_1_7_2.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
and here is the HTML:
<div id="inline">
<h2>Join the our mailing list!</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<button id="send">Send E-mail</button>
</form>
</div>
here is the php (which i am also new to)
<?php
$sendto = "llantz#lecreuset.com";
$usermail = $_POST['email'];
$content = nl2br($_POST['msg']);
$subject = "New Feedback Message";
$headers = "From: " . strip_tags($usermail) . "\r\n";
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>New User Feedback</h2>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$usermail."</p>\r\n";
$msg .= "<p><strong>Message:</strong> ".$content."</p>\r\n";
$msg .= "</body></html>";
if(#mail($sendto, $subject, $msg, $headers)) {
echo "true";
} else {
echo "false";
}
?>
I figured it out - this is due to a cross-domain access problem. I do not have the answer on how to solve it yet but wanted to post this so no one else spends time looking at my code, trying to fix it.
*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
I'm having a difficult time implementing this AJAX code into my form so that the page doesn't need to reload but will still perform server-side validation. I'm new to AJAX and PHP, so I'm working off a couple form templates, but I have been working on this for hours and I can't figure out why it's not working. Any help would be appreciated.
Here's a portion of the HTML code:
<div id="popupContact">
<form id="formElem" name="formElem" action="" method="post">
<fieldset class="step">
<legend>Personal Details</legend>
<p>
<label for="firstname">First Name</label><em>*</em>
<input id="firstname" name="firstname" />
</p>
<p>
<label for="lastname">Last Name</label><em>*</em>
<input id="lastname" name="lastname" />
</p>
<p>* fields are required</p>
</fieldset>
<fieldset class="step">
<legend>Confirm</legend>
<p>Before you submit your information, please ensure that each step
below has this <img src="../img/global/checked.png" alt="Complete" >
above them. If there is a step that has this
<img src="../img/global/error.png" alt="Error" >, please click on that tab
and review the information to ensure it is correct and complete. Thank you.</p>
<p>
<label for="human">Please Type: "Something"</label><em>*</em>
<input id="human" name="human" />
</p>
<p class="submit">
<button id="registerButton" type="submit">Submit</button>
</p>
</fieldset>
</form>
</div>
Here's the JAVAScript code:
$(function() {
var form = $("#formElem");
var fname = $("#firstname");
var lname = $("#lastname");
var address = $("#streetaddress");
var city = $("#city");
var state = $("#state");
var phone = $('#phone');
var email = $('#email');
var insurance = $('#insurance');
var license = $('#license');
var human = $('#human');
$('#registerButton').bind('click',function(){
if($('#formElem').data('errors')){
alert('Please correct the errors in the Form');
return false;
}
else {
var dataString = 'fname='+$('#firstname').val()+'&lname='+$('#lastname').val()+'&address='+$('#streetaddress'.val())+'&city='+$('#city')+'&state='+$('#state').val()+'&phone='+$('#phone').val()+'&email='+$('#email').val()+'&insurance='+$('#insurance').val()+'&license='+$('#license').val()+'&human='+$('#human').val();
$.ajax({
type: "POST",
url: "js/validation.php",
data: dataString,
async: false,
success: function() {
$('#popupContact').html("<div id='message'></div>");
$('#message').html("<h2>Inquiry Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='..img/global/check.png' />");
});
}
});
return false;
}
});
And here's the PHP code:
<?php
if(isset($_POST['email'])) {
$email_to = "somebody#somewhere.com";
$email_subject = "Inquiry";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['firstname']) ||
!isset($_POST['lastname']) ||
!isset($_POST['email']) ||
!isset($_POST['phone']) ||
!isset($_POST['streetaddress']) ||
!isset($_POST['city']) ||
!isset($_POST['state']) ||
!isset($_POST['insurance']) ||
!isset($_POST['license']) ||
!isset($_POST['human'])){
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$firstname = $_POST['firstname']; // required
$lastname = $_POST['lastname']; // required
$emailfrom = $_POST['email']; // required
$phone = $_POST['phone']; // required
$address = $_POST['streetaddress']; //required
$city = $_POST['city']; //required
$state = $_POST['state']; //required
$insurance = $_POST['insurance']; //required
$license = $_POST['license']; //required
$human = $_POST['human']; //required
$error_message = "";
$email_exp = '/^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/';
if(!preg_match($email_exp,$emailfrom)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($firstname)."\n";
$email_message .= "Last Name: ".clean_string($lastname)."\n";
$email_message .= "Email: ".clean_string($emailfrom)."\n";
$email_message .= "Telephone: ".clean_string($phone)."\n";
$email_message .= "Address: \n".clean_string($address)."\n";
$email_message .= "".clean_string($city).", ";
$email_message .= "".clean_string($state)."\n";
$email_message .= "Have Insurance: ".clean_string($insurance)."\n";
$email_message .= "Have License: ".clean_string($license)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
Thank you for contacting us. We will be in touch with you very soon.
<?php
}
?>
I left out most of the actual validation code part of it, so I know that what you see isn't complete. What I don't understand is that without the AJAX part of this, the form validation works just fine-client and server-side, but when I add the AJAX, something's not connecting. Thanks for your help in advance.
EDIT
Does anyone have a suggestion as to where my code is going wrong?
EDIT
Okay, so if I put js/validation.php in the action="" tag for the form and disable the AJAX part of the code, then validation works just fine, but I'm forwarded to a page that is just blank with the confirmation code. Does this shed any light on the issue? Really, any help is appreciated. I've tried using the tips given in the comments, but for some reason nothing happens. It looks like my page is refreshed, but no confirmation message, or anything. I am totally and completely lost.
You're not far off, but I think I'd attack this in a slightly less aggressive manner.
Starting with the form, I'd just make it a form with an id, and park the submit button outside the form tags. Why? Because a button inside a form can have some undesirable effects (like submitting to a magical black hole) Less code = happy developer.
I'd catch the click on the button with a click handler. So:
$('#registerButton').click(function(){
Do your ajax here
});
I'd catch errors initially with front-end validation, because it saves server hits and is more pleasant from a UI standpoint. It's also faster....and no, it can't be entirely relied on because any competent person can override it, but it's a good first step. My personal favorite is here
In the click action, I'd use the ajax (like you have in your
example) to submit the form to your script for validation.
Serialize your form to send it in:
$.ajax({
type: "POST",
url: "js/validation.php",
data: $('#formElem').serialize(),
...
I'd have the script return a json string with a result case
(true/false) and data to support that case (such as an id for
success, and an array of the error cases for false) So, you're
doing exactly right with your ajax call above, but return the
data
type for my example as json (not dataString) and add a var in
the
parens after success (let's use returndata as an example) Then, within your
success callback, the returned data would be available as
returndata.field (change field to equal the variable name in the
json string) If it doesn't work, check the output on
jsonlint.com
In the success of the ajax call from step 4, setup two cases (if/else). If your result case is true, let them proceed and indicate success as your UI dictates. If the result case is false, then iterate through the array of error cases to notify the user on each respective question.
You're almost there. If this is your first experience with jQuery AJAX, I'm really impressed!
I know you already accepted an answer, but I also wanted to suggest checking out the jQuery Validate plugin - http://bassistance.de/jquery-plugins/jquery-plugin-validation/ - no need to rewrite the wheel really. I personally use this plugin anytime I'm doing any type of client-side validation with jQuery. I mention this too because the plugin comes with a native "remote" validation type that you can use for any type of remote validation with a few simple lines of code. I've also read in some places that jQuery may start "officially" supporting the validation plugin at some point, so it can never hurt to start using it sooner than later. Just some food for thought!