What is causing PHP Notice: Undefined index:? - javascript

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

Related

Novice developer - Trouble with php contact form templates - probably something dumb

I am a novice developer and for some reason I have never been able to get a php contact form to function properly. I've tried templates from bootstrapious and reusable forms but I've never been able to get them to work. My ultimate goal is to have a form with recaptcha but I can't get just a regular old form to work. Here are the codes from my latest attempt. I've been working on this for days and I feel like I'm missing something small and stupid. Thank you
<!DOCTYPE html>
<html lang="en">
<head>
<title>Contact Form Tutorial by Bootstrapious.com</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet" type="text/css">
<link href="custom.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xl-8 offset-xl-2 py-5">
<h1>Contact form Tutorial from Bootstrapious.com</h1>
<p class="lead">This is a demo for our tutorial dedicated to crafting working Bootstrap contact form with PHP and AJAX background.</p>
<p class="lead">This file uses PHPMailer to send the emails.</p>
<form id="contact-form" method="post" action="contact-2.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">Firstname *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">Lastname *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please, leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Send message">
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-muted"><strong>*</strong> These fields are required. Contact form template by Bootstrapious.</p>
</div>
</div>
</div>
</form>
</div><!-- /.8 -->
</div> <!-- /.row-->
</div> <!-- /.container-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js" integrity="sha256-dHf/YjH1A4tewEsKUSmNnV05DDbfGN3g7NMq86xgGh8=" crossorigin="anonymous"></script>
<script src="contact-2.js"></script>
</body>
PHP
<?php
/*
THIS FILE USES PHPMAILER INSTEAD OF THE PHP MAIL() FUNCTION
*/
require 'PHPMailer-master/PHPMailerAutoload.php';
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$fromEmail = 'uprightjared#gmail.com';
$fromName = 'Demo contact form';
// an email address that will receive the email with the output of the form
$sendToEmail = 'uprightjared#gmail.com';
$sendToName = 'Demo contact form';
// subject of the email
$subject = 'New message from contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone',
'email' => 'Email', 'message' => 'Message');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back
to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try
again later';
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off by
error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailTextHtml = "<h1>You have a new message from your contact form</h1>
<hr>";
$emailTextHtml .= "<table>";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
}
}
$emailTextHtml .= "</table><hr>";
$emailTextHtml .= "<p>Have a nice day,<br>Best,<br>Ondrej</p>";
$mail = new PHPMailer;
$mail->setFrom($fromEmail, $fromName);
$mail->addAddress($sendToEmail, $sendToName); // you can add more addresses
by simply adding another line with $mail->addAddress();
$mail->addReplyTo($from);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->msgHTML($emailTextHtml); // this will also create a plain-text version
of the HTML email, very handy
if(!$mail->send()) {
throw new \Exception('I could not send the email.' . $mail->ErrorInfo);
}
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
// $responseArray = array('type' => 'danger', 'message' => $errorMessage);
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
JS
$(function () {
// init the validator
// validator files are included in the download package
// otherwise download from http://1000hz.github.io/bootstrap-validator
$('#contact-form').validator();
// when the form is submitted
$('#contact-form').on('submit', function (e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "contact-2.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and
apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-
dismissable"><button type="button" class="close" data-dismiss="alert" aria-
hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});

Getting "405 Not Allowed" after doing an Ajax post request for same domain

I would expect this to happen for CORS but I'm literally attempting something in the same domain and I'm at a loss.
I simple html form:
<form action="" method="post" class="wpcf7-form contact-form">
<div class="contact-input-fields">
<p>
<span class="wpcf7-form-control-wrap">
<label for="name">Name*</label>
<input type="text" id="name" name="name" value="" class="wpcf7-form-control" required="">
</span>
</p>
<p>
<span class="wpcf7-form-control-wrap">
<label for="email">Email*</label>
<input type="email" id="email" name="email" value="" class="wpcf7-form-control" required="">
</span>
</p>
<p>
<span class="wpcf7-form-control-wrap">
<label for="subject">Subject*</label>
<input type="text" id="subject" name="subject" value="" class="wpcf7-form-control" required="">
</span>
</p>
</div><!-- /.contact-input-fields -->
<p>
<span class="wpcf7-form-control-wrap">
<label for="message">Message*</label>
<textarea id="message" name="message" class="wpcf7-form-control" required=""></textarea>
</span>
</p>
<p class="choose-table-form">
<input type="submit" id="submit" value="Enviar" class="wpcf7-form-control wpcf7-submit" style="max-width:100%;">
</p>
</form><!-- /.contact-form -->
This is my javascript:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".success").hide();
$("#submit").click(function() {
var data = {
name: $("#name").val(),
email: $("#email").val(),
subject: $("#subject").val(),
message: $("#message").val()
};
$.ajax({
url: "forms/contactForm.php",
type: "POST",
data: data,
success: function(data){
$(".success").fadeIn(1000);
}
});
});
});
</script>
and my PHP:
<?php
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$msg = "Name: ".$name."\nEmail: ".$email."\Subject: ".$subject."\nMessage: ".$message;
//send email
mail("email#domain.com", "Message" .$email, $msg);
}
I don't see anything wrong but everytime I press "submit" and trigger the ajax call I get the "405 Not Allowed".
I've looked around at other answers here but they're mostly CORS related.
I don't see any div with success class on it, so you need to add that to your HTML, I used bootstrap so it uses alert-success
<div class="alert-success">Done!</div>
And in your jQuery code, use preventDefault(); and the full url to the php file
$(".alert-success").hide();
$("#submit").click(function(e) {
e.preventDefault();
var data = {
name: $("#name").val(),
email: $("#email").val(),
subject: $("#subject").val(),
message: $("#message").val()
};
$.ajax({
url: "http://localhost/jquery/forms/contactForm.php",
type: "POST",
data: data,
success: function(data){
$(".alert-success").fadeIn(1000);
}
});
});
Also, make sure you are testing this within a server, whether localhost using wamp or xampp or on a live server.

