Submitting html form and send it via email (PHP, AJAX, HTML) - javascript

I'm a beginner developper
i'm trying to create a form that the customers will fill, and send it via email and i'm stuck with two problems
1) The sucess message made with AJAX appear with the errors, when the cust click on submit button the error message appear as well as the sucess message !
2) Nothing happen after submitting the form : no email sending even after the sucess of the form!
here is the codage !
HTML;
function validateText(id){
if($("#"+id).val() == null || $("#"+id).val() == ""){
$(".error-messages").fadeIn();
var input = $("#"+id);
var select = $("#"+id);
input.addClass("is-invalid");
select.addClass("is-invalid");
return false;
} else {
$(".error-messages").fadeOut();
var input = $("#"+id);
var select = $("#"+id);
input.removeClass("is-invalid");
select.removeClass("is-invalid");
return true;
}
}
$(function() {
$('.text-danger').hide();
$("#submitbtn").click(function() {
// validate and process form here
validateText("nom")
validateText("prenom")
validateText("email")
validateText("tel")
validateText("cell")
validateText("adresse")
validateText("gren")
validateText("habitat")
validateText("chauffage")
validateText("climat")
validateText("sousol")
validateText("facture")
var dataString = 'nom='+ nom + '&email=' + email + '&tel=' + tel + '&cell=' + cell + '&adresse=' + adresse + '&gren=' + gren + '&habitat=' + habitat + '&chauffage=' + chauffage + '&climat=' + climat + '&sousol=' + sousol + '&tel=' + facture;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "formulaire.php",
data: dataString,
cache: false,
success: function(html) {
$(".sucess-messages").show();
}
});
return false;
});
});
<div id="formulaire" class="contact-clean" action="">
<div class="container">
<h2 class="text-center"><i class="fa fa-users"></i> Formulaire d'inscription <i class="fa fa-users"></i></h2>
<p class="text-center">Veuillez remplir le formulaire ci-dessous pour bénéficier de nos consultations gratuites<br></p>
<div class="row">
<div class="col">
<form method="post" id="formulaire">
<div class="form-group">
<label id="form" class="form">Nom</label>
<small id="errormsg" class="form-text text-danger" data-aos="fade-right">Veuillez entrer votre nom</small>
<input id="nom" class="form-control" type="text" name="nom" required="" placeholder="Veuillez entrer votre nom" maxlength="50" minlength="2">
</div>
<div class="form-group">
<label id="form" class="form">Prénom</label>
<small id="errormsg" class="form-text text-danger" data-aos="fade-right">Veuillez entrer votre prénom</small>
<input id="prenom" class="form-control" type="text" name="prenom" required="" placeholder="Veuillez entrer votre prénom" maxlength="50" minlength="2">
</div>
<div class="form-group">
<small id="errormsg" class="form-text text-danger" data-aos="fade-right">Veuillez entrer une adresse email valide.</small>
<label id="form" class="form">Email</label>
<input id="email" class="form-control" type="email" name="email" required="" placeholder="Veuillez entrer votre adresse email" inputmode="email">
</div>
<div class="form-group">
<small id="errormsg" class="form-text text-danger" data-aos="fade-right">Veuillez entrer votre num de téléphone</small>
<label id="form" class="form">Numéro de téléphone</label>
<input id="tel" class="form-control" type="text" name="tel" required="" placeholder="Veuillez entrer votre numéro de téléphone" minlength="10" inputmode="tel">
</div>
<div class="form-group">
<small id="errormsg" class="form-text text-danger" data-aos="fade-right">Veuillez entrer votre num de cellulaire<br></small>
<label id="form" class="form">Numéro de cellulaire</label>
<input id="cell" class="form-control" type="text" name="cell" required="" placeholder="Veuillez entrer votre numéro de cellulaire" minlength="10" inputmode="tel">
</div>
<div class="form-group">
<small id="errormsg" class="form-text text-danger" data-aos="fade-right">Veuillez entrer une adresse valide</small>
<label id="form" class="form">Adresse</label>
<input id="adresse" class="form-control" type="text" name="adresse" required="" placeholder="Veuillez entrer votre adresse" minlength="5" autofocus="">
</div>
<div class="form-group">
<small id="errormsg" class="form-text text-danger" data-aos="fade-right">Veuillez entrer une mesure valide</small>
<label id="form" class="form">Hauteur de grenier au milieu <br></label>
<label id="form" class="form" style="color:#a30e0e;">(en mètre)<br></label>
<input id="gren" class="form-control" type="text" name="gren" placeholder="Veuillez entrer l'hauteur sans sign de (mètres)" maxlength="5" minlength="1" autofocus="" inputmode="numeric">
</div>
<div class="form-group">
<small id="errormsg" class="form-text text-danger" data-aos="fade-right">Veuillez choisir le type d'habitation</small>
<label id="form" class="form">Type d'habitation</label>
<select id="habitat" class="form-control" name="habita">
<optgroup label="Veuillez selectionner le type de votre habitation">
<option value="1" selected="">Maison</option>
<option value="2">Appartement</option>
<option value="3">Villa</option>
</optgroup>
</select>
</div>
<div class="form-group">
<small id="errormsg" class="form-text text-danger" data-aos="fade-right">Veuillez identifier votre moyen de chauffage</small>
<label id="form" class="form">Moyen de chauffage</label>
<input id="chauffage" class="form-control" type="text" name="chauffage" placeholder="Veuillez entrer votre moyen de chauffage" minlength="5" autofocus="">
</div>
<div class="form-group">
<small id="errormsg" class="form-text text-danger" data-aos="fade-right">Veuillez identifier votre moyen de climatisation<br></small>
<label id="form" class="form">Moyen de climatisation</label>
<input id="climat" class="form-control" type="text" name="climat" placeholder="Veuillez entrer votre moyen de climatisation" minlength="5" autofocus="">
</div>
<div class="form-group">
<small id="errormsg" class="form-text text-danger" data-aos="fade-right">Veuillez choisir le type de votre sous sol<br></small>
<label id="form" class="form">Type de sous sol</label>
<select id="sousol" class="form-control" name="sousol" required="">
<optgroup label="Veuillez selectionner le type de votre habitation">
<option value="oui" selected="">Fini</option>
<option value="non">Non fini</option>
</optgroup>
</select>
</div>
<div class="form-group">
<small id="errormsg" class="form-text text-danger" data-aos="fade-right">Veuillez saisir un montant valide</small>
<label id="form" class="form">Combien vous payez votre facture énérgétique par an? <br></label>
<label id="form" class="form" style="color:#a30e0e;">(en $)</label>
<input id="facture" class="form-control" type="text" name="facture" placeholder="Veuillez saisir le montant sans marque de monnaie" minlength="2" autofocus="" inputmode="numeric">
</div>
<div class="form-group">
<textarea id="observations" class="form-control" rows="14" name="observations" placeholder="Autres observations"></textarea>
</div>
<div class="form-group">
<button id="submitbtn" class="btn btn-primary" type="button">Envoyer</button>
</div>
<div class="form-group danger" id="formdanger" >
<div class="error-messages" role="alert"><span><strong>ERRUR: </strong>Veuillez vérifier les informations en <strong>rouge</strong><br></span></div>
</div>
<div class="form-group" id="formsucess">
<div id="sucess-messages" class="sucess-messages" role="alert"><span><strong>Vôtre demande a été transmite, MERCI</strong><br></span></div>
</div>
</form>
<?php
$nom = $_POST['nom'];
$prénom = $_POST['prenom'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$cell = $_POST['cell'];
$adresse = $_POST['adresse'];
$gren = $_POST['gren'];
$habitat = $_POST['habitat'];
$chauffage = $_POST['chauffage'];
$climat = $_POST['climat'];
$sousol = $_POST['sousol'];
$facture = $_POST['facture'];
$observations = $_POST['observations'];
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers = "From: contact#oyacg.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email";
$email_subject = "Nouvelle Inscription OYA Formulaire";
$email_from = "$email";
$email_body = "Vous avez reçu une nouvelle inscriptio OYAFormulaire.\n".
"Nom:\n $nom".
"prénom:\n $prenom".
"email:\n $email".
$to = "haymacproduction#gmail.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";
mail($to,$email_subject,$email_body,$headers);
echo "THANK TOU PEACEFUKKT";
?>

The JavaScript variables to be sent via Ajax are all undefined.
In your Ajax call, serialize the form and send
Also you have an id duplicate issue. Both form and div are using the same id. Change form tag to something else. formID.
Change this
<form method="post" id="formulaire">
To
<form method="post" id="formID">
Also
Change
data: dataString
To
data : $('#formID').serialize(),

Related

validations with "setCustomValidity" incompatible with alerts

Im working with forms so need to customize validations with "setCustomValidity" function, the problem comes when i work with alerts and validations in the same.
The button that i use to send my data form got type="submit" when i use that kind my form is making validations correctly but that type makes a refresh so the alert never shows up.
If i switch the type to type="button" then makes the opposite. Validations are not working and alerts finally shows up.
Here is some of the form´s side code:
<div class="modal-dialog">
<div class="modal-content">
<div class="col-12 user-img">
<img src="../../images/nuevoConcesionario.png" alt="">
</div>
<span id="switching1" class="d-none">
<center>
<div class="alert alert-danger" role="alert" id="mensajeError" value="AA">
</div>
</center>
</span>
<form class="formu">
<div class="row">
<div class="form-group col-md-6">
<label for="nombre" class="col-form-label">Nombre Concesionario(*)</label>
<input type="text" class="form-control" id="nomConcesionario" placeholder="Nombre Concesionario" required>
</div>
<div class="form-group col-md-6">
<label for="Nif" class="col-form-label">NIF(*)</label>
<input type="text" class="form-control" id="nifConcesionario" placeholder="Ejemplo NIF: A58818501" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6" >
<label for="ciudad" class="col-form-label">Ciudad(*)</label>
<input type="text" class="form-control" id="nomCiudad" placeholder="Ciudad" required>
</div>
<div class="form-group col-md-6">
<label for="cp" class="col-form-label">Codigo Postal</label>
<input type="text" id="cpConcesionario" placeholder="Codigo Postal" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6" >
<label for="ciudad" class="col-form-label">Telefono Contacto</label>
<input type="tel" class="form-control" id="tlf" placeholder="Telefono Contacto">
</div>
<div class="form-group col-md-6">
<label for="nom_admin" class="col-form-label">Nombre Administrador(*)</label>
<input type="text" id="nomAdministrador" placeholder="Nombre Administrador" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="email" class="col-form-label">Email(*)</label>
<input type="email" id="emailConcesionario" placeholder="email" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="nom_admin" class="col-form-label">Dirección(*)</label>
<input type="text" id="direccion" placeholder="direccion" class="form-control" required>
</div>
</div>
<div class="row">
<div style="width: 100%; margin: 0 25% 0 25%">
<button type="button" id="bEnviar" class="btn btn-primary" onclick="altaConcesionario();">Dar de alta concesionario</button>
</div>
</div>
</form>
Here is altaConcesionario validation´s function:
function altaConcesionario() {
var nomConcesionario = document.getElementById('nomConcesionario');
var nifConcesionario = document.getElementById('nifConcesionario');
var nomCiudad = document.getElementById('nomCiudad');
var nomAdministrador = document.getElementById('nomAdministrador');
var cpConcesionario = document.getElementById('cpConcesionario');
var telefono = document.getElementById('tlf');
var direccion = document.getElementById('direccion');
var emailConcesionario = document.getElementById('emailConcesionario');
// TODO unificar este mismo patron
var nomConcesionarioPatt = /[A-Za-z0-9]{4,60}/;
var nomCiudadPatt = /[A-Za-z0-9]{4,60}/;
var nomAdminPatt = /[A-Za-z0-9]{4,60}/;
var addrPatt = /[A-Za-z0-9]{4,60}/;
var emailConcesionarioPatt = /^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
var elNif = checkNif(nifConcesionario.value);
var validate = true;
// Nombre concesionario
if (nomConcesionario.value) {
nomConcesionario.setCustomValidity("");
if (!nomConcesionarioPatt.test(nomConcesionario.value)) {
mostrarAlertaValidacion("Error en el ingreso. min[4] caracteres");
nomConcesionario.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
nomConcesionario.setCustomValidity("Por favor, rellene campo 'nombre concesionario'");
mostrarAlertaValidacion("Por favor, rellene campo 'nombre concesionario'");
validate = false;
}
// Nif concesionario
if (nifConcesionario.value) {
nifConcesionario.setCustomValidity("");
if (!elNif) {
nifConcesionario
.setCustomValidity("El nif introducido no es correcto");
validate = false;
}
} else {
nifConcesionario
.setCustomValidity("Por favor, rellene campo 'NIF concesionario'");
validate = false;
}
// Nombre ciudad
if (nomCiudad.value) {
nomCiudad.setCustomValidity("");
if (!nomCiudadPatt.test(nomCiudad.value)) {
nomCiudad
.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
nomCiudad.setCustomValidity("Por favor, rellene campo 'nombre ciudad'");
validate = false;
}
// Nombre administrador
if (nomAdministrador.value) {
nomAdministrador.setCustomValidity("");
if (!nomAdminPatt.test(nomAdministrador.value)) {
nomAdministrador
.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
nomAdministrador
.setCustomValidity("Por favor, rellene campo 'nombre administrador'");
validate = false;
}
if (direccion.value) {
direccion.setCustomValidity("");
if (!addrPatt.test(direccion.value)) {
direccion
.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
direccion.setCustomValidity("Por favor, rellene campo 'direccion'");
validate = false;
}
// Email concesionario
if (emailConcesionario.value) {
emailConcesionario.setCustomValidity("");
if (!emailConcesionarioPatt.test(emailConcesionario.value)) {
emailConcesionario
.setCustomValidity("El email introducido no es correcto. mail#dominio.com");
validate = false;
}
} else {
emailConcesionario
.setCustomValidity("Por favor, rellene campo 'email colaborador'");
validate = false;
}
// TODO falta validacion email
// TODO poner las rewdirecciones en su sitio
// Si estan todos los campos rellenos entra
if (validate) {
// POPUP
// SI TRUE
$
.ajax({
type : "POST",
url : '/proyecto/Api',
data : {
action : 'addConcesionario',
auth_token : auth_token,
usuario_sesion : usuario,
nomConcesionario : nomConcesionario.value,
nifConcesionario : nifConcesionario.value,
nomCiudad : nomCiudad.value,
nomAdministrador : nomAdministrador.value,
cpConcesionario : cpConcesionario.value,
telefono : telefono.value,
direccion : direccion.value,
email : emailConcesionario.value
},
success : function(response) {
alert("EXITO");
window.location.href = "/proyecto/administracion/administracion.jsp";
},
error : function(result) {
alert("ERROR");
window.location.href = "/proyecto/administracion/administracion.jsp";
}
});
}
so i would like to know if there is any reasonable way to make both works together as i need to give information to the final user and is really important for me both of functions.
Thanks in advance,
This happened because you need to prevent form submitting event.preventDefault(). Take a look at example below
const form = document.querySelector('#myForm');
form.addEventListener('submit', ev => {
ev.preventDefault();
//Your code here (validation, http etc)
console.log('Prevented');
})
<form id="myForm">
<div class="row">
<div class="form-group col-md-6">
<label for="nombre" class="col-form-label">Nombre Concesionario(*)</label>
<input type="text" class="form-control" id="nomConcesionario" placeholder="Nombre Concesionario" required>
</div>
<div class="form-group col-md-6">
<label for="Nif" class="col-form-label">NIF(*)</label>
<input type="text" class="form-control" id="nifConcesionario" placeholder="Ejemplo NIF: A58818501" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="ciudad" class="col-form-label">Ciudad(*)</label>
<input type="text" class="form-control" id="nomCiudad" placeholder="Ciudad" required>
</div>
<div class="form-group col-md-6">
<label for="cp" class="col-form-label">Codigo Postal</label>
<input type="text" id="cpConcesionario" placeholder="Codigo Postal" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="ciudad" class="col-form-label">Telefono Contacto</label>
<input type="tel" class="form-control" id="tlf" placeholder="Telefono Contacto">
</div>
<div class="form-group col-md-6">
<label for="nom_admin" class="col-form-label">Nombre Administrador(*)</label>
<input type="text" id="nomAdministrador" placeholder="Nombre Administrador" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="email" class="col-form-label">Email(*)</label>
<input type="email" id="emailConcesionario" placeholder="email" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="nom_admin" class="col-form-label">Dirección(*)</label>
<input type="text" id="direccion" placeholder="direccion" class="form-control" required>
</div>
</div>
<div class="row">
<div style="width: 100%; margin: 0 25% 0 25%">
<button type="submit" class="btn btn-primary">Dar de alta concesionario</button>
</div>
</div>
</form>

with this function "Uncaught TypeError: $.ajax is not a function"

I have a problem and I do not know where I can solve everything I did because the error is in this $.ajax,
because I have used this code several times before already looked and I have already reviewed and I did not get results and I went down to post here for you to help me
Thank you
$(document).ready(function () {
$("#doarBronze").click(function()
{
$("#formVIP_Modal").modal("show");
$.ajax({
type: 'GET',
url: "bronze_doar_modal.php",
dataType: 'json',
data: {},
success: function(data)
{
if(data.hasError == false)
{
$("#abrir_vips_box").html(data.html);
$("#proxima_ir_cadastro_bronze").click(function()
{
$("#abrir_vips_box").html(data.boxBronze_cadastro);
$("#TitleVips").html("Cadastro para o PainelVIP");
});
}
else{
alert("ERRO!\n"+data.msgErro);
}
},
error: function(){
alert("Ocorreu Um Erro Contate um Admistrador");
}
});
});
});
<?php
require "insane.php";
$insane = new insane();
$html = '
<div id="infoBronze">
<center><b>Termos do Servidor </b><br></center>
Vantagens Extras <br>
<small>* Eventos Exclusivos Para Vip </small><br>
<small>* Suporte Exclusivo </small><br>
<small>* Sala no TS³</small><br><br>
Informacoes <br>
<small>* Reembolso de VIP Somente Quando Servidor Fechar/Falir. </small><br>
<small>* VIP Podem Ser Pausado Apenas 1 Vez </small><br>
<small>* Maximo 2 Vip Por Conta </small><br>
<small>* VIP Valera por 31 Dias </small><br>
<small>* Nao Vendemos Kits Diferentes dos Abaixo </small><br><br>
Apos Wipe <br>
<small>* Kits VIP"s Serao Liberado as 00:00 </small> <br><br>
Ativar Vip <br>
<small>* Apos o Pagamento Aprovado Basta Entrar no Jogo e Digitar<br> /ativarvip (CODIGO DE TRANSACAO) ex <b>9C834542-8123-4419-9A75-BAD63B495EF1</b> </small><br>
<small>* Em Menos de 12 horas Sua Conta sera ativa no (Painel VIP) </small><br>
<hr>
<input type="button" value="Proximo" class="btn btn-primary btn-block" id="proxima_ir_cadastro_bronze">
</div>';
$cadbronze = '
<div class="row">
<div class="col-md-4 order-md-2 mb-4">
<h4 class="d-flex justify-content-between align-items-center mb-3">
<span class="text-muted">Carrinho</span>
<span class="badge badge-secondary badge-pill">1</span>
</h4>
<ul class="list-group mb-3">
<li class="list-group-item d-flex justify-content-between lh-condensed">
<div>
<h6 class="my-0">1x VIP Bronze</h6>
<small class="text-muted">InsaneRust 4x</small>
</div>
<span class="text-muted">R$15,00</span>
</li>
<li class="list-group-item d-flex justify-content-between">
<span>Total (BRL)</span>
<strong>R$15,00</strong>
</li>
</ul>
<form class="card p-2">
<div class="input-group">
<input type="text" class="form-control" placeholder="Codigo de Promocao">
<div class="input-group-append">
<button type="submit" class="btn btn-success">Usar</button>
</div>
</div>
</form>
</div>
<div class="col-md-8 order-md-1">
<h4 class="mb-3">Dados Para o Painel VIP</h4>
<form class="needs-validation" method="POST" action="modal/p_c_bronze.php" enctype="multipart/form-data">
<div class="row">
<div class="col-md-6 mb-3">
<label>Seu Nome</label>
<input type="text" class="form-control" name="vip_nome" placeholder="Digite seu Nome" required>
<div class="invalid-feedback"> Verifique Seu Nome </div>
</div>
<div class="col-md-6 mb-3">
<label>Seu Nick</label>
<input type="text" class="form-control" name="vip_nick" placeholder="Digite Seu Nick do Servidor" required>
<div class="invalid-feedback"> Verifique Seu Nick </div>
</div>
</div>
<div class="mb-3">
<label>Seu Email</label>
<div class="input-group">
<input type="email" class="form-control" name="vip_email" placeholder="Digite Seu E-mail" required>
<div class="invalid-feedback" style="width: 100%;"> Confira Seu Email. </div>
</div>
</div>
<div class="mb-3">
<label>Senha</label>
<input type="password" class="form-control" name="vip_senha" placeholder="Escolha uma Senha para o (PainelVIP)" required>
<div class="invalid-feedback"> Confira sua Senha </div>
</div>
<div class="mb-3">
<label>Sua Steam</label>
<input type="text" class="form-control" name="vip_steam" placeholder="Insira a Url da Sua Steam" required>
<div class="invalid-feedback"> Confira sua Steam </div>
</div>
<hr class="mb-4">
<div class="alert alert-info">
<strong>Informação</strong> <br>Esse cadastro é apenas para acesso na (AREAVIP) e Para Nos Entrar em Contato Sobre Alguma Coisa efetuada/alterada fora isso nao entraremos em contato.
</div>
<hr class="mb-4">
<h4 class="mb-3">Forma de Pagamento</h4>
<div class="d-block my-3">
<div class="custom-control custom-radio">
<input id="checkBox" type="checkbox" checked required>
<label class="custom-control-label" for="credit">PAGSEGURO</label>
</div>
<div class="custom-control custom-radio">
<input id="checkBox" type="checkbox">
<label class="custom-control-label" for="debit">PAYPAL</label>
</div>
</div>
<hr class="mb-4">
<input type="submit" value="Finalizar" class="btn btn-success btn-block">
</div>
</div>
</form>
</div>
</div>';
$insane->setSaida("corpo_inicio", $html);
$insane->setSaida("boxBronze_cadastro", $cadbronze);
$insane->fim();
?>

Send e-mail form and continue on the same page

I can send email and get normally , but would like to click the submit button , the form was sent and presented a message to the user and continue on the page normally ... Ja tried with ajax and everything and nothing.
I would like the message to appear in a div , identical to the image below.
html
<form class="well form-horizontal" action="php/contato.php" method="post" id="contact_form">
<fieldset>
<legend style="text-align: center;">Fale conosco</legend>
<!-- Nome -->
<div class="form-group">
<label class="col-md-4 control-label">Nome</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="name" placeholder="Nome Completo" class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Email-->
<div class="form-group">
<label class="col-md-4 control-label">E-Mail</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input name="email" placeholder="E-Mail" class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Telefone-->
<div class="form-group">
<label class="col-md-4 control-label">Telefones</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
<input name="telefone" placeholder="(xx)xxxxx-xxxx" class="form-control" type="text" required> </br>
<input name="celular" placeholder="Seu Whatsapp (Opcional)" class="form-control" type="text">
</div>
</div>
</div>
<!-- Assunto-->
<div class="form-group">
<label class="col-md-4 control-label">Assunto</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-comment"></i></span>
<input name="assunto" placeholder="Assunto" class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Mensagem -->
<div class="form-group">
<label class="col-md-4 control-label">Deixe-nos sua mensagem.</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea class="form-control" name="mensagem" placeholder="Dúvidas, elogios, Criticas ou Sugestões são bem vindas." required></textarea>
</div>
</div>
</div>
**<!-- I want the message to appear here -->**
<div class="alert alert-success" role="alert" id="success_message">Sucesso <i class="glyphicon glyphicon-thumbs-up"></i> Muito obrigado pelo contato, retornaremos em breve.</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-4">
<button type="submit" class="btn btn-warning">Enviar <span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</fieldset>
</form>
JavaScript
$(function () {
$('#contact_form').validator();
$('#contact_form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "php/contato.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact_form').find('.messages').html(alertBox);
$('#contact_form')[0].reset();
}
}
});
return false;
}
})
});
contato.php
<?php
// configure
$from = 'email';
$sendTo = 'email';
$subject = 'Contato do site';
$fields = array('name' => 'Nome do Cliente', 'email' => 'Email', 'telefone' => 'Telefone', 'celular' => 'Celular', 'assunto' => 'Assunto', 'mensagem' => 'Mensagem'); // array variable name => Text to appear in email
$okMessage = 'Email enviado, já já entraremos em contato';
$errorMessage = 'Ocorreu um erro no envio e ja fomos notificados sobre isso, aperte F5 e tente novamente por favor';
// let's do the sending
try
{
$emailText = "Mais um contato chegando através do site\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
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 {
echo $responseArray['message'];
}
?>
...
$('#contact_form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
...
You're not preventing the default action.
You probably want to use:
...
$('#contact_form').on('submit', function (e) {
// Prevent form submission
e.preventDefault();
if (true) { // you no longer need the if-block
...
HTML
<form class="well form-horizontal" action="" method="POST" id="contact_form">
<fieldset>
<legend style="text-align: center;">Fale conosco</legend>
<!-- Nome -->
<div class="form-group">
<label class="col-md-4 control-label">Nome</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="name" placeholder="Nome Completo" class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Email-->
<div class="form-group">
<label class="col-md-4 control-label">E-Mail</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input name="email" placeholder="E-Mail" class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Telefone-->
<div class="form-group">
<label class="col-md-4 control-label">Telefones</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
<input name="telefone" placeholder="(xx)xxxxx-xxxx" class="form-control" type="text" required> </br>
<input name="celular" placeholder="Seu Whatsapp (Opcional)" class="form-control" type="text">
</div>
</div>
</div>
<!-- Assunto-->
<div class="form-group">
<label class="col-md-4 control-label">Assunto</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-comment"></i></span>
<input name="assunto" placeholder="Assunto" class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Mensagem -->
<div class="form-group">
<label class="col-md-4 control-label">Deixe-nos sua mensagem.</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea class="form-control" name="mensagem" placeholder="Dúvidas, elogios, Criticas ou Sugestões são bem vindas." required></textarea>
</div>
</div>
</div>
<!-- I want the message to appear here -->
<div class="alert alert-success" role="alert" id="success_message">
Sucesso <i class="glyphicon glyphicon-thumbs-up"></i> Muito obrigado pelo contato, retornaremos em breve.
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-4">
<button type="submit" class="btn btn-warning">Enviar <span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</fieldset>
</form>
JAVASCRIPT
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
(function ($) {
$(document).ready(function (e) {
var contactForm = $('#contact_form');
contactForm.on('submit', function (evt) {
evt.preventDefault();
var url = "contato.php";
var objData = {
"name" : $("input[name=name]").val(),
"email" : $("input[name=email]").val(),
"telefone" : $("input[name=telefone]").val(),
"celular" : $("input[name=celular]").val(),
"assunto" : $("input[name=assunto]").val(),
"mensagem" : $("input[name=mensagem]").val()
};
$.ajax({
type: "POST",
url: url,
data: objData,
success: function (data){
if (data.type && data.message) {
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable">';
alertBox += '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>';
alertBox += messageText + '</div>';
contactForm.find('#success_message').html(alertBox);
contactForm[0].reset();
}
}
});
return false;
})
});
})(jQuery);
</script>
PHP
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
// PLEASE MAKE SURE YOU DON'T HAVE ANY WHITESPACE BEFORE THE OPENING PHP TAG (<?php)
// Por favor, certifique-se de que você não tem qualquer espaço em branco antes da tag de abertura do PHP ( <?php )
$from = 'email';
$sendTo = 'email';
$subject = 'Contato do site';
$okMessage = 'Email enviado, já já entraremos em contato';
$errorMessage = 'Ocorreu um erro no envio e ja fomos notificados sobre isso, aperte F5 e tente novamente por favor';
try {
// GET & SANITIZE THE POST DATA...
$name = isset($_POST['name']) ? htmlspecialchars(trim($_POST['name'])) : "";
$email = isset($_POST['email']) ? htmlspecialchars(trim($_POST['email'])) : "";
$telefone = isset($_POST['telefone']) ? htmlspecialchars(trim($_POST['telefone'])) : "";
$celular = isset($_POST['celular']) ? htmlspecialchars(trim($_POST['celular'])) : "";
$assunto = isset($_POST['assunto']) ? htmlspecialchars(trim($_POST['assunto'])) : "";
$mensagem = isset($_POST['mensagem']) ? htmlspecialchars(trim($_POST['mensagem'])) : "";
// BUILD UP THE MESSAGE...
$emailText = "Mais um contato chegando através do site\n=============================\n";
$emailText .= "Nome do Cliente: \n$name\n\n";
$emailText .= "Email: \n$email\n\n";
$emailText .= "Telefone: \n$telefone\n\n";
$emailText .= "Celular: \n$celular\n\n";
$emailText .= "Assunto: \n$assunto\n\n";
$emailText .= "Mensagem: \n$mensagem\n\n";
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}catch (\Exception $e){
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// SIMPLY DIE-OUT THE JSON-ENCODED RESPONSE...
die(json_encode($responseArray));
?>

The form doesn't send the element's post varibles generated by Ajax

I have the following trouble.
I have one form which some its elements are generated by ajax , beacuse I have one select with diferent options that are taken from the server, depens on the option on the select I charge with ajax some text input. The problem is when I try to send the data to the php file for procesing , the post varibles from the text input dont exist while the other no dinamically elements don't have any problem.
this is my form
<form role="form" action="scripts/agregaPeticion.php" method="POST">
<div class="form-group">
<label for="sala">Sala que se quiere pedir</label>
<br>
<select id="ComboSalas" name="Salas" width="30">
<option value="-1" selected> Elige la Sala que deeseas</option>
<?php
for ($i=0; $i < $num; $i++) {
$row = $result->fetch_assoc();
echo "<option value='".$row['idSala']."'>".$row['nombreSala']."</option>";
}
?>
</select>
</div>
<div class="form-group">
<label for="fechaI">Fecha Inicio: </label>
<input required id="datepicker" name="fechaInicio" />
<label for="fechaT">Fecha Termino: </label>
<input required id="datepicker2" name="fechaFinal"/>
</div>
<div id="hourpicker" class="form-group">
<label for="fechaInicio">Hora de inicio del evento</label>
<input required type="text" id="hora_inicio" name="horaInicio" placeholder="Ejemplo: 12:00 pm" onkeypress="valida_hora(value)">
<br><br>
<label for="fechaInicio">Hora de termino del evento</label>
<input required type="text" id="hora_inicio" name="horaTermino" placeholder="Ejemplo: 1:00 pm" onkeypress="valida_hora(value)">
</div>
<div class="form-group">
<label for="nombreEvento">Nombre del evento que se realizará:</label>
<input type="text" cols="45" required name="nombreEvento">
<label for="descripcionEvento">Breve descripcion del evento que se realizará:</label>
<textarea cols="45" rows="8" name="descripcionEvento"></textarea>
</div>
<div class="form-group">
<p>Cuáles son las opciones que ocupará en su evento?</p>
<input type="checkbox" name="clima" value="Bike">Aire Acondicionado
<br>
<input type="checkbox" name="internet" value="Car"> Acceso a internet
<br>
<input type="checkbox" name="proyector" value="Car"> Uso de proyector
</div>
<div id="ranges">
<!-- Implementacion de AJAX para los rangos automaticos-->
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block" id="enviar" onclick="enviarDatos();">SOLICITAR </button>
</form>
the input text will be insert where it say "<!-- Implementacion de AJAX para los rangos automaticos-->"
the input text are fine and works the problem is when I try to take their values from de post varible , because dont have nothing.
this is my ajax's code
//CONSTANTES
var READY_STATE_UNINITIALIZED=0;
var READY_STATE_LOADING=1;
var READY_STATE_LOAED=2;
var READY_STATE_INTERACTIVE=3;
var READY_STATE_COMPLETE=4;
//VARIABLES
var combo;
var peticionHttp;
//FUNCIONES
function inicializarAjax(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function mostrarContenido(){
if(peticionHttp.readyState==READY_STATE_COMPLETE){
if(peticionHttp.status=200){
document.getElementById("ranges").innerHTML=peticionHttp.responseText;
}else{
alert("hubo problemas con la petición");
}
}
}
function cambioSala(){
combo=document.getElementById("ComboSalas").value;
var sala=combo;
if(sala==-1){
//NO HA SELECCIONADO NINGUNA SALA
document.getElementById("ranges").innerHTML="";
}else{
var url="http://localhost/GestionDeSalas/rangos.php?q="+sala;
if(peticionHttp){
peticionHttp.open("GET",url,true);
peticionHttp.onreadystatechange=mostrarContenido;
peticionHttp.send();
}
}
}
function enviarDatos(){
var s=document.getElementsByName("sillas");
alert(s[0].value);
}
function cargarTodo(){
peticionHttp=inicializarAjax();
peticionHttp.overrideMimeType('text/xml');
document.getElementById("ComboSalas").onchange=cambioSala;
}
window.onload=cargarTodo;
and this is the file wanted by ajax
<?php
$q = intval($_GET['q']);
require "scripts/conecta.php";
mysqli_select_db($con,"ControlSalas");
$sql="SELECT numSillas,numMesas,numPersonas FROM Sala WHERE idSala = '".$q."'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
echo '<div class="form-group">';
echo '<label for="NumSillas">Numero de sillas solicitadas para el evento</label>';
echo '<input type="range" name="points" max="'.$row['numSillas'].'" min="0" onchange="updateTextInput(this.value);" value="0">';
echo '<input type="text" id="textInput" value="0" readonly disabled name="sillas">';
echo '</div>';
echo '<div class="form-group">';
echo '<label for="NumMesas">Numero de mesas solicitadas para el evento</label>';
echo '<input type="range" name="points" min="0" max="'.$row['numMesas'].'" onchange="updateTextInputM(this.value);" value="0">';
echo '<input type="text" id="textInputM" value="0" readonly disabled name="mesas">';
echo '</div>';
echo '<div class="form-group">';
echo '<label for="NumPersonas">Numero de personas aproximada que asistirán al evento</label>';
echo '<input type="range" name="points" min="0" max="'.$row['numPersonas'].'" onchange="updateTextInputP(this.value);" value="0">';
echo '<input type="text" id="textInputP" value="0" readonly disabled name="personas">';
echo '</div>';
mysqli_close($con);
?>

jquery don't submit form

Hi I'm trying to validate form with jquery before submit. The validation works fine, but never submit.
There is the form:
<form class="form-signin panel-body" role="form" action="addUser" method="post" id="register">
<h2 class="form-signin-heading">Sign Up</h2>
<div id="na" class="form-group">
<input type="text" id="name" name="name" class="form-control" placeholder="Name" required>
</div>
<div id="su" class="form-group">
<input type="text" id="surname" name="surname" class="form-control" placeholder="Surname" required>
</div>
<div id="user" class="form-group">
<input type="text" id="username" name="username" class="form-control" value="<%= request.getParameter("username1") %>" placeholder="Username" required>
</div>
<div id="mail" class="form-group">
<input type="email" id="email" name="email" class="form-control warning" value="<%= request.getParameter("email1") %>" placeholder="Email address" required>
</div>
<div id="pa" class="form-group">
<input type="password" id="password" name="password" class="form-control" value="<%= request.getParameter("password1") %>" placeholder="Password" required>
</div>
<select class="form-control" id="year" name="year">
<option value="">Year</option>
</select>
<select class="form-control" id="month" name="month">
<option value="">Month</option>
</select>
<select class="form-control" id="day" name="day">
<option value="">Day</option>
</select>
<div class="row">
<span> </span>
</div>
<label>
<select class="form-control" id="sex" name="sex">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</label>
<label>
By clicking Sign up, you are agree to our<a data-toggle="modal" href="#terms"> Terms and
Conditions</a> and have read our usage policy data, including ouruse of
<a data-toggle="modal" href="#cookies">cookies</a>.
</label>
<button id="send" class="btn btn-lg btn-primary btn-block" >Sign in</button>
</form>
Mainly I want refuse duplicate username's or email adress. There's my jquery script:
$(document).ready(function() {
$("#register").submit(function(event){
// $("#register").click(function(){
var $username = $("#username").val();
var $mail = $("#email").val();
// Evita que si alguna comprovacio retorna false s'envi el formulari
event.preventDefault();
// Funcio que valida que el nom no estigui en blanc
if($("#name").val().trim() == ""){
$("#na").addClass( "has-error");
return false;
}
// Funcio que valida que el cognom no estigui en blanc
if($("#surname").val().trim() == ""){
$("#su").addClass( "has-error");
return false;
}
// Funcio ajax per validar que el nom d'usuari no està en ús
$.ajax({
url: "/projCreditV1/rwsc/as/check-value/user_name/" + $username,
success: function(data){
// Si retorna TRUE vol dir que el nom d'usuari es valid perque no està en ús
if(data == "true"){
$("#mail").removeClass("has-error");
return true;
}
else{
$("#user").addClass("has-error");
return false;
}
}
});
// Funcio ajax per validar que el mail no està en ús
$.ajax({
url: "/projCreditV1/rwsc/as/check-value/mail/" + $mail,
success: function(data){
// Si retorna TRUE vol dir que el mail es valid perque no està en ús
if(data == "true"){
$("#mail").removeClass("has-error");
return true;
}
else{
$("#mail").addClass("has-error");
return false;
}
}
});
// Funcio que valida que la contrasenya no estigui en blanc
if($("#password").val().trim() == ""){
$("#pa").addClass( "has-error");
return false;
}
});
});
When some field doesn't meets the requirements return false. I think if whole form doesn't return false, should submit..
Thanks
please remove the event.preventDefault();.
if you use that code, it will never execute the form.
The reason the submit doesn't finish is the:
event.preventDefault(); line. The return doesn't work for the async request. Because it doesn't return the value back to the event.
A way to fix this would be:
Make a normal button instead of a submit button
make jquery do the
submit.

Categories