reCaptcha script blocks my AJAX form from sending the e-mail - php

I have created a Contact form that is sending my contact form data using AJAX.
<form action="inc/contact.php" method="POST" id="contact-form">
<div class="messages"></div>
<div class="row controls">
<div class="col-12">
<div class="input-group-meta form-group mb-30">
<label for="name">Name*</label>
<input type="text" placeholder="John Doe" name="name" required="required" data-error="Name is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-12">
<div class="input-group-meta form-group mb-30">
<label for="email">Email*</label>
<input type="email" placeholder="john.doe#mybusiness.com" name="email" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-12">
<div class="input-group-meta form-group mb-30">
<label for="message">Message*</label>
<textarea placeholder="Your message*" name="message" required="required" data-error="Please,leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-12"><button class="button-class form-button g-recaptcha" type="submit" name="submit" value="send" data-sitekey="6Lc8GI4iAAAAAFxgjs6MQwHdtp5ZjLcgIDQKsJSL" data-callback='onSubmit' data-action='submit'>Send Message</button></div>
<div class="success-message">Thanks for Contacting Us!</div>
</div>
</form>
and this is the validation script
<script>
$('button').click(function() {
validateMe();
})
function validateMe() {
// console.log('validate me');
$('label').css('color', 'white');
var error = []; //this array holds the error messages
var emailReg = /^[^\s#]+#[^\s#]+\.[^\s#]+$/; //regex for email validation
//console.log($('#contact-form input'));
$('#contact-form input').each(function() { //goes through all input fields
var inputName = $(this).attr('name'); //assigns to inputName the name of each field
if ($(this).val().length > 4) {
// console.log($(this).attr('name'));
if (inputName == 'email' && !emailReg.test($(this).val())) //if it is not a valid email
{
error.push($(this).attr('name'));
console.log('invalid email');
}
} else {
error.push($(this).attr('name')); //we are pushing the error messages into this array
}
})
//one more time for the text textarea
$('#contact-form textarea').each(function() { //goes through all input fields
var inputTextname = $(this).attr('name'); //assigns to inputName the name of each field
if ($(this).val().length < 4) {
// console.log($(this).attr('name'));
error.push($(this).attr('name'));
}
})
if (error.length == 0) {
$('#contact-form').submit(function(e) {
console.log('submitted');
$('.success-message').show(1000);
function onSubmit(token) {
document.getElementById("form-button").submit();
}
$.ajax({
type: "POST",
url: "inc/contact.php",
data: $("#contact-form").serialize(),
success: function(data) {
console.log(data)
}
})
e.preventDefault();
});
} else {
for (x = 0; x < error.length; x++) { //loops through all the different errors
$('label[for="' + error[x] + '"]').css('color', 'red');
console.log(error[x]);
}
}
}
</script>
Everything works fine up to here. When i try to add the reCaptcha v3. Script the contact form stops to send and i get the error.
I have tried to move the reCaptcha script onSubmit function to the Footer but still the same.
ReCAPTCHA couldn't find user-provided function: onSubmit

Related

Form Validation with Jquery with if statements

I'm about to release my personal website but stucked with contact form validation. I want visitors to properly enter every field. While I'm doing this, I can go for both sides (either javascript or php validation). But the page is static HTML, only requests for mail.php for sending it. (Using PHPMAILER).
What I want is basically users to get notified in each field, then if they enter everything properly, I want them to submit the form and show the success message, without redirecting them. So here is my code and I appreciate for your help.
<form name="form1" id="contact-form" method="post" role="form">
<div class="col-md-8 col-pb-sm animate-box">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" name="name" required="required" class="form-control" placeholder="Your Name">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="email" required="required" pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" name="email" class="form-control" placeholder="Email">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control" required="required" name="message" id="" cols="30" rows="7" placeholder="Message"></textarea>
</div>
</div>
<div class="col-md-12">
<div class="col-md-3 form-group">
<input type="submit" name="submit" value="Send Message" class="btn btn-primary" formaction="mail.php" onsubmit="return ValidateLoginForm();">
</div>
<div class="col-md-7 col-md-offset-1 form-align" id="form_response"></div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<footer>
<div id="footer">
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<p>
Copyright © 2020 Umut Pirinci.
</p>
</div>
</div>
</div>
</div>
</footer>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- jQuery Easing -->
<script src="js/jquery.easing.1.3.js"></script>
<!-- animateAnything -->
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/409445/animateAnything.js"></script>
<!-- Bootstrap -->
<script src="js/bootstrap.min.js"></script>
<!-- Waypoints -->
<script src="js/jquery.waypoints.min.js"></script>
<!-- Owl Carousel -->
<script src="js/owl.carousel.min.js"></script>
<!-- Magnific Popup -->
<script src="js/jquery.magnific-popup.min.js"></script>
<script src="js/magnific-popup-options.js"></script>
<!-- Main JS (Do not remove) -->
<script src="js/main.js"></script>
<script>
$(function() {
$('a[href*=\\#]:not([href=\\#])').on('click', function() {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.substr(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
});
});
</script>
<script>
$(function () {
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "mail.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;
}
})
});
</script>
<script>
function ValidateLoginForm() {
var name = document.form1.name;
var message = document.form1.message;
var email = document.form1.email;
if (name.value == "") {
alert("Your name wasn't recognised.");
name.focus();
return false;
}
if (message.value == "") {
alert("Please enter your message.");
message.focus();
return false;
}
if (email.value == "") {
alert("Please enter your email address.");
email.focus();
return false;
}
else {
return true;
}
}
</script>
<script>
function form_sub() {
$('#form_response').html('Your form has been successfully sent!').fadeIn(1500).delay(5000).fadeOut(1500);
}
</script>
</body>
</html>
There are some things you need to do:
1- input with type submit you need to remove the onsubmit attribute as this attribute must be added on FORM tag only.
2- try to combine submission functions with only one.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form name="form1" id="contact-form" method="post" role="form">
<div class="col-md-8 col-pb-sm animate-box">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" name="name" required="required" class="form-control" placeholder="Your Name">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="email" required="required" pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" name="email" class="form-control" placeholder="Email">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control" required="required" name="message" id="" cols="30" rows="7" placeholder="Message"></textarea>
</div>
</div>
<div class="col-md-12">
<div class="col-md-3 form-group">
<input type="submit" name="submit" value="Send Message" class="btn btn-primary" formaction="mail.php">
</div>
<div class="col-md-7 col-md-offset-1 form-align" id="form_response"></div>
</div>
</div>
</div>
</form>
<script>
$('#contact-form').on('submit', function (e) {
ValidateLoginForm();
e.preventDefault();
return false;
})
function ValidateLoginForm() {
var name = document.form1.name;
var message = document.form1.message;
var email = document.form1.email;
if (name.value == "") {
alert("Your name wasn't recognised.");
name.focus();
return false;
}
if (message.value == "") {
alert("Please enter your message.");
message.focus();
return false;
}
if (email.value == "") {
alert("Please enter your email address.");
email.focus();
return false;
} else {
var url = "mail.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();
}
}
});
}
}
</script>

