Ajax Contact Form Not Sending Emails [duplicate] - javascript

This question already has answers here:
Ajax Contact Form Problems - No email being sent
(2 answers)
Closed 9 years ago.
Sorry for being a noob but I'm trying my best. I've done and read everything I could find and I have never got this to work. Would really appreciate the help. The form id matches in the html and javascript. The PHP is linked in the Javascript and I have the javascript linked in the head of my html. What am I missing? I've tried other codes I found online as well and nothing.. The issue is that no email ever gets sent through. If you hit send the page reloads and thats it.
<!--[if lte IE 8]>
<script src="js/html5shiv.js"></script><![endif]-->
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.dropotron.js"></script>
<script src="js/skel.min.js"></script>
<script src="js/skel-panels.min.js"></script>
<script src="js/init.js"></script>
<script src="js/contact.js"></script>
<noscript>
<link rel="stylesheet" href="css/skel-noscript.css" />
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/style-noscript.css" />
</noscript>
<!-- Contact Form-->
<div class="content style4 featured">
<div class="container small">
<form id="contact" form method="post">
<div class="row half">
<div class="6u"><input type="text" class="text" name="name" placeholder="Name" /></div>
<div class="6u"><input type="text" class="text" placeholder="Email" name="email" /></div>
</div>
<div class="row half">
<div class="12u"><textarea name="text" placeholder="Message"></textarea></div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li><input type="submit" class="button" value="Send Message" /></li>
<li><input type="reset" class="button alt" value="Clear Form" /></li>
<p class="success" style="display:none">Your message has been sent successfully.</p>
<p class="error" style="display:none">E-mail must be valid and message must be longer than 100 characters.</p>
</ul>
</div>
</div>
</form>
</div>
</div>
PHP:
<?php
// Email Submit
// Note: filter_var() requires PHP >= 5.2.0
if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['text']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
// detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if (preg_match( $test, $val ))
exit;
}
//send email
mail( "test#gmail.com", "Contact Form: ".$_POST['name'], $_POST['text'], "From:" . $_POST['email'] );
}
?>
JS:
$('#contact').submit(function() {
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : dataString,
cache : false,
success : function() {
$("#contact").fadeOut(300);
$("#notice").fadeIn(400);
}
});
return false;
});
Thanks.

