0
I would like help to identify the problem, ultilizo a form that uses JS to validate and PHP to send, but it is not working. It works perfectly on other sites, but when you click SUBMIT (Submit) it reloads the page adding a question mark at the end of the URL and the message is not sent. Follow form codes (HTML), validation (JS), and sending (PHP).
Form:
<form name="sentMessage" id="contactForm" novalidate>
<div class="control-group form-group">
<div class="controls form-group has-feedback">
<label>Nome*</label>
<input type="text" class="form-control" id="name" required data-validation-required-message="Por favor, insira seu nome.">
<i class="fa fa-user form-control-feedback"></i>
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls form-group has-feedback">
<label>Empresa</label>
<input type="tel" class="form-control" id="empresa">
<i class="fa fa-building form-control-feedback"></i>
</div>
</div>
<div class="control-group form-group">
<div class="controls form-group has-feedback">
<label>Telefone*</label>
<input type="tel" class="form-control" id="phone" required data-validation-required-message="Por favor, insira seu número de telefone." >
<i class="fa fa-phone form-control-feedback"></i>
</div>
</div>
<div class="control-group form-group">
<div class="controls form-group has-feedback">
<label>Email*</label>
<input type="email" class="form-control" id="email" required data-validation-required-message="Por favor, insira seu email.">
<i class="fa fa-envelope form-control-feedback"></i>
</div>
</div>
<div class="control-group form-group">
<div class="controls form-group has-feedback">
<label>Mensagem</label>
<textarea rows="10" cols="100" class="form-control" id="message" maxlength="999" style="resize:none" placeholder="Relate sobre sua solicitação ou projeto."></textarea>
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<br>
<button type="submit" class="btn btn-success btn-lg">Enviar solicitação</button>
</form>
JS:
/*
Jquery Validation using jqBootstrapValidation
example is taken from jqBootstrapValidation docs
*/
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// something to have when submit produces an error ?
// Not decided if I need it yet
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var empresa = $("input#empresa").val();
var phone = $("input#phone").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "bin/contact_me.php",
type: "POST",
data: {
name: name,
empresa: empresa,
phone: phone,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Sua mensagem foi enviada. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>" + firstName + " Parece que não está funcionando...</strong> Você poderia enviar um email direto para nós? Desculpe pela inconveniência.");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
PHP:
<?php
if(empty($_POST['email']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$phone = $_POST['phone'];
$empresa = $_POST['empresa'];
$email_address = $_POST['email'];
$message = $_POST['message'];
// create email body and send it
$to = '[email protected]'; // PUT YOUR EMAIL ADDRESS HERE
$email_subject = "Solicitação de $name, $empresa."; // EDIT THE EMAIL SUBJECT LINE HERE
$email_body = "Uma solicitação foi enviada no site.\n\n"."Aqui estão os detalhes:\n\nNome: $name\n\nTelefone: $phone\n\nEmail: $email_address\n\nMensagem:\n$message";
$headers = "From: $email_address\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
Event.preventDefault(); should be at the beginning of Submit and not within the validation success.
– Rodrigo Mello
If you do not place Event.preventDefault(); in the right place the default is to submit to the same page
– Rodrigo Mello
Thanks for the answers! But where would be the right place? I always used there and it worked. The page only reloaded and appeared to the div saying that the message was sent.
– Batman
My fault, Event.preventDefault() is already present in "jqBootstrapValidation". That is, your Event.preventDefault() in submitSuccess ñ is for nothing. Do the following. Put your $.ajax(.. ) inside a confirm... "if (confirm('send? ')) { $.ajax(...) } Else { Alert('did not send') }" This will confirm after Alert whether there was a post to the same page or not, if you click Cancel in confirm nothing should happen, because jqBootstrapValidation should have already prevented Submit. If you click Yes on confirm then the ajax would be pulled (from there there has pq the page reload
– Rodrigo Mello
So I don’t know much about JS. I bought a template a while ago that came with these JS and PHP files and the form, and how much I liked the form I use on my websites attaching the JS and PHP files ready (I change only the content information needed to send by email). And on all my sites it works the way it is. That’s why I’m finding it strange that it’s not working on this one. Can it be on account of other JS files indexed in the page?
– Batman