Insert multiple values in row php

I can`t find a solution for this formular, so i am asking you guys how i can solve this: (1)I have this formular:
<form id="formRetur" action="" method="POST" novalidate="novalidate">
<div id="mail-status" style="color: black;text-align: center;"></div>
<h3><strong>
Detalii client
</strong></h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nume_prenume" id="nume_prenume" placeholder="Nume Prenume">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_tlf" id="nr_tlf" placeholder="Numar telefon">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="adresa_email" id="adresa_email" placeholder="Adresa email">
</div>
</div>
</div>
<h3><strong>
Detalii comanda
</strong></h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_comanda" id="nr_comanda" placeholder="Numar comanda">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="data_comanda" id="data_comanda" placeholder="Data comanda">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_factura" id="nr_factura" placeholder="Numar factura">
</div>
</div>
</div>
<h3><strong>
Detalii produse
</strong></h3>
<div class="row">
<i class="fa fa-plus" aria-hidden="true" style="position: absolute;z-index:999;"></i>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="den_prod" id="den_prod" placeholder="Denumire produs">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="culoare_prod" id="culoare_prod" placeholder="Culoare produs">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="cantitate" id="cantitate" placeholder="Cantitate">
</div>
</div>
</div>
<div class="maimulte">
</div>
<h3><strong>
Motiv retur
</strong></h3>
<div class="row">
<div class="col-md-12">
<textarea name="motiv" id="motiv" class="form-control" cols="30" rows="10"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-12" style="margin-top:10px;margin-bottom:10px;"><div class="g-recaptcha" data-sitekey="<?php echo SITE_KEY; ?>"></div> </div>
<div class="col-md-12">
<button type="submit" id="send-message" class="btn btn-default">Trimite </button>
</div>
<div id="loader-icon" style="display:none;"><img src="images/loader.gif"></div>
</div>
</form>
I use ajax to insert data in DB, but i have an option where you can add more products when user press + adding +1 row with 3 fields name,color, qty and i want to insert also these in db, here is my ajax:
<script>
$(document).ready(function (e){
$("#formRetur").on('submit',(function(e){
e.preventDefault();
$("#mail-status").hide();
$('#send-message').hide();
$('#loader-icon').show();
$.ajax({
url: "valid_retur.php",
type: "POST",
dataType:'json',
data: {
"nume_prenume":$('input[name="nume_prenume"]').val(),
"nr_tlf":$('input[name="nr_tlf"]').val(),
"adresa_email":$('input[name="adresa_email"]').val(),
"nr_comanda":$('input[name="nr_comanda"]').val(),
"data_comanda":$('input[name="data_comanda"]').val(),
"nr_factura":$('input[name="nr_factura"]').val(),
"den_prod":$('input[name="den_prod"]').val(),
"culoare_prod":$('input[name="culoare_prod"]').val(),
"cantitate":$('input[name="cantitate"]').val(),
"motiv":$('textarea[name="motiv"]').val(),
"g-recaptcha-response":$('textarea[id="g-recaptcha-response"]').val()},
success: function(response){
// $( '#frmContact' ).each(function(){
// this.reset();
// });
$("#mail-status").show();
$('#loader-icon').hide();
if(response.type == "error") {
$('#send-message').show();
$("#mail-status").attr("class","alert alert-danger");
} else if(response.type == "message"){
// grecaptcha.reset();
$('#send-message').show();
$("#mail-status").attr("class","alert alert-success");
}
$("#mail-status").html(response.text);
},
error: function(){}
});
}));
});
</script>
Here is my db:enter image description here
And there is my php file who insert in db with values from ajax:
<?php
if($_POST)
{
include('config.php');
$nume_prenume = filter_var($_POST["nume_prenume"], FILTER_SANITIZE_STRING);
$nr_tlf = filter_var($_POST["nr_tlf"], FILTER_SANITIZE_STRING);
$adresa_email = filter_var($_POST["adresa_email"], FILTER_SANITIZE_STRING);
$nr_comanda = filter_var($_POST["nr_comanda"], FILTER_SANITIZE_STRING);
$data_comanda = filter_var($_POST["data_comanda"], FILTER_SANITIZE_STRING);
$nr_factura = filter_var($_POST["nr_factura"], FILTER_SANITIZE_STRING);
$den_prod = filter_var($_POST["den_prod"], FILTER_SANITIZE_STRING);
$culoare_prod = filter_var($_POST["culoare_prod"], FILTER_SANITIZE_STRING);
$cantitate = filter_var($_POST["cantitate"], FILTER_SANITIZE_STRING);
$motiv = filter_var($_POST["motiv"], FILTER_SANITIZE_STRING);
if(empty($nume_prenume)) {
$empty[] = "<b>nume_prenume</b>";
}
if(empty($nr_tlf)) {
$empty[] = "<b>nr_tlf</b>";
}
if(empty($adresa_email)) {
$empty[] = "<b>adresa_email</b>";
}
if(empty($nr_comanda)) {
$empty[] = "<b>nr_comanda</b>";
}
if(empty($data_comanda)) {
$empty[] = "<b>data_comanda</b>";
}
if(empty($den_prod)) {
$empty[] = "<b>data_comanda</b>";
}
if(empty($culoare_prod)) {
$empty[] = "<b>data_comanda</b>";
}
if(!empty($empty)) {
$output = json_encode(array('type'=>'error', 'text' => implode(", ",$empty) . ' obligatoriu!'));
die($output);
}
// if(!filter_var($email2, FILTER_VALIDATE_EMAIL)){ //email validation
// $output = json_encode(array('type'=>'error', 'text' => '<b>'.$email2.'</b> is an invalid Email, please correct it.'));
// die($output);
// }
//reCAPTCHA validation
if (isset($_POST['g-recaptcha-response'])) {
require('component/recaptcha/src/autoload.php');
$recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY, new \ReCaptcha\RequestMethod\SocketPost());
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$output = json_encode(array('type'=>'error', 'text' => '<b>Captcha</b> Validation Required!'));
die($output);
}
}
// bag in db
$sql0 = "INSERT INTO retur (nume_prenume, nr_tlf, email, nr_comanda, data_comanda, nr_factura, den_prod, culoare_prod, cantitate_prod, motiv_retur)
VALUES ('$nume_prenume', '$nr_tlf', '$adresa_email', '$nr_comanda', '$data_comanda', '$nr_factura', '$den_prod', '$culoare_prod', '$cantitate', '$motiv')";
mysqli_query($conn, $sql0);
}
So basically this is a formular for returns products and if he have more products to return i added that jquery to add more fields and i want to be inserted in databased then i will fetch data and display it in my CMS.
1.You don't have to write that much code in ajax. You can easily use serialize():
Reduce you ajax code with below code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#your_form_id");
$("#Your_submit_id").click(function(){
$.ajax({
type:"POST",
url:"URL",
data:form.serialize(),
success: function(response){
console.log(response);
}
});
});
});
</script>
2.To add multiple product:
-You have to create every input field as array for product info like:
<input type="text" name="prod_name[]">
This array statement store you every product info index wise. If you
used normal variable then it will post only you last product
details.
In Php code you have to take the count of posted
product title & use for loop to get the every product information.
for($i=0;$i<count($prod_name);$i++)
{
//Insert/fetch All Values like : $prod_name[$i]
}
-When you click on add, just create clone of the prev available div.

send emails from phonegap android application

I want to send a feedback form from android PhoneGap application i have used following code which is not working
1) i have used bellow Ajax code and JQuery files to send ajax request and HTML form, i want to send the email of 4 html fields
<script type="text/javascript" src="assets/js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="assets/js/jquery.js"></script>
<script type="text/javascript" src="assets/js/geturi.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#send").click(function() {
var fullName = $("#fullName").val();
var emailId = $("#emailId").val();
var mobileNo = $("#mobileNo").val();
var message = $("#message").val();
var dataString = "fullName=" + fullName + "&emailId=" + emailId + "&mobileNo=" + mobileNo + "&message=" + message + "&send=";
if ($.trim(fullName).length > 0 & $.trim(emailId).length > 0 & $.trim(mobileNo).length > 0 & $.trim(message).length > 0) {
$.ajax({
type: "POST",
url: "https://www.activebittechnologies.com/phonegap/mail.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#send").val('Sending Enquiry...');
},
success: function(data) {
if (data == "success") {
alert("Mail Sent");
$("#send").val('submit');
} else if (data == "error") {
alert("error");
}
}
});
}
return false;
});
});
</script>
<div class="content form">
<div class="header">
<div class="header-overlay"></div><img src="assets/banner/5.jpg">
<div class="info">
<h3 class="title">Send Contact Enquiry</h3>
<span data-close="#enquirepop" class="closeit"><i class="fa fa-times" aria-hidden="true"></i></span>
</div>
</div>
<div class="form-group">
<input id="fullName" name="fullName" type="text" class="form-control" placeholder="Full Name">
</div>
<div class="form-group">
<input id="emailId" name="emailId" type="text" class="form-control" placeholder="Email Id">
</div>
<div class="form-group">
<input id="mobileNo" name="mobileNo" type="text" class="form-control" placeholder="Mobile No">
</div>
<div class="form-group">
<textarea class="form-control" id="message" name="message" placeholder="Your Message" style="color:#fff;"></textarea>
</div>
<div class="text-right">
<input type="button" id="send" class="btn btn-primary" value="Send">
</div>
</div>
unable to go on this page from phone gap when installed on android phone bellow is php script which is on server
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
$toEmail = "hotelinkonkan#gmail.com";
$mailHeaders = "From: " . $_POST["fullName"] . "<". $_POST["emailId"] .">\r\n";
$sentml=mail($toEmail, $_POST["fullName"], $_POST["message"], $mailHeaders);
if($sentml)
echo"success";
else
echo"error";
?>
I use $("#form1").serialize() to get all the values from the form, and I validate the values on the server side. You should always validate your values server side, because users can send a direct post to your php without any javascript validation.
Hope it helps.
<script type="text/javascript" src="assets/js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="assets/js/jquery.js"></script>
<script type="text/javascript" src="assets/js/geturi.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#send").click(function() {
$.ajax({
type: "POST",
url: "https://www.activebittechnologies.com/phonegap/mail.php",
data: $("#form1").serialize(),
crossDomain: true,
cache: false,
beforeSend: function() {
$("#send").val('Sending Enquiry...');
},
success: function(data) {
console.log(data);
if (data == "success") {
alert("Mail Sent");
$("#send").val('submit');
} else if (data == "error") {
alert("error");
}
}
});
return false;
});
});
</script>
<form id='form1' >
<div class="content form">
<div class="header">
<div class="header-overlay"></div><img src="assets/banner/5.jpg">
<div class="info">
<h3 class="title">Send Contact Enquiry</h3>
<span data-close="#enquirepop" class="closeit"><i class="fa fa-times" aria-hidden="true"></i></span>
</div>
</div>
<div class="form-group">
<input id="fullName" name="fullName" type="text" class="form-control" placeholder="Full Name">
</div>
<div class="form-group">
<input id="emailId" name="emailId" type="text" class="form-control" placeholder="Email Id">
</div>
<div class="form-group">
<input id="mobileNo" name="mobileNo" type="text" class="form-control" placeholder="Mobile No">
</div>
<div class="form-group">
<textarea class="form-control" id="message" name="message" placeholder="Your Message" style="color:#fff;"></textarea>
</div>
<div class="text-right">
<input type="button" id="send" class="btn btn-primary" value="Send">
</div>
</div></form>

Add a checkbox option to a PHP/MySQL form

I have the following form
<body>
<div class="container">
<div class="title pull-left"><img src="http://www.isfin.ro/images/institutul_de_studii_financiare_ISF.png" width="145px" height="80px" /></div>
<div class="title pull-right"><h1>Actualizare newsletter</h1></div>
</div>
<hr class="featurette-divider"></hr>
<div class="container">
<div class="col-sm-12">
GDPR text goes here
</div>
<div class="form-group">
<label for="email">Email:</label>
<input id="email" class="form-control" type="email" placeholder="Adresa Email">
</div>
<div class="form-group">
<label for="nume">Nume:</label>
<input id="nume" class="form-control" type="text" placeholder="Nume">
</div>
<p>Want to remain subscribed?</p>
<label class="radio-inline">
<input type="radio" name="optradio" value="yes">Yes
</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="no">No
</label>
<br><br>
<button type="submit" id="submit" class="btn btn-default btn-block btn-primary">Trimite</button>
<div id="display"></div>
<script>
$(document).ready(function(){
$("#submit").click(function(){
var em = $("#email").val();
var sub = $("#nume").val();
var com = $("#comments").val();
var dataString = 'em1='+ em + '&sub1='+ sub + '&com1='+ com;
if(em==''||sub==''||com=='')
{
$("#display").html("<div class='alert alert-warning'>Please Fill All Fields.</div>");
}
else
{
$.ajax({
type: "POST",
url: "processor.php",
data: dataString,
cache: false,
success: function(result){
$("#display").html(result);
}
});
}
return false;
});
});
</script>
</div>
</body>
And this is the content of processor.php
<?php
include_once('config.php');
$email=mysqli_real_escape_string($con, $_POST['em1']);
$emailclean = filter_var($email, FILTER_SANITIZE_EMAIL, FILTER_FLAG_STRIP_HIGH);
$sub=mysqli_real_escape_string($con, $_POST['sub1']);
$subclean = filter_var($sub, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
//insert into database
mysqli_query($con,"INSERT INTO contact(`email`, `nume`)VALUES('$emailclean','$subclean')");
//send message back to AJAX
echo '<div class="alert alert-success">Preferintele au fost actualizate.</div>';
$con->close();
?>
How can I insert the content of the radio buttons Yes / No into a database field?
My database have the following structure id, email, nume, subscription_status, i need to insert the value from radio buttons into subscription_status (Yes or No value).
Thanks!
Get the value of selected checkbox:
var data = document.querySelector('input[name="optradio"]:checked').value;
Now add this value to your data string which you are sending via ajax:
var dataString = 'em1='+ em + '&sub1='+ sub + '&com1='+ com + '&radio=' + data;
And get the value on PHP/server side:
$radio_value = $_POST['radio'];

Jquery ajax posts twice

I got an ajax issue I can't get my head around. I'm using a ajax post method to send an email. But everytime I send one the post happens 2 times. I've tried adding preventDefault and stopPropagation but it doesn't seem to do the trick.
Jquery
$(document).ready(function()
{
$("#submit_btn").click(function(event)
{
event.preventDefault();
event.stopPropagation();
var proceed = true;
var submit = $('#submit_btn');
$("#contact_form input, #contact_form textarea").each(function () {
$(this).closest("div").removeClass('has-error');
if(!$.trim($(this).val())) {
$(this).closest("div").addClass('has-error');
proceed = false;
}
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).closest("div").addClass('has-error');
proceed = false;
}
});
if(proceed){
post_data = {
'user_name' : $('input[name=name]').val(),
'user_email' : $('input[name=email]').val(),
'subject' : $('select[name=subject]').val(),
'msg' : $('textarea[name=message]').val()
};
$.ajax({
type: 'POST',
url: "./mail.php",
data: post_data,
beforeSend: function() {
submit.html('Sending...');
},
success: function(data){
output = '<div class="alert alert-success" role="alert">Hi ' + $('input[name=name]').val() + ' Thank you for your email</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
submit.html("Send");
},
error: function(){
output = '<div class="alert alert-danger" role="alert">Something went wrong. Please try again</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
submit.html("Send");
}
});
return false;
}
else{
output = '<div class="alert alert-danger" role="alert">Please fill in the required fields so I can get back to you !</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
}
});
$("#contact_form input, #contact_form textarea").keyup(function() {
$(this).closest("div").removeClass('has-error');
$("#contact_form").find("#contact_results").slideUp();
});
});
HTML
<div class="clear" id="contact">
<h3>Contact Me</h3>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<form role="form" id="contact_form" action="">
<div class="form-group">
<label for="name">Name</label><input name="name" type="text" placeholder="Name" class="form-control" id="name" />
</div>
<div class="form-group">
<label for="email">Email address</label>
<input name="email" type="email" placeholder="E-Mail" class="form-control" id="email" />
</div>
<div class="form-group">
<label for="subject">Subject</label>
<select name="subject" class="form-control" id="subject">
<option value="General Question">General Question</option>
<option value="Hire me!">Hire me !</option>
<option value="Partner with me!">Partner with me !</option>
</select>
</div>
<div class="form-group">
<label for="message">Message</label><textarea name="message" placeholder="Message" id="message" class="form-control" rows="5"></textarea>
</div>
<button type="submit" class="btn btn-default" id="submit_btn">Send</button>
<div id="contact_results"></div>
</form>
</div>
</div>
</div>
</div>
If someone could point me in the right direction that would be much appreciated.
Try changing $("#submit_btn").click(function(event) to $("#submit_btn").one('click',function(event)
If that doesn't work, check that the JS is not being loaded twice

Categories