Trying to implement a form with php/ajax without success - javascript

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;
});
});

Related

Php Ajax Form is not submitting

Hey guys I am creating a newsletter sign-up form and trying to submit it with AJAX..
Here is my form:
<div id="form-content">
<form method="POST" id="news-form" name="newsletter">
<div class="bd-input-2 form-group">
<input type="email" name="newsletter_email" placeholder="Enter your email address" required />
</div>
<div class="form-group">
<button type="submit" name="newsletter">Submit</button>
</div>
</form>
</div>
And this one is my JS file in same page as form:
$('#news-form').submit(function(e){
e.preventDefault();
$.ajax({
url: 'newsletter-submit.php',
type: 'POST',
data: $(this).serialize()
})
.done(function(data){
$('#form-content').fadeOut('slow', function(){
$('#form-content').fadeIn('slow').html(data);
console.log(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
On console nothing is displaying not even an error just an empty line.
And my newsletter-submit.php file :
<?php
if(isset($_POST['newsletter'])){
$newsletter_email = filter_var($_POST['newsletter_email'],FILTER_VALIDATE_EMAIL);
if(filter_var($newsletter_email, FILTER_VALIDATE_EMAIL)){
$newsletter_email = filter_var($newsletter_email, FILTER_VALIDATE_EMAIL);
$em_check = sqlsrv_query($con, "SELECT email FROM newsletter_signups WHERE email='$newsletter_email'",array(), array("Scrollable"=>"buffered"));
$num_rows = sqlsrv_num_rows($em_check);
if($num_rows > 0){
echo "<br/><p style='color: #fff;'>Email exist in our newsletter list.</p>";
}else{
$query = "INSERT INTO newsletter_signups (email) VALUES ('{$newsletter_email}')";
$insert_newsletter_query = sqlsrv_query($con,$query);
echo '<br/><p style="color: green;">Thank you for sign up in our newsletter</p>';
}
}
}
?>
But if I add any code after php tags e.g Hello world that is displayed after the submission.
My php code was working before AJAX file
Your input field is named newsletter_email and in your php you are checking for isset($_POST['newsletter']) which is always false.

Ajax submitting form without refreshing page [duplicate]

This question already has answers here:
jQuery AJAX submit form
(20 answers)
Closed last year.
Can anyone tell me why this bit of code isn't working?
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').bind('submit', function () {
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
return false;
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="button" value="Submit">
</form>
</body>
</html>
When I push submit nothing happens. In the receiving php file I'm using $_POST['time'] and $_POST['date'] to put the data in a mysql query but it's just not getting the data. Any suggestions? I'm assuming it's something to do with the submit button but I can't figure it out
The form is submitting after the ajax request.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').bind('click', function (event) {
// using this page stop being refreshing
event.preventDefault();
$.ajax({
type: 'POST',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
PHP
<?php
if(isset($_POST["date"]) || isset($_POST["time"])) {
$time="";
$date="";
if(isset($_POST['time'])){$time=$_POST['time']}
if(isset($_POST['date'])){$date=$_POST['date']}
echo $time."<br>";
echo $date;
}
?>
JS Code
$("#submit").click(function() {
//get input field values
var name = $('#name').val();
var email = $('#email').val();
var message = $('#comment').val();
var flag = true;
/********validate all our form fields***********/
/* Name field validation */
if(name==""){
$('#name').css('border-color','red');
flag = false;
}
/* email field validation */
if(email==""){
$('#email').css('border-color','red');
flag = false;
}
/* message field validation */
if(message=="") {
$('#comment').css('border-color','red');
flag = false;
}
/********Validation end here ****/
/* If all are ok then we send ajax request to email_send.php *******/
if(flag)
{
$.ajax({
type: 'post',
url: "email_send.php",
dataType: 'json',
data: 'username='+name+'&useremail='+email+'&message='+message,
beforeSend: function() {
$('#submit').attr('disabled', true);
$('#submit').after('<span class="wait"> <img src="image/loading.gif" alt="" /></span>');
},
complete: function() {
$('#submit').attr('disabled', false);
$('.wait').remove();
},
success: function(data)
{
if(data.type == 'error')
{
output = '<div class="error">'+data.text+'</div>';
}else{
output = '<div class="success">'+data.text+'</div>';
$('input[type=text]').val('');
$('#contactform textarea').val('');
}
$("#result").hide().html(output).slideDown();
}
});
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contactform input, #contactform textarea").keyup(function() {
$("#contactform input, #contactform textarea").css('border-color','');
$("#result").slideUp();
});
HTML Form
<div class="cover">
<div id="result"></div>
<div id="contactform">
<p class="contact"><label for="name">Name</label></p>
<input id="name" name="name" placeholder="Yourname" type="text">
<p class="contact"><label for="email">Email</label></p>
<input id="email" name="email" placeholder="admin#admin.com" type="text">
<p class="contact"><label for="comment">Your Message</label></p>
<textarea name="comment" id="comment" tabindex="4"></textarea> <br>
<input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
</div>
PHP Code
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//check if its an ajax request, exit if not
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type' => 'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if (!isset($_POST["username"]) || !isset($_POST["useremail"]) || !isset($_POST["message"])) {
$output = json_encode(array('type' => 'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$username = filter_var(trim($_POST["username"]), FILTER_SANITIZE_STRING);
$useremail = filter_var(trim($_POST["useremail"]), FILTER_SANITIZE_EMAIL);
$message = filter_var(trim($_POST["message"]), FILTER_SANITIZE_STRING);
//additional php validation
if (strlen($username) < 4) { // If length is less than 4 it will throw an HTTP error.
$output = json_encode(array('type' => 'error', 'text' => 'Name is too short!'));
die($output);
}
if (!filter_var($useremail, FILTER_VALIDATE_EMAIL)) { //email validation
$output = json_encode(array('type' => 'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if (strlen($message) < 5) { //check emtpy message
$output = json_encode(array('type' => 'error', 'text' => 'Too short message!'));
die($output);
}
$to = "info#wearecoders.net"; //Replace with recipient email address
//proceed with PHP email.
$headers = 'From: ' . $useremail . '' . "\r\n" .
'Reply-To: ' . $useremail . '' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$sentMail = #mail($to, $subject, $message . ' -' . $username, $headers);
//$sentMail = true;
if (!$sentMail) {
$output = json_encode(array('type' => 'error', 'text' => 'Could not send mail! Please contact administrator.'));
die($output);
} else {
$output = json_encode(array('type' => 'message', 'text' => 'Hi ' . $username . ' Thank you for your email'));
die($output);
}
This page has a simpler example
http://wearecoders.net/submit-form-without-page-refresh-with-php-and-ajax/
Here is a nice plugin for jQuery that submits forms via ajax:
http://malsup.com/jquery/form/
its as simple as:
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
alert('form was submitted');
});
});
</script>
It uses the forms action for the post location.
Not that you can't achieve this with your own code but this plugin has worked very nicely for me!
JS Code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var time = $("#time").val();
var date = $("#date").val();
var dataString = 'time='+ time + '&date=' + date;
if(time=='' || date=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
HTML Form
<form>
<input id="time" value="00:00:00.00"><br>
<input id="date" value="0000-00-00"><br>
<input name="submit" type="button" value="Submit">
</form>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
</div>
PHP Code
<?php
if($_POST)
{
$date=$_POST['date'];
$time=$_POST['time'];
mysql_query("SQL insert statement.......");
}else { }
?>
Taken From Here
type="button"
should be
type="submit"
In event handling, pass the object of event to the function and then add statement i.e.
event.preventDefault();
This will pass data to webpage without refreshing it.
$(document).ready(function(){
$('#userForm').on('submit', function(e){
e.preventDefault();
//I had an issue that the forms were submitted in geometrical progression after the next submit.
// This solved the problem.
e.stopImmediatePropagation();
// show that something is loading
$('#response').html("<b>Loading data...</b>");
// Call ajax for pass data to other place
$.ajax({
type: 'POST',
url: 'somephpfile.php',
data: $(this).serialize() // getting filed value in serialize form
})
.done(function(data){ // if getting done then call.
// show the response
$('#response').html(data);
})
.fail(function() { // if fail then getting message
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-6 col-xs-12"></div>enter code here
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="msg"></div>
<form method="post" class="frm" id="form1" onsubmit="">
<div class="form-group">
<input type="text" class="form-control" name="fname" id="fname" placeholder="enter your first neme" required>
<!--><span class="sp"><?php// echo $f_err;?></span><!-->
</div>
<div class="form-group">
<input type="text" class="form-control" name="lname" id="lname" placeholder="enter your last neme" required>
<!--><span class="sp"><?php// echo $l_err;?></span><!-->
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" id="email" placeholder="enter your email Address" required>
<!--><span class="sp"><?php// echo $e_err;?></span><!-->
</div>
<div class="form-group">
<input type="number" class="form-control" name="mno" id="mno" placeholder="enter your mobile number" required>
<!--><span class="sp"><?php //echo $m_err;?></span><!-->
</div>
<div class="form-group">
<input type="password" class="form-control" name="pass" id="pass" pattern="(?=.*[a-z])(?=.*[A-Z]).{4,8}" placeholder="enter your Password" required>
<!--><span class="sp"><?php //echo $p_err;?></span><!-->
</div>
<div class="radio">
<input type="radio" value="male" name="gender" id="gender" checked>male<br>
<input type="radio" value="female" name="gender" id="gender">female<br>
<input type="radio" value="other" name="gender" id="gender">other<br>
<!--><span class="sp"> <?php //echo $r_err;?></span><!-->
</div>
<div class="checkbox">
<input type="checkbox" name="check" id="check" checked>I Agree Turms&Condition<br>
<!--><span class="sp"> <?php //echo $c_err;?></span><!-->
</div>
<input type="submit" class="btn btn-warning" name="submit" id="submit">
</form>enter code here
</div>
<div class="col-md-3 col-sm-6 col-xs-12"></div>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" >
$(function () {
$(".submit").click(function (event) {
var time = $("#time").val();
var date = $("#date").val();
var dataString = 'time=' + time + '&date=' + date;
console.log(dataString);
if (time == '' || date == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else
{
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function (data) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
$("#data").html(data);
}
});
}
event.preventDefault();
});
});
</script>
<form action="post.php" method="POST">
<input id="time" value=""><br>
<input id="date" value=""><br>
<input name="submit" type="button" value="Submit" class="submit">
</form>
<div id="data"></div>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
<?php
print_r($_POST);
if ($_POST['date']) {
$date = $_POST['date'];
$time = $_POST['time'];
echo '<h1>' . $date . '---' . $time . '</h1>';
}
else {
}
?>

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 contact form does not send email

All day i trying to solve the problem but without success.
The form does not send a message and not written an error.
form.html
<div class="ok" id="ok"></div>
<div id="data">
<div id="alert" class="alert_ig"></div>
<form id="form" class=" clearfix" method="POST" action="">
<div class="col-sm-12">
<div class="form-group">
<input name="name" type="text" id="name" value="{$smarty.cookies.nameuser}" class="form-control" placeholder="Name"/>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input name="email" type="email" id="email" value="{$smarty.cookies.emailuser}" class="form-control" placeholder="E-mail"/>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<textarea id="message" class="form-control" rows="5" name="text" placeholder="Message"></textarea>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<button style="margin-top:10px" id="submit" type="submit" class="bot_g">Send</button>
</div>
</div>
</form>
<script>
$(document).ready(function() {
$('#submit').click(function(e){
var form = $(this);
var error = false;
if (!error) {
var data = form.serialize();
$.ajax({
type: 'POST',
url: '{$home}/system/modules/contacts/send.php',
dataType: 'json',
data: data,
success: function(data){
if (data.error.length > 0) {
$('#alert').html(""+data['error']+"");
$('#email').addClass("fill");
} else {
$('#ok').html('send.');
$( "#data" ).css( "display","none" );
}
},
return false;
)};
});
</script>
</div>
send.php
<?php
require_once '../../inc/core.php';
$name=Text(trim($_POST['name']));
$email=Text(trim($_POST['email']));
$subject=Text(trim($_POST['subject']));
$text=Text(trim($_POST['text']));
if(empty($name)){
$json['error'] = 'Come on, you have a name don\'t you?';
echo json_encode($json);
exit;
}
if (mb_strlen($name) < 2 || mb_strlen($name) > 250){
$json['error'] = 'Your name must consist of at least 2 characters!';
echo json_encode($json);
exit;
}
if(empty($email)){
$json['error'] = 'No Email, No Message!';
echo json_encode($json);
exit;
}
if (mb_strlen($email) < 5 || mb_strlen($email) > 64){
$json['error'] = 'Your email must consist of at least 5 characters!';
echo json_encode($json);
exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$json['error'] = 'Unknown characters in your e-mail!';
echo json_encode($json);
exit;
}
if(empty($subject)){
$json['error'] = 'Um...yea, you have to write something to send this form.';
echo json_encode($json);
exit;
}
if (mb_strlen($subject) < 5 || mb_strlen($subject) > 250){
$json['error'] = 'Your subject must consist of at least 5 characters!';
echo json_encode($json);
exit;
}
if (mb_strlen($text) < 2 || mb_strlen($text) > 10000){
$json['error'] = 'Thats All? Really?';
echo json_encode($json);
exit;
}
$mailer = new phpmailer();
$mailer->ContentType = "text/html";
$mailer->From = $email;
$mailer->Subject = 'New message from '.$home;
$mailer->Body ="Subject: ".$subject."<br/>
Name: ".$name."<br/>
E-mail: ".$email."<br/>
".nl2br($text);
$mailer->AddAddress($setup['emailadmin'], '');
$mailer->Send();
$json['error'] = 0;
echo json_encode($json);
?>
When is my problem with this code?
I must use this send.php format, but may to change ajax and html form to working...
thanks
var form = $(this);
In this line $(this); refers to the submit button so var form, stores your submit button instead of the form element itself.
You may not see an error on the client-side, but if you try to debug the data sent to your server-side you will see something is wrong.
Try replacing $(this) with the selector that matches your form element.
Also, if you want to inform your users when the server returns an error like a 500 error for example, you can add an error callback to your $ajax function, along with the success callback you already have.
Have a look here http://api.jquery.com/jquery.ajax/ for the documentation.
Also add e.preventDefault() at the end of your event handler, to prevent the default action of submitting the form if you want to do an ajax submit.

Form with ajax: JS not executing

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>

Categories

Resources