try preventing the default form submission by changing:
$('#contact').submit(function() {
...
to
$('#contact').submit(function(evt) {
evt.preventDefault();
//rest of your js code
and you dont have input elements with id name, email and message as per your posted code. Add those as ids to your input elements

Related

script in head doesn't seem to be executing

I'm trying to use lambda on AWS with api gateway to do a contact form on a static S3 web site, based on this blog post: https://aws.amazon.com/blogs/architecture/create-dynamic-contact-forms-for-s3-static-websites-using-aws-lambda-amazon-api-gateway-and-amazon-ses/
I don't think my script is running because my submit button does nothing. Any ideas what I might be doing wrong?
Here's my full page code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ltdrescue Contact Form</title>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<script "text/javascript">
function submitToAPI(e) {
e.preventDefault();
var URL = "https://abc1234.execute-api.us-east-1.amazonaws.com/01/contact";
var Namere = /[A-Za-z]{1}[A-Za-z]/;
if (!Namere.test($("#name-input").val())) {
alert ("Name can not less than 2 char");
return;
}
var mobilere = /[0-9]{10}/;
if (!mobilere.test($("#phone-input").val())) {
alert ("Please enter valid mobile number");
return;
}
if ($("#email-input").val()=="") {
alert ("Please enter your email id");
return;
}
var reeamil = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,6})?$/;
if (!reeamil.test($("#email-input").val())) {
alert ("Please enter valid email address");
return;
}
var name = $("#name-input").val();
var phone = $("#phone-input").val();
var email = $("#email-input").val();
var desc = $("#description-input").val();
var data = {
name : name,
phone : phone,
email : email,
desc : desc
};
$.ajax({
type: "POST",
url : "https://abc1234.execute-api.us-east-1.amazonaws.com/01/contact",
dataType: "json",
crossDomain: "true",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function () {
// clear form and show a success message
alert("Successfull");
document.getElementById("contact-form").reset();
location.reload();
},
error: function () {
// show an error message
alert("UnSuccessfull");
}});
}
</script>
</head>
<body>
<div id="wrap">
<div class="top_corner"></div>
<div id="main_container">
<div id="header">
<div id="logo"><img src="images/logo.gif" alt="" title="" border="0" /></div>
<div id="menu">
<ul>
<li>Home</li>
<li>About</li>
<li>Adopt</li>
<li>Support Us</li>
<li>Resources</li>
<li><a class="current" href="contact.html" title="">Contact</a></li>
</ul>
</div>
</div>
<div class="center_content_pages">
<div class="financial-application-form">
<h2>Contact Us</h2>
<p>
Please use this form to contact us with any suggestions or questions.
<br><br>
<b>Note:</b> due to the ever increasing number of animals in dire need of rescue, we are unable to intake owner surrenders.
</p>
<form id="contact-form" method="post">
<h4>Name:</h4>
<input type="text" style="height:35px;" id="name-input" placeholder="Enter name here…" class="form-control" style="width:100%;" /><br/>
<h4>Phone:</h4>
<input type="phone" style="height:35px;" id="phone-input" placeholder="Enter phone number" class="form-control" style="width:100%;"/><br/>
<h4>Email:</h4>
<input type="email" style="height:35px;" id="email-input" placeholder="Enter email here…" class="form-control" style="width:100%;"/><br/>
<h4>How can we help you?</h4>
<textarea id="description-input" rows="3" placeholder="Enter your message…" class="form-control" style="width:100%;"></textarea><br/>
<div class="g-recaptcha" data-sitekey="6Lc7cVMUAAAAAM1yxf64wrmO8gvi8A1oQ_ead1ys" class="form-control" style="width:100%;"></div>
<button type="button" onClick="submitToAPI(event)" class="btn btn-lg" style="margin-top:20px;">Submit</button>
</form>
</div
</div>
<div class="testimonials">
<h2>Need to find a new home for your pet?</h2>
<p>
<img src="http://images.adoptapet.com/images/shelter-badges/Approved-Shelter_Paw-Print_Badge.png">
</p>
</div>
<div class="clear"></div>
</div>
<div class="footer">
<div class="footer_links">
<a class="current" href="default.html" title="">Home</a>
About
Adopt
Support Us
Resources
Contact
</div>
</div>
</div>
</div>
</body>
</html>
You have not added the script tag correctly Please refer below to correct it.
Wrong Way
<script "text/javascript">
Right Way
<script type="text/javascript"></script> OR <script></script>
See in HTML5 you can omit the type attribute but it's a good practice to add it.

Server Side Validation Show Success or Error message inline

I built a form for my class (private access only) where every one submit a form with some information. The information like Full name of the course, Subject, Select options for the list of teachers and a checkboxes for available class rooms. Some might like big or small rooms and available accessories for study. I did an effort for designing and built a form in bootstrap and php. Forms looks Okay and the validation is inline till I need to include one more feature in it. Every time when i submit a form it gets loaded. I mean, the form works with the php and html validation but the whole page gets loaded everytime i click the submit. I google it and know the this goal should be achieve by Ajax. I watched youtube videos and follow other questions here but got nothing. Inline validation or show the success message on the same page still not working. I want is when the user submit the form it will show the alert-success message on the samepage without refreshing or the error message inline if any errors there with server side validation. Codes easily available on internet.
html:
<?php
include('ajaxreturn.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello, world!</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<body>
<form id="submit" onsubmit="submitForm(); return false;">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="form-control-label" for="Name">Name</label>
<input class="form-control" id="name" type="text" name="name" value= "<?php if (isset($_POST["name"])) echo htmlspecialchars($_POST["name"]) ?>">
<span class="text-danger"><?php echo $name_error;?></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="form-control-label" for="subject">Subject</label>
<input class="form-control form-control" type="text" name="subject" id="subject" value= "<?php if (isset($_POST["subject"])) echo htmlspecialchars($_POST["subject"]) ?>">
<span class="text-danger"><?php echo $subject_error;?></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="Category">Category</label>
<select class="form-control pt-0 pb-0" id="category">
<option>...</option>
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-check pl-3 pt-1">
<label class="form-check-label">
<input name="classroom" id="classroom" class="form-check-input" type="checkbox" <?php if (isset($classroom) && $classroom=="classroom") echo "checked";?> value="classroom">
L-1
</label>
</div>
<span class="text-danger pl-3 pt-0"><?php echo $classroom_error;?></span>
</div>
div class="row">
<div class="form-check pl-3 pt-1">
<label class="form-check-label">
<input name="classroom" id="classroom" class="form-check-input" type="checkbox" <?php if (isset($classroom) && $classroom=="classroom") echo "checked";?> value="classroom">
L-2
</label>
</div>
<span class="text-danger pl-3 pt-0"><?php echo $classrooms_error;?></span>
</div>
<div class="row">
<button id="submit" name="submit" value="submit" type="submit" class="btn btn-success">submit</button>
<span class="text-danger"> Wrong!</span>
<span class="text-success"> Thanks!</span>
</div>
</form>
<!-- Optional JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<!-- <script src="main.js"></script> -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
php:
<?php
// Form Variables
$name = "";
$subject = "";
$category = "";
$classroom="";
//Error Variables
$name_error ="";
$subject_error = "";
$category_error = "";
$classroom_error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Your Name";
} else {
$name = validation($_POST["name"]);
// Function calling and checking the letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Your name must contain Letters, Numbers and Spaces";
}
}
if (empty($_POST["subject"])) {
$subject_error = "Your Subject";
} else {
$website = validation($_POST["subject"]);
// Function calling and checking the letters and whitespace
if ((!preg_match("/^[a-zA-Z ]*$]/", $subject)) {
$subject_error = "Subjets must contain Letters, Numbers and Spaces";
}
}
if (empty($_POST["category"])) {
$category_error = "Please select categoy";
} else {
$category = validation($_POST["category"]);
}
if (empty($_POST["classroom"])) {
$classroom_error = "Select the Class Room";
} else {
$classroom = validation($_POST["classroom"]);
}
}
function validation($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Ajax:
<script>
function _(id){ return document.getElementById(id); }
function submitForm(){
_("submit").disabled = true;
_("status").innerHTML = 'please wait ...';
var formdata = new FormData();
formdata.append( "name", _("name").value );
formdata.append( "subject", _("subject").value );
formdata.append( "category", _("category").value );
formdata.append( "classroom", _("classroom").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "ajaxreturn.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
_("submit").innerHTML = '<h2>Thanks '+_("name").value+', your message has been sent.</h2>';
} else {
_("status").innerHTML = ajax.responseText;
_("submit").disabled = false;
}
}
}
ajax.send( formdata );
}
</script>
Error:
ajaxform.php?name=&website=&submit=submit:78 Uncaught TypeError: Cannot read property 'value' of null
at submitForm (ajaxform.php?name=&website=&submit=submit:78)
at HTMLButtonElement.onclick (ajaxform.php?name=&website=&submit=submit:58)
submitForm # ajaxform.php?name=&website=&submit=submit:78
onclick # ajaxform.php?name=&website=&submit=submit:58
ajaxform.php?name=&website=&submit=submit:78
formdata.append( "category", _("category").value );
onclick # ajaxform.php?name=&website=&submit=submit:58
<button name="submit" id="submit" onclick="submitForm()" value="submit" type="submit" class="btn btn-success">submit</button>
Category with Select options Tag
<option value=1>1</option>
<option value=1>1</option>
<option value=1>1</option><option value=1>1</option>
Trying changing the ajax inside to this.
if (this.status == 200 && this.readyState == 4) {
this.responseText;
The rest of your code above looks right. I have never seen xmlhttprequest used having a variable name inside, Usually it looks like
var xhr1 = new XMLHttpRequest();
xhr1.open('POST', "ajaxreturn.php", true);
xhr1.onreadystatechange = function() {
if (this.status == 200 && this.readyState == 4) {
console.log(this.responseText);
dostuff = this.responseText;
};//end onreadystate
xhr1.send();
I dont know enough php to take a look at your server side validation. I use NodeJs for all of that. Did you console log your this.responseText to see what variable your server is sending back. Also don't have your submit button submit, that is also your problem, have it run the onSubmit function. So...
<button id="submit" name="submit" onclick="submitForm()" class="btn btn-success">submit</button>
and take the onSubmit off of your form tag. I believe this will fix your issues.
When you submit the form, thats what opens a new page, when you just run the function with ajax, that won't make the browser open a new page. It just happens in the background.

Contact Form Not Submitting

Using Zurb Foundation 5 and contact form will not submit. Nothing happens when clicking submit button. It should replace form with a thank you message and send the form data to my email. Any help greatly appreciated...
HTML:
<body>
<section id="footer">
<div class="row">
<div class="small-12 medium-6 large-6 columns">
some other stuff
</div>
<div class="small-12 medium-6 large-6 columns">
<form id="myForm" data-abide="ajax">
<div class="contactform">
<div class="name-field">
<label>Your name <small>required</small>
<input id="name" type="text" required pattern="[a-zA-Z]+">
<small class="error">Be sure and leave your name.</small>
</label>
</div>
<div class="email-field">
<label>Email <small>required</small>
<input id="email" type="email" required>
<small class="error">Oops, you forgot your email.</small>
</label>
</div>
<div class="text-field">
<label>Message <small>required</small>
</label>
<textarea id="message" required></textarea>
<small class="error">I see you're the quiet type. How about a short message?</small>
</div>
<button type="submit">Submit</button>
</div>
</form>
</div>
</div>
</section>
JS:
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script>
$(document).on('opened', '[data-reveal]', function () {
var modal = $(this);
$(window).trigger('resize');
});
</script>
<script>
$(document).foundation();
</script>
<script>
$('#myForm')
.on('valid.fndtn.abide', function () {
var name = $("input#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
//Data for response
var dataString = 'name=' + name +
'&email=' + email +
'&message=' + message;
//Begin Ajax call
$.ajax({
type: "POST",
url:"php/mail.php",
data: dataString,
success: function() {
$('.contactform').html("<div id='thanks'></div>");
$('#thanks').html("<h2>Thanks!</h2>")
.append("<p>Glad to hear from you "+ name +"! I'll be in touch soon.</p>")
.hide()
.fadeIn(1500);
},
}); //ajax call
return false;
});
</script>
PHP
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$msg = "
Name: $name
Email: $email
Comments:
$message
";
$to = "parker.w.gibson#gmail.com";
$subject = "Web Form";
$message = $msg;
$headers = "Web Form";
mail($to,$subject,$message,$headers);
?>
edited to separate JS
I think this is some sort of a cross domain issue.Your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary POST. Modern browsers will only allow Ajax calls to services in the same domain as the request. To enable CORS on your remote server go to the following web page which gives instructions for the different types of servers .Try reading this .
FYI
CORS

AJAX Contact Form Reloads Page but Doesn't Send Email

Hi like the title say my code seems to reload the page when hitting the send button but never actually sends the email. I've tried and read everything I could and nothing is allowing it to work properly. I would sincerely appreciate the help.
<!--[if lte IE 8]>
<script src="js/html5shiv.js"></script><![endif]-->
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.dropotron.js"></script>
<script src="js/skel.min.js"></script>
<script src="js/skel-panels.min.js"></script>
<script src="js/init.js"></script>
<script src="js/contact.js"></script>
<noscript>
<link rel="stylesheet" href="css/skel-noscript.css" />
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/style-noscript.css" />
</noscript>
<!-- Contact Form-->
<div class="content style4 featured">
<div class="container small">
<form id="contact" form method="post">
<div class="row half">
<div class="6u"><input type="text" class="text" name="name" id ="name" placeholder="Name" /></div>
<div class="6u"><input type="text" class="text" placeholder="Email" name="email" id="email"/></div>
</div>
<div class="row half">
<div class="12u"><textarea name="text" placeholder="Message" id="message"></textarea></div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li><input type="submit" class="button" value="Send Message" /></li>
<li><input type="reset" class="button alt" value="Clear Form" /></li>
<p class="success" style="display:none">Your message has been sent successfully.</p>
<p class="error" style="display:none">E-mail must be valid and message must be longer than 100 characters.</p>
</ul>
</div>
</div>
</form>
PHP:
<?php
// Email Submit
// Note: filter_var() requires PHP >= 5.2.0
if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['message']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
// detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if (preg_match( $test, $val ))
exit;
}
//send email
mail( "test#gmail.com", "Contact Form: ".$_POST['name'], $_POST['text'], "From:" . $_POST['email'] );
}
?>
JS:
$('#contact').submit(function(e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
//var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : {name:name,email:email,message:message},
cache : false,
success : function() {
$("#contact").fadeOut(300);
$("#notice").fadeIn(400);
}
});
return false;
});
Thank you for your time.
Assuming that your email function works well in the AJAX part you need to use event.preventDefault()
Also noticed in the mail.php you have this
if ( isset($_POST['email'])
&& isset($_POST['name']) &&
**isset($_POST['text'])** &&
filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
}
this will fail isset($_POST['text']) since there is no post element I suppose it should be isset($_POST['message'])
Also your form elements are missing the ids please add them as
<!-- Contact Form-->
<div class="content style4 featured">
<div class="container small">
<form id="contact" form method="post">
<div class="row half">
<div class="6u"><input type="text" class="text" name="name" id ="name" placeholder="Name" /></div>
<div class="6u"><input type="text" class="text" placeholder="Email" name="email" id="email"/></div>
</div>
<div class="row half">
<div class="12u"><textarea name="text" placeholder="Message" id="message"></textarea></div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li><input type="submit" class="button" value="Send Message" /></li>
<li><input type="reset" class="button alt" value="Clear Form" /></li>
<p class="success" style="display:none">Your message has been sent successfully.</p>
<p class="error" style="display:none">E-mail must be valid and message must be longer than 100 characters.</p>
</ul>
</div>
</div>
</form>
</div>
</div>
<script>
$('#contact').submit(function(e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
//var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : {name:name,email:email,message:message},
cache : false,
success : function() {
$("#contact").fadeOut(300);
$("#notice").fadeIn(400);
}
});
return false;
});
</script>
I have just tested and it worked for me.
Can you modify your function, i think it is not getting called at all.
$('#contact').on('submit', function(e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
//var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : {name:name,email:email,message:message},
cache : false,
success : function() {
$("#contact").fadeOut(300);
$("#notice").fadeIn(400);
}
});
return false;
});
Does your mail() function actually work by itself? Like can you send some mail using that function? Also, the PHP isset function will take mixed arguments like so...
PHP:
if(isset( $_POST['email'], $_POST['name'], $_POST['text'], filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$rules = "/(content-type|bcc:|cc:|to:)/i";
foreach( $_POST as $key => value ) {
if(preg_match($rules, $value))
exit;
} //end of foreach
} //end of if
your submit button is doing a form post, u need to stop the default behavior of that button and call your method performing ajax on click of submit button.
http://api.jquery.com/event.preventdefault/
In JS you are accessing the values by id but you are giving id's just do the thing give id's for input tags i.e. name, email, message
<div class="6u"><input type="text" class="text" name="name" id="name" placeholder="Name" /></div>
<div class="6u"><input type="text" class="text" placeholder="Email" id="email" name="email" /></div>
<div
class="12u">
give your dataString as
var dataString = {name:name,email:email,message:message};
for more set header in mail i.e.
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . "\r\n";
mail( "test#gmail.com", "Contact Form: ".$_POST['name'], $_POST['text'], "From:" .$_POST['email'] ,$headers);
better if you write it just before where the body tag is closing instead of writing in head. and above code will get executed whenever you click on an anchor tag. so be specific like this. <body> <!-- just before body tags closes--><script> $('a.buttonClassName').click(function(e){e.preventDefault(); $("<div>default"+e.type+ "prevented</div>").appendTo("#log") })</script></body>

What is causing PHP Notice: Undefined index:?

I have a user registration form in my jQuery mobile app but when I submit the form via an $.ajax call it inserts only a blank row and the error_log says:
[01-Dec-2013 13:27:13] PHP Notice: Undefined index: fname in /home2/hedonsof/public_html/tcob/php/register.php on line 10
[01-Dec-2013 13:27:13] PHP Notice: Undefined index: lname in /home2/hedonsof/public_html/tcob/php/register.php on line 11
[01-Dec-2013 13:27:13] PHP Notice: Undefined index: username in /home2/hedonsof/public_html/tcob/php/register.php on line 12
[01-Dec-2013 13:27:13] PHP Notice: Undefined index: password in /home2/hedonsof/public_html/tcob/php/register.php on line 13
[01-Dec-2013 13:27:13] PHP Notice: Undefined index: email in /home2/hedonsof/public_html/tcob/php/register.php on line 14
My index:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Mobile Web App</title>
<link href="lib/BlackBerry-JQM-all-1.0.0.css" rel="stylesheet" type="text/css"/>
<link href="style/main.css" rel="stylesheet" type="text/css"/>
<script src="lib/BlackBerry-JQM-all-1.0.0.js" type="text/javascript"></script>
<script src="ui/jquery.ui.map.js" type="text/javascript"></script>
<script src="ui/jquery.ui.map.services.js" type="text/javascript"></script>
<script src="ui/jquery.ui.map.extensions.js" type="text/javascript"></script>
<script src="app.js" type="text/javascript"></script>
<script src=http://maps.googleapis.com/maps/api/js?sensor=false type="text/javascript"></script>
</head>
<body>
<div data-role="page" id="landing">
<div data-role="header"> </div>
<div data-role="content">
<div id="map_
canvas" style="height:600px"> </div>
<div id="info"> </div>
</div>
<div data-role="footer">
<div data-role="actionbar"> <a id="help" data-role="tab"> <img src="img/ic_help.png"/>
<p>Help</p>
</a> <a id="chat" data-role="tab"> <img src="img/ic_textmessage.png"/>
<p>Chat</p>
</a> <a id="add" data-role="tab" href="#add"> <img src="img/ic_add.png"/>
<p>Add </p>
</a> <a id="settings" data-role="tab" href="#register"> <img src="img/Core_applicationmenu_icon_settings.png" alt="" />
<p>Settings</p>
</a> </div>
</div>
</div>
<div data-role="page" id="register">
<div data-role="header"> </div>
<div data-role="content">
<div class="BB10Container">
<form id="adduser">
<label for="fname">First Name</label>
<input type="text" name="fname" id="fname" placeholder="John"/>
<label for="lname">Last Name</label>
<input type="text" name="lname" id="lname" placeholder="Doe"/>
<label for="username">Username</label>
<input type="text" name="username" id="username" placeholder="Username"/>
<label for="basic">Password</label>
<input type="password" name="password" id="password" placeholder="Password"/>
<label for="verpass">Repeat Password</label>
<input type="password" name="verpass" id="verpass" placeholder="Password"/>
<label for="regemail">Email</label>
<input type="email" name="email" id="email" placeholder="your#email.com"/>
<input type="submit" data-role="button" data-inline="true" data-icon="check" value="Submit" id="regsubmit">
</form>
</div>
<div id="info"> </div>
</div>
<div data-role="footer">
<div data-role="actionbar"> <a id="help" data-role="tab"> <img src="img/ic_help.png"/>
<p>Help</p>
</a> <a id="chat" data-role="tab"> <img src="img/ic_textmessage.png"/>
<p>Chat</p>
</a> <a id="add" data-role="tab" href="#add"> <img src="img/ic_add.png"/>
<p>Add </p>
</a> <a id="settings" data-role="tab" href="#settings"> <img src="img/Core_applicationmenu_icon_settings.png" alt="" />
<p>Settings</p>
</a> </div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#regsubmit").click(function(){
var formData = $("#adduser").serialize();
alert(formData);
$.ajax({
type: "POST",
url: "register.php",
cache: false,
data: fname: fname,
lname: lname,
username: username,
password: password,
email: email,
success: onSuccess
});
return false;
});
});
function onSuccess(data, status)
{
alert('Success');
}
</script>
</body>
</html>
My PHP
<?php
require('connect.php');
ini_set('display_errors', 'On');
error_reporting(E_ALL);
try{
$db = mysql_connect($host, $dbusername, $password ) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
// Note: You need to verify the data coming in isn't harmful, this SQL pretty much puts anything into the database so make sure to change this!
$fname = $_POST['fname'];
$lname =$_POST['lname'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
mysql_query("INSERT INTO members (fname, lname, username, password,email) VALUES ('$fname', '$lname','$username','$password','$email')");
mysql_close($db);
echo "SUCCESS";
}
catch(Exception $e)
{
echo $e->getMessage();
// Note: Log the error or something
}
?>
You are sending blank values in your data. You have defined your data field for the $.POST as
data: fname: fname,
lname: lname,
username: username,
password: password,
email: email,
but you have never set the value of the parameters fname,lname,etc. Meaning, when you say fname: fname -- what is the value of fname on the right side of the colon? Also, posted further down, the argument list needs to be wrapped in a {}. You can see an example of this on the jQuery .ajax() documentation page.
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
However, to solve your issues, just send the serialized form data as your post object
data: formdata
This will send the serialized form that you have already performed in with the POST.
The data you are POSTing to register.php from your Ajax call needs to be a single JSON like this (notice the added {} around the fields):
data: {fname: fname,
lname: lname,
username: username,
password: password,
email: email},
From this change you wil be able to access the fields inside the $_POST associative array. Which should address the PHP error.
You may also want to check out http://api.jquery.com/serialize/ this will automcatically send all form elements in the form as key value pairs in the $_POST request

Categories

Resources