PHP variable from external file? - php

*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

Related

jQuery AJAX reaches memory stack limit upon just 18 args

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.

wp_mail() + Ajax + ValidationEngine + $wpdb->insert

I decided to ask this question because there is no simple answer to it.
I have a contact form in my home.php which looks like:
HTML:
<form id="js-calculator" name="calculator" action="" method="post">
<input type="email" name="email" id="email" placeholder="E-mail" />
<input type="tel" name="phone" id="phone" placeholder="Phone" />
<textarea name="message" id="message" placeholder="Message"></textarea>
<label for="accept"><input class="" type="checkbox" id="accept" name="accept" /> I agree to terms and conditions</label>
<button type="submit" id="send__btn">Wyślij wycenę</button></p>
</form>
JavaScript:
jQuery(document).ready(function ($) {
$('#js-calculator').submit(function (e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: '<?php echo admin_url("admin-ajax.php") ?>',
type: 'post',
dataType: 'JSON',
data: $this.serialize()
}
});
});
});
PHP in functions.php
// Function to send emails
function sendMail () {
$subject = 'Automatic evaluation';
$headers = 'From: My Website Contact Form <contact#mysite.com>';
$send_to = "office#mysite.com, ". $_POST['email'];
$subject = "Evaluation for ". $_POST['name'];
$message = "Message from ".$_POST['message'];
}
add_action('wp_ajax_sendhtmlmail', 'sendMail');
add_action('wp_ajax_nopriv_sendhtmlmail', 'sendMail');
add_filter( 'wp_mail_content_type', 'set_content_type' );
function set_content_type( $content_type ) {
return 'text/html';
}
// Function to update DB
function addCustomer(){
global $wpdb;
$phone = $_POST['phone'];
$email = $_POST['email'];
$accept = $_POST['accept'];
if($wpdb->insert('customers',array(
'phone'=>$phone,
'email'=>$email,
'accept'=>$accept
))===FALSE){
echo "Error";
} else {
$wpdb->insert_id;
}
die();
}
add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');
What I would like to achive is:
1. Send an HTML email to client and to website admin,
2. Add client details to Database, check if email exists,
3. Have a secure connections and data flow;
Right now I have no idea what I`ve done wrong... Any help will be much appreciated.
You are almost there, couple of things:
In your JS ajax call, you need to specify the action to call, here's modified call:
jQuery(document).ready(function ($) {
$('#js-calculator').submit(function (e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: '<?php echo admin_url("admin-ajax.php?action=sendhtmlmail") ?>',
type: 'post',
dataType: 'JSON',
data: $this.serialize()
}
});
});
});
Now, lets look at the php functions:
// Function to send emails
function sendMail () {
$data = array(
'email' = sanitize_email($_POST['email']),
'name' = sanitize_text_field($_POST['name']),
'message' = sanitize_text_field($_POST['message']),
);
$subject = 'Automatic evaluation;
$headers = 'From: My Website Contact Form <contact#mysite.com>';
$send_to = "office#mysite.com, ". $data['email'];
$subject = "Evaluation for ". $data['name'];
$message = "Message from ".$data['message'];
wp_mail($send_to, $subject, $message, $headers);
addCustomer($data);
// TODO: Fill in this $response array with meaninfull data (check output from wp_mail and addCustomer)
$response = array(
'success' => true
);
wp_send_json($response);
}
add_action('wp_ajax_sendhtmlmail', 'sendMail');
add_action('wp_ajax_nopriv_sendhtmlmail', 'sendMail');
Just missing the wp_mail call, and the cleanup of the inputs, I removed your other ajax call, and have the sendMail function just pass the data to the addCustomer function. You'll notice a wp_send_json call, this is to send the response to the JS. https://codex.wordpress.org/Function_Reference/wp_send_json
Now lets look at your addCustomer function:
// Function to update DB
function addCustomer($data){
global $wpdb;
$phone = $data['phone'];
$email = $data['email'];
$accept = $data['accept'];
if($wpdb->insert('customers',array(
'phone'=>$phone,
'email'=>$email,
'accept'=>$accept
))===FALSE){
return false;
} else {
return $wpdb->insert_id;
}
}
The only thing that change here, is the return, so that the caller knows if it failed.
To handle inputs from user, check this doc from wordpress and core functions:
https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data
Or you could use the following plugins together:
https://wordpress.org/plugins/contact-form-7/
https://wordpress.org/plugins/flamingo/
Here's how to use it: https://contactform7.com/save-submitted-messages-with-flamingo/
I hope this helps you!
Regards,
P.S wordpress questions are better suited here: https://wordpress.stackexchange.com/

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!

jQuery Mobile PHP Form - Get Checked Radio Button Value

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

Categories