Ajax not working on PHP page

I am trying to understand the basics of using AJAX in conjunction with PHP in order to use php pages to provide functions, but not change my 'view' on my MVC design.
So I created this basic login page...
<!DOCTYPE html>
<head>
<title>learning Php</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script type="text/javascript">
$(document).ready(function() {
$(#"login").click(function() {
var action = $("#form1").attr("action");
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response)
{
if(response == 'success')
{
$("#form1").slideUp('slow', function() {
$("#message").html('<p class="success">You have logged in.</p>');
};
}
else
$("#message").html('<p class="error">Incorrect password or username.</p>');
}
});
return false;
});
});
</script>
</head>
<body>
<div>
<form name="form1" id="form1" method="post" action="loginForm.php">
<p>
<label for="username"> Username: </label>
<input type="text" id="username" name="username" />
</p>
<p>
<label for="password"> Password: </label>
<input type="text" id="username" name="username" />
</p>
<p>
<input type="submit" id="login" name="login" value="login" />
</p>
</form>
<div id="message"></div>
<div>
</body>
</html>
And this was my php page to "handle" to login...
<?php
$is_ajax = $_REQUEST['is_ajax'];
if(isset($is_ajax) && $is_ajax)
{
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if($username == 'demo' && $password == 'demo')
{
echo 'success';
}
}
?>
The problem I am having is that whenever I submit my login, I am redirected to "/loginForm.php" instead of staying on my current page and having the message change underneath the login form.
I tried using Firebug to help me track down what I suspected to be a javascript error, but to no avail.
Any idea on why I am being redirected or why the form is not submitting via Ajax?
One more mistake here
if(response == 'success')
{
$("#form1").slideUp('slow', function() {
}); <--- You Missed ")" here
}
a small mistake
$(#"login").click(function() {
This should be
$("#login").click(function() {
^ // # inside quotes.
Besides the typo and Rocky's good catch on the }); <--- You Missed ")" here
Both your username and password fields are the same.
<label for="username"> Username: </label>
<input type="text" id="username" name="username" />
and
<label for="password"> Password: </label>
<input type="text" id="username" name="username" />
the 2nd one should read as
<input type="text" id="password" name="password" />
In using everyone's answer, you will have yourself a working script.
Remember to hash your password once you go LIVE.
Edit sidenote: I've made a note below about using a button, rather than an input.
Here's a rewrite, just in case. However that input needs to be a <button>.
<!DOCTYPE html>
<head>
<title>learning Php</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script type="text/javascript">
$(document).ready(function() {
$("#login").click(function() {
var action = $("#form1").attr("action");
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response)
{
if(response == 'success')
{
$("#form1").slideUp('slow', function() {
$("#message").html('<p class="success">You have logged in.</p>');
});
}
else
$("#message").html('<p class="error">Incorrect password or username.</p>');
}
});
return false;
});
});
</script>
</head>
<body>
<div>
<form name="form1" id="form1" method="post" action="loginForm.php">
<p>
<label for="username"> Username: </label>
<input type="text" id="username" name="username" />
</p>
<p>
<label for="password"> Password: </label>
<input type="text" id="password" name="password" />
<!--
Your original input
<input type="text" id="username" name="username" />
-->
</p>
<button type="submit" id="login" name="login" />LOGIN</button>
<!--
Your original submit input. Don't use it
<p>
<input type="submit" id="login" name="login" value="login" />
</p>
-->
</form>
<div id="message"></div>
</div>
</body>
</html>
Your last div just before </body> was unclosed </div>, I've changed that above.
Additional edit from comments.
It seems that there was probably a space inserted somewhere and the use of trim() was the final nail to the solution.
response.trim();
A special thanks goes out to Jay Blanchard to have given us a helping hand in all this, cheers Sam!
References (TRIM):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
http://php.net/manual/en/function.trim.php

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>

Ajax Contact Form Not Sending Emails [duplicate]

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

Categories

Resources