There are 3 elements to this.
An HTML form
The AJAX connection which sends the form values and receives and parses response from the PHP script
The PHP script which decides whether the values are good/bad or not and sends back an appropriate response (probably in XML format for easy parsing by the javascript function?)
When the PHP looks at and handles the sent data, inserting it into a database or doing whatever with it, it needs to send back a response or maybe a collection of responses so that javascript can display a proper error message(s) to the user. Maybe also putting a red border or something around the elements that have the bad input.
How is this usually done, on both ends? I'm thinking that PHP should just send back simple numeric error codes and javascript will set the proper text error messages in different divs. But I'm not really sure, and I'm not really sure what I should be googling to find an answer.
(BTW I'm not talking about HTTP error codes)
Use this jquery ajax function to post data to php file Then do whatever with data (send in data base or make some collections ) then echo result that you will catch within success section. Then put your result in a div or where you want.
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"dummyData="+dummyData,
beforeSend: function()
{
},
success: function(resp)
{
$("#resultDiv").html(resp);
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
What you are asking is called validation.
There is server side validation, and client side validation.
The first is the most important one, as you don't want users to corrupt your database.
The second is important for your customer. As it gives him prompt response about anything that's invalid with the form (red border).
If you want to validate the form client side, it is usually done with Javascript.
For server side validation, I would use JSON, as the communication between server and client, as both php and javascript know how to handle it well.
For php:
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.json-decode.php
for JS.
just access the result parameter:
success: function(response){
var json = $.parseJSON(response.responseText);
}
Example for Ajax contact form: (Was originally in dutch and it's kinda old and badly coded)
Keep in mind you need jquery for this example. Just download the jquery.js from their website and add it to your scripts in the of your HTML
form.html
<form id="frm_contact" name="contactformulier">
<label>Naam<span style="color:red">*</span></label><br/>
<input type="text" size="15" maxlength="50" name="naam" />
<br/><br/>
<label>Bedrijf</label><br/>
<input type="text" size="15" maxlength="50" name="bedrijf" />
<br/><br/>
<label>Email<span style="color:red">*</span></label><br/>
<input type="text" size="15" maxlength="50" name="tmail" />
<br/><br/>
<label>Bericht<span style="color:red">*</span></label><br/>
<textarea name="tekst">
</textarea>
<br/><br/>
(<span style="color:red">*</span>) Required fields!
<br/><br/>
<div id="subbutton">Send</div>
</form>
<div id="error-msg"></div>
form.html (javascript code)
<script>
$(document).ready(function(){
var err="";
$("#subbut").click(function(){
$.post("PHP/ajax_contact.php", $("#frm_contact").serialize(),
function(data){
switch(data){
case '0':
err="<span><center>Thanks for contacting us!</center></span>";
$("#frm_contact").hide();
break;
case '1':
err="Invalid email!";
break;
case '2':
err="Fill in all fields please!";
break;
case '3':
err="Error sending this mail.";
break;
default:
err="<center>Mail server is offline.</center>"; //Or whatever error
$("#frm_contact").hide();
}
$("#error-msg").html("<br/>"+err+"<br/>");
});
});
});
</script>
PHP/ajax_contact.php
<?php
function check_email_address($email) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
return true;
}
return false;
}
$naam = trim($_POST['naam']);
$bedrijf = trim($_POST['bedrijf']);
$tmail = trim($_POST['tmail']);
$tekst = trim($_POST['tekst']);
if(isset($naam ) && isset($tmail) && isset($tekst)){
if(!empty($naam) && !empty($tmail) && !empty($tekst)){
if(check_email_address($tmail)){
$to = 'name#something.com';
$subject = 'Some subject';
$message = 'Name: '.$naam.' //// Company: '.$bedrijf.'
-------------------------------------------------------
'.$tekst.'
-------------------------------------------------------
Sended on: '.date("F j, Y, g:i a").' - from: www.somthing.com';
$headers = 'From: '. $tmail . "\r\n" .
'Reply-To: '. $tmail . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
echo '0'; //Succes <3
}else{
echo '1'; //Invalid mail adres
}
}else{
echo '2'; //Empty fields
}
}else{
echo '3'; //Fail post
}
?>
Related
This is confusing me any ideas as to why I only receive the telephone number (missing the name and email fields) when a form is submitted? Ive tried changing everything but i can't seem to get the other 2 fields to work when submitted.
<aside class="sidebar">
<h3 class="text-center">Request a Callback</h3>
<div class="enquiry-wrapper">
<form id="enquiry-form" method="post" action="enquiry.php" class="clearfix">
<input type="text" name="enquiry-name" id="enquiry-name" autocomplete="off" placeholder="Name ...">
<input type="email" name="enquiry-email" id="enquiry-email" autocomplete="off" placeholder="Email ...">
<input type="tel" name="tel" id="tel" autocomplete="off" placeholder="Phone Number ...">
<div class="form-submit">
<input type="submit" class="btn btn-colour" name="enquiry-submit" id="enquiry-submit" value="Send message">
</div>
<!-- form-submit end -->
</form>
<div id="enquiry-message"></div>
</div>
<!-- enquiry-wrapper end -->
</aside>
This is the enquiry.php
<?php
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$from = 'contact#rpsfm.co.uk';
// an email address that will receive the email with the output of the form
$sendTo = 'contact#rpsfm.co.uk';
// subject of the email
$subject = 'new contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('enquiry-name' => 'Name', 'enquiry-email' => 'Email', 'tel' => 'Tel');
// message that will be displayed when everything is OK :)
$okMessage = header( 'Location: http://rpsfm.co.uk/thanks1.html' );
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
?>
This is the js.
jQuery(document).ready(function() {
"use strict";
$("#enquiry-form").submit(function() {
var e = $(this).attr("action");
$("#enquiry-message").slideUp(750, function() {
$("#enquiry-message").hide();
$("#enquiry-submit").after("").attr("disabled", "disabled");
$.post(e, {
name: $("#enquiry-name").val(),
email: $("#enquiry-email").val(),
tel: $("#tel").val()
}, function(e) {
document.getElementById("enquiry-message").innerHTML = e;
$("#enquiry-message").slideDown("slow");
$("#enquiry-form img.loader").fadeOut("slow", function() {
$(this).remove()
});
$("#enquiry-submit").removeAttr("disabled");
if (e.match("success") != null)
$("#enquiry-form").slideUp("slow")
})
});
return false
})
});
Hope I've done this right if not let me know any more info you need.
ATB
Luke
there are multiple things which make me wonder, besides that I do not understand what you are trying to accomplish.
In enquiry.php:
// message that will be displayed when everything is OK :)
$okMessage = header( 'Location: http://rpsfm.co.uk/thanks1.html' );
Taken this excerp from the manual:
The second special case is the "Location:" header. Not only does it
send this header back to the browser, but it also returns a REDIRECT
(302) status code to the browser unless the 201 or a 3xx status code
has already been set.
By passing this to a variable you are redirecting almost instantly before executing your code.
Secondly your JavaScript code does not seem to work as you desire. I think you want to send your form via AJAX, but your code is ignored, because the form is send via regular post.
event.preventDefault(); should prevent the sending of the form via regular submit.
Used like
jQuery(document).ready(function() {
"use strict";
$("#enquiry-form").submit(function(event) {
event.preventDefault();
// [...]
});
});
I update as I come along with more issues.
Update
Please take a look at this:
$(document).ready(function() {
"use strict";
$("#enquiry-form").submit(function(event) {
event.preventDefault();
var e = $(this).attr("action");
$("#enquiry-message").slideDown(750, function() {
$("#enquiry-message").hide();
$("#enquiry-submit").after("").attr("disabled", "disabled");
$.post(e, {
"enquiry-name": $("#enquiry-name").val(),
"enquiry-email": $("#enquiry-email").val(),
"tel": $("#tel").val()
}, function(e) {
document.getElementById("enquiry-message").innerHTML = e;
$("#enquiry-message").slideDown("slow");
$("#enquiry-form img.loader").fadeOut("slow", function() {
$(this).remove();
});
$("#enquiry-submit").removeAttr("disabled");
if (e.type === "success") {
$("#enquiry-form").slideUp("slow");
}
});
});
});
});
You have used the wrong variable names for the POST data. So your assoc array in the enquiry.php could not use the correct keys and left it out. It seems like the assignment of the header() function works, but it seems like very bad practice to me. You could return the ok message with your AJAX return call, instead of using the header() function.
I am making a one page website, and I would like to add a contact form in one section. So I am working with PHP, thing is, I cant seem to find any base pre-made forms that do not open a new webpage or direct that you to a new page once you submit. I would like to keep this one page, so I would like an overlay to appear once everything is all correct in the form and it has been submitted. No popups or redirects. This may require jQuery but I am not sure how to put it in so it actually does that.
Here is how I have set up the form in HTML:
<form action="mail.php" method="post" enctype="multipart/form-data" >
<label></label>
<input name="name" required placeholder="Your Name">
<label></label>
<input name="email" type="email" required placeholder="Your Email">
<label></label>
<textarea name="message" cols="20" rows="5" required placeholder="Message"></textarea>
<input id="submit" name="submit" type="submit" value="Submit">
</form>
Here is mail.php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: Website';
$to = 'email#emailhere.com';
$subject = 'Email Inquiry';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";?>
<?php
if ($_POST['submit']) {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Thank you for your message! </p>';
} else {
echo '<p>An error occurred. Try sending your message again.</p>'; }}?>
Now, I would like to be able to remove the echo for the thank you message, and replace it with jQuery code for an overlay I made.
$(document).ready(function() {
$("#overlay").show();
});
I am missing a part of the function, as right now its just going to show when the page is ready. But I don't know where to put that/how it works with this PHP.
My confusion is I am not sure where the PHP is telling it to go to some blank page when you hit submit, so I don't know where to stop and start the script. I also just don't know how to mesh this all together properly. Is it in the PHP or the script where I have it check all elements before it can call to action the "thank you overlay". I just don't really know what direction to go from here.
Thank you so much for your time. I am learning a lot of this on my own so my knowledge is patchy.
Please let me know if I can help clear anything up.
-rj
Hava a look at jQuery Ajax. Usually, you throw data by the server by going to another page, so you do a "synchronous" request. The Ajax technique enables you to stay on the page, while a request is made, an "asynchronous" request. JQuery makes Ajax requests much simpler. Good luck ;)
Try adding an onclick event on #submit button and use a Javascript XMLHttpRequest object instead of action="mail.php" in the form
This is working from example, hope it can push you on correct path :)
Add this string right after submit button
<span class="status"></span>
PHP
if($mail_sent){
echo "<span class='notice'>Your message has been sent, thank you.</span>";
exit;
}else{
echo "<span class='error'>We couldn't send your message please try again, thank you.</span>";
exit;
}
And JS part to display errors
jQuery(function($) {
$("#contact-form").submit(function(){
return false;
})
$("#contact-form input[type=submit]").click(function(event){
var formerror = false;
$(this).attr('disabled', 'disabled').css({'cursor': 'auto', 'opacity': 0.5});
$('.status').fadeIn('normal').html('Loading please wait...');
$(this).closest("form").find("input, textarea").each(function(){
error = false;
switch($(this).attr('id')){
case 'name':
if($(this).val().match(/^[a-zA-Z\ \']+$/) == null || $(this).val() == "Name")
error = true;
else
error = false;
break;
case 'email':
if($(this).val().match(/^[a-zA-Z0-9_\.\-]+\#([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/) == null)
error = true;
else
error = false;
break;
case 'message':
if($(this).val().length < 4 || $(this).val() == "Type your message")
error = true;
else
error = false;
break;
}
if(error){
$(this).css('border-color', '#f00');
formerror = true;
}
});
if(formerror){
$('.status').fadeOut('normal',
function(){
$(this).html("One or more required fields are missing or invalid, please correct and resend.")
.addClass("error");
}
).fadeIn();
$(this).removeAttr('disabled').css({'cursor': 'pointer', 'opacity': 1});
event.preventDefault();
}else{
//get teh link
$.post( "contact.php", { name: $('#name').val(),
email: $('#email').val(),
website: $('#website').val(),
message: $('#message').val()
})
.done(function( data ) {
$('.status').removeClass('error').fadeIn('normal', function(){$(this).html(data)});
$("#contact-form input[type=submit]").removeAttr('disabled').css({'opacity': 1, 'cursor': 'pointer'});
});
event.preventDefault();
}
});
});
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!
*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!