Form with ajax: JS not executing - javascript

I've got one big problem on only 1 page of a web site: Javascript doesn't want to be executed.
I tried to copy and paste from another web site i've done where it works perfectly... but not here. Maybe you can help me to figure out why it doesn't work...
I tried many ways, no ajax seems to work here.
Here is one of them, when i try to send a mail, i got no alert but {"reponse":"Mail sent corretly!"} instead, and the mail is corretly sent.
The submit button works! The page is refreshing, so i think the js is not executed. (i'd like to have the information without refreshing the page, like a normal ajax request).
I've tried to put the script (and the link to librairies) in the head, nothing changed.
Here is my code:
<--! Some HTML -->
<form class="form-horizontal myForm" method="post" action="contact.php">
<div class="form-group col-md-6">
<input type="text" class="form-control" name="prenom" id="prenom" placeholder="First Name" pattern="[a-zA-ZÀ-ÿ._-\s]{1,30}" required>
</div>
<div class="form-group col-md-6" style="margin-left:14px">
<input type="text" class="form-control" name="nom" id="nom" placeholder="Name" pattern="[a-zA-ZÀ-ÿ._-\s]{1,30}" required>
</div>
<div class="form-group col-md-6">
<input type="email" class="form-control" name="email" id="email" placeholder="Mail" required >
</div>
<div class="form-group col-md-6" style="margin-left:14px">
<input type="text" class="form-control" name="objet" id="objet" placeholder="Object" pattern="[a-zA-ZÀ-ÿ._-\s]{1,30}" required >
</div>
<div class="form-group col-md-12">
<input type="text" class="form-control" name="message" id="message" placeholder="Your message" required>
</div>
<div class="form-group">
<label for="captcha" class="col-xs-12 col-sm-2 control-label">Captcha</label>
<div class="col-xs-6 col-sm-2">
<input type="text" class="form-control" id="captcha" name="captcha" required>
</div>
<div class="col-xs-2 col-sm-1">
<img src="form.php">
</div>
</div>
<div class="form-group col-md-12">
<button type="submit" class="btn btn-default">Submit</button>
</div>
<div class="the-return"> </div>
</form>
<--! Some HTML -->
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js"></script> <!-- Gem jQuery -->
<script>
$(document).ready(function() {
// On submit
$('.myForm').on('submit', function(e) {
e.preventDefault(); // Prevent default submit
var $this = $(this);
// Getting values
var name = $('#nom').val();
var fname = $('#prenom').val();
var objet = $('#objet').val();
var mail = $('#email').val();
var msg = $('#msg').val();
// Looking for errors
if(name === '' || fname === '' || objet === '' || mail === '' || msg === '') {
alert('Les champs doivent êtres remplis');
} else {
// Sending Ajax query
$.ajax({
url: $this.attr('action'), // form's action
type: $this.attr('method'), // form's method
data: $this.serialize(), // Serializing data
success: function(html) { // php's file response
alert(html); // Print the result
}
});
}
});
});
And my php file:
session_start();
if(isset($_GET['err']))
{
$reponse = 'Mail not sent corretly!';
echo json_encode(['reponse' => $reponse]);
echo 'An error occurred, please try again
<form .... /form>'; //Same form
}
if(isset($_POST["captcha"]) && $_POST["captcha"]!="" && $_SESSION["captcha"]==$_POST["captcha"])
{
if(isset($_POST["nom"]))
{
if(preg_match("/^[a-zA-Z][a-zA-Z]*[a-zA-Z]$/",$_POST['nom']))
{
if(isset($_POST["prenom"]))
{
if (preg_match("/^[a-zA-Z][a-zA-Z]*[a-zA-Z]$/",$_POST['prenom']))
{
if(isset($_POST["objet"]))
{
if (preg_match("/^[a-zA-Z][a-zA-Z]*[a-zA-Z]$/",$_POST['objet']))
{
if(isset($_POST["email"]))
{
if (preg_match("/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/",$_POST['email']))
{
$passage_ligne = "\r\n";
$emailAdmin = 'benjamin#parisbeaute.fr';
// Subject
$subject = $_POST['objet'];
// Headers
$headers = 'FROM: "'.$_POST['nom'].' '.$_POST['prenom'].'" <'.$_POST['email'].'>'.$passage_ligne;
$headers .= 'MIME-Version: 1.0'.$passage_ligne;
$headers .= 'Content-type: text/html; charset=UTF-8'.$passage_ligne;
$message = $_POST['message'];
// Formulaire
// Fonction mail()
mail($emailAdmin, $subject, $message, $headers);
echo '<div>Thanks a lot !</div>';
$reponse = 'Mail sent corretly!';
echo json_encode(['reponse' => $reponse]);
}}}}}}}}}
?>
Thanks in advance, sorry for my poor English, it's not my native language as you can see in my code.

Not sure why it did't work, but If you want sending the data using the $.ajax request, then stick to click event. Try change the code into this :
$(document).ready(function() {
// On button click
$('#my_button').on('click', function(e) {
var $this = $('.myForm');
// Getting values
var name = $('#nom').val();
var fname = $('#prenom').val();
var objet = $('#objet').val();
var mail = $('#email').val();
var msg = $('#msg').val();
// Looking for errors
if(name === '' || fname === '' || objet === '' || mail === '' || msg === '') {
alert('Les champs doivent êtres remplis');
} else {
// Sending Ajax query
$.ajax({
url: $this.attr('action'), // form's action
type: $this.attr('method'), // form's method
data: $this.serialize(), // Serializing data
success: function(html) { // php's file response
alert(html); // Print the result
}
});
}
});
});
And change button type into :
<button type="button" class="btn btn-default" id="my_button">Submit</button>

Related

call php file from javascript / Google recaptcha

Many apologies if the answer to my question is obvious.
I am trying to incorporate the Google reCaptcha into my website.
This is the javascript in the HEAD of my page:
var onSubmit = function(token) {
$.ajax({
type: 'POST',
url: 'assets/php/contact.php',
success: function(){
alert('Thank you for your request ' + document.getElementById('name').value);
}
});
};
The reCaptcha is visible and working.
The above code gives me the result of 'success:' BUT is not processing the form using the call to the php file.
All other scripts on the page are working fine.
Here is the contact.php code:
I've made those changes to my code. No change in the result however. Here is the code for the php file:
<?php
//contact form submission code
//Validate data on the form
// define variables and set to empty values
$name = $email = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = contact_input($_POST["name"]);
$email = contact_input($_POST["email"]);
$message = contact_input($_POST["message"]);
}
function contact_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// if the url field is empty
if(isset($_POST['url']) && $_POST['url'] == ''){
// put your email address here
$youremail = 'my#email.co.uk';
// prepare a "pretty" version of the message
// Important: if you added any form fields to the HTML, you will need to add them here also
$body = "Contact Form from Wilderness Canoe website just submitted:
Name: $_POST[name]
E-Mail: $_POST[email]
Message: $_POST[message]";
// Use the submitters email if they supplied one
// (and it isn't trying to hack your form).
// Otherwise send from your email address.
if( $_POST['email'] && !preg_match( "/.+#.+\..+/i", $_POST['email']) ) {
$headers = "From: $_POST[email]";
} else {
$headers = "From: $youremail";
}
// finally, send the message
mail($youremail, 'Contact Form', $body, $headers );
}
?>
and the code for the form:
<form id="form" method="post" action="assets/php/contact.php" onsubmit="return validate();">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<i class="zmdi zmdi-account mdc-text-light-blue zmdi-hc-2x txtfields"></i>
<label class="mdl-textfield__label" for="name"> Full Name</label>
<input class="mdl-textfield__input " type="text" id="name" required name="name">
<!--error msg ><span class="mdl-textfield__error">Only alphabet and no spaces, please!</span-->
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<i class="zmdi zmdi-email mdc-text-light-blue zmdi-hc-2x txtfields"></i>
<label class="mdl-textfield__label" for="email">Your Email</label>
<input class="mdl-textfield__input " type="text" id="email" required name="email">
<!--error msg ><span class="mdl-textfield__error">Valid email only, please!</span-->
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<i class="zmdi zmdi-comment-text mdc-text-light-blue zmdi-hc-2x txtfields"></i>
<label class="mdl-textfield__label" for="message">Your Message/Comment</label>
<textarea class="mdl-textfield__input " type="text" rows= "1" max-rows="4" id="message" name="message"></textarea>
</div>
<!-- antispam --><p class="antispam">Leave this empty: <input type="text" name="url" /></p>
<!-- RECAPTCHA -->
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
<div class="clear"><button type="submit" value="Send" name="submit" id="mc-embedded-contact" class="send">Submit</button></div>
</form>
The complete javascript:
<script type="text/javascript">
var onSubmit = function(token) {
var formData = $("#form").serialize();
$.ajax({
type: 'POST',
data: formData,
url: 'assets/php/contact.php',
success: function(){
alert('Thank you for your request ' + document.getElementById('name').value);
}
});
};
var onloadCallback = function() {
grecaptcha.render('mc-embedded-contact', {
'sitekey' : '6Ldbfg8UAAAAAAaWVBiyo4uGfDqtfcnu33SpOj6P',
'callback' : onSubmit
});
};
</script>
Your ajax request doesnt send any form data in your code. You should add your form data like this:
var onSubmit = function(token) {
var formData = $("#yourFormId").serialize();
$.ajax({
type: 'POST',
data: formData,
url: 'assets/php/contact.php',
success: function(){
alert('Thank you for your request ' + document.getElementById('name').value);
}
});
};

