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!
Related
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.
I'm trying to add a PHP form to a website I'm working on. Not real familiar with PHP, but I've put the file in the upload folder in the CMS.
I think I've linked the jQuery and other files correctly and I've edited the PHP file putting in emails etc. This one also calls on another PHP validation file.
Anyway it shows up normally and I can fill it out but it goes to a 404 page and doesn't work.
My question is, what linking convention do I use to link to the php file and is it in the right place? I use cPanel where the CMS is installed.
Instead of putting: action="url([[root_url]]/uploads/scripts/form-to-email.php"
should I just put: action="uploads/scripts/form-to-email.php"?
The page in question is here: www.edelweiss-web-design.com.au/captainkilowatt/
Also, anyone know a good captcha I can integrate with it...? Thanks!
<div class="contact-form">
<h1>Contact Us</h1>
<form id="contact-form" method="POST" action="uploads/scripts/form-to-email.php">
<div class="control-group">
<label>Your Name</label>
<input class="fullname" type="text" name="fullname" />
</div>
<div class="control-group">
<label>Email</label>
<input class="email" type="text" name="email" />
</div>
<div class="control-group">
<label>Phone (optional)</label>
<input class="phone" type="text" name="phone" />
</div>
<div class="control-group">
<label>Message</label>
<textarea class="message" name="message"></textarea>
</div>
<div id="errors"></div>
<div class="control-group no-margin">
<input type="submit" name="submit" value="Submit" id="submit" />
</div>
</form>
<div id='msg_submitting'><h2>Submitting ...</h2></div>
<div id='msg_submitted'><h2>Thank you !<br> The form was submitted Successfully.</h2></div>
</div>
Here is the php:
<?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?><?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://www.edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?>
I've added the php file.
So, in the action part, when I submit the form, it no longer gives me a 404 but takes me to a blank page with the 'form-to-email.php' page. However, the script is not working from what I can tell. Again, I know html and css, and little javascipt, but how php is meant to work...?
What am I doing wrong?
I would suggest using one of the modules for CMS instead of trying to build form in PHP from scratch. It is much more safer to use CMS buildin functions and that is the point of using the CMS in the first place. For CMS made simple the formbuilder module is here:
http://dev.cmsmadesimple.org/projects/formbuilder
Thanks for all the comments.
I found another form with a captcha (PHP) and preserved the whole structure by uploading it as is into CMSMS uploads folder.
I then used iframe to embed the form on my page, changed a couple of little details with the CSS and wording, and bob's your uncle, it works just fine.
For anyone interested, I used: www.html-form-guide.com/contact-form/creating-a-contact-form.html
This is free and I am certainly not trying to spam as I am in no way affiliated with this site or any sites associated with it.
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 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).
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
}
?>