Ajax submit Form serialized data in php are null

I ve been searching all relative questions here and still cant figure out the problem I have.
I am using a simple modal form :
<p id="messages">Let's make today a great day!</p>
<form id="myloginform" name="myloginform" action="scripts/login.php" method="post" >
<div class="form-group">
<label for="username" class="">Enter username</label>
<input type="text" class="form-control input-lg c-square" id="username" name="username" placeholder="Username" required> </div>
<div class="form-group">
<label for="password" class="">Enter pass</label>
<input type="password" class="form-control input-lg c-square" id="password" name="password" placeholder="Password" required> </div>
<div class="form-group">
<div class="c-checkbox">
<input type="checkbox" id="login-rememberme" class="c-check">
<label for="login-rememberme" class="c-font-thin c-font-17">
<span></span>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn c-theme-btn btn-md c-btn-uppercase c-btn-bold c-btn-square c-btn-login" id="check">login</button>
</div>
</form>
I am using ajax to pass the form to a php file :
<script>
$(document).ready(function(){
$('form#myloginform').submit(function(e) {
var my_data = $('form#myloginform').serialize();
$.ajax({
type : 'POST',
url : 'scripts/login.php',
cache : false,
data : my_data,
contentType : false,
processData : false,
dataType: 'json',
success: function(response) {
//TARGET THE MESSAGES DIV IN THE MODAL
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
e.preventDefault();
});
});
</script>
The login.php file is very simple and returns an json $output response
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "Test"){
$success = true;
}
if($success == true) {
$output = json_encode(array('type'=>'success', 'message' => $username));
} else {
$output = json_encode(array('type'=>'error', 'message' => $username));
}
die($output);
?>
The $output in every case returns null. I checked with firebug, and everything is OK , no errors, POST perfect still I cannot get the variables in php to work. Any ideas ??? Is something wrong with my approach or do I need to deserialize the data in the php file , somehow...???
Don't use die.
Use echo or print.
Also set contentType to true.

Image not send using javascript when submit form no refresh page

I have a javascript using send text and photo, my problem is photo not send in my directory folder and empty column photo in database.
How to fix this? I'm confused :(
This is my screenshot result
index.php
<script>
$(function () {
$('#fr_testi').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'testi.php',
data: $('#fr_testi').serialize(),
success: function () {
document.getElementById("sc_testi").innerHTML = "Succes :)";
$('#nama_testi').val("");
$('#status_testi').val("");
$('#foto_testi').val("");
$('#komentar_testi').val("");
}
});
});
});
</script>
<form method="POST" id="fr_testi" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label">Nama</label>
<div class="controls">
<input name="nama" id="nama_testi" maxlength="100" type="text" required>
<input type="hidden" value="<?php echo $sk->kode?>" name="kode">
</div>
</div>
<div class="control-group">
<label class="control-label">Status</label>
<div class="controls">
<input id="status_testi" name="status" maxlength="100" type="text" required>
</div>
</div>
<div class="control-group">
<label class="control-label">Foto</label>
<div class="controls">
<input name="foto" id="foto_testi" type="file" required>
</div>
</div>
<div class="control-group type2">
<label class="control-label">Komentar</label>
<div class="controls">
<textarea maxlength="250" id="komentar_testi" name="komentar" required></textarea>
</div>
</div>
<center>
<button type="submit" class="button button_type_2 button_grey_light">Send</button><br/><br/>
<font color="green" id="sc_testi"></font>
</center>
</form>
testi.php
<?php
include "element/koneksi.php";
$nama = $_POST['nama'];
$kode = $_POST['kode'];
if ($nama!=NULL or $kode!=NULL) {
date_default_timezone_set("Asia/Jakarta");
$tglnya = date("Y-m-d");
$status = $_POST['status'];
$komentar = $_POST['komentar'];
$warna = "#52B3D9";
$kon = "NO";
$namafile_tmp = $_FILES['foto']['tmp_name'];
if($namafile_tmp){
$namafile = $_FILES['foto']['name'];
$file = $kode."_".$tglnya."_".$namafile;
copy($namafile_tmp, "images/sekolah/testimoni/{$file}");
unlink($namafile_tmp);
}
$query= "INSERT INTO sekolah_testimoni VALUES(id_testi,'$kode','$nama','$komentar','$status','$file','$warna',now(),'$kon','$kon')";
mysql_query($query);
}
else
{
echo "<script language='JavaScript'>window.history.back() </script>";
}
?>
The jquery method serialize doesn't include input file type.
If you just want to register filename on DB, you can use JS like below instead of serialize.
sendData = "";
$.each($("#formulario input, #formulario select"), function () {
if ($(this).prop("type") == "submit") return;
sendData += sendData!=""?"&":"";
sendData += $(this).prop("name") + "=" + $(this).val()
});
But if you want to upload file, save on the server and then register the location on DB, you should post directly from HTML or use FormData javascript object to perform this task.
fileInputElement = document.getElementById("yourFileInputID");
var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);
// if you need to upload multiple files you should loop through the fileInputElement.files array, appending one by one
var request = new XMLHttpRequest();
request.open("POST", "http://yourURL/");
request.send(formData);
Unfortunately this method doesn't work on old browsers. To get upload working on those you should use an iframe solution (post form to an invisible iframe without leaving the page).

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>

Trying to implement a form with php/ajax without success

I'm trying to implement a form based on a tutorial found on the internet. Unfortunately I can't get it working. When I click on "Send" the page reloads and that's it.
Any idea what the issue is? Many thanks
HTML:
<div class="block-right"> <h1>Formulaire de contact</h1>
<!-- CONTACT FORM-->
<div class="contact-form">
<form id="contact" method="post" class="clearfix">
<div class="clearfix">
<input id="name" name="name" placeholder="Name" type="text" value="">
<input id="email" name="email" placeholder="Email" type="email" value="">
</div>
<textarea id="message" name="message" placeholder="Message"></textarea>
<input type="submit" value="Envoyer" name="submit">
<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>
</form>
</div><!-- /.contact-form -->
</div> <!-- End DIV block-right -->
JS:
// Contact Form
$(document).ready(function(){
$("#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;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email) && (message.length > 100) && (name.length > 1)){
$.ajax({
type: "POST",
url: "../sendmessage.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000);
}
});
} else{
$('.error').fadeIn(1000);
}
return false;
});
});
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( "xyz#gmail.com", "Contact Form: ".$_POST['name'], $_POST['message'], "From:" . $_POST['email'] );
}
?>
Remember to wrap your code inside $(document).ready
$(document).ready(function(){
$("#contact").submit(function(e){
e.preventDefault();
//Your code.
return false;
});
});
Or use delegated event:
$(document).on("submit","#contact",function(e){
e.preventDefault();
//Your code.
return false;
});
Update:
If you use .noConflict(); to relinquish control of $. You could try:
jQuery(document).ready(function(){
jQuery("#contact").submit(function(e){
e.preventDefault();
//Your code.
return false;
});
});

Categories

Resources