I'm making a form, I'm using AJAX to send it, but I also have a google reCAPTCHA in it and I don't know how to make it required.
I don't want to send the form without checked reCAPTCHA and if it's not checked then I want to show the information about this. I tried lots of things but I still don't know what's wrong.
My HTML code:
<div class="form">
<div id="form-messages"></div>
<form id="formularz" method="post" action="mailer.php">
<div class="line">
<input id="name" name="name" type="text" placeholder="Imię"/>
<input id="email" name="email" type="email" placeholder="E-mail" required/>
</div>
<div class="line2">
<input id="temat" name="temat" type="text" placeholder="Temat" />
<textarea id="wiadomosc" name="message" placeholder="Wiadomość" required></textarea>
</div>
<div class="line3">
<div class="g-recaptcha captcha" data-sitekey="6Lcu9xgUAAAAAPbwLwKWILHGxu-X0cPjAhRtYM2R"></div>
<input id="submit" name="submit" type="submit" value="Wyślij">
<div style="clear:both;"></div>
</div>
</form>
</div>
My js code:
$(function() {
var form = $('#formularz');
var formMessages = $('#form-messages');
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function() {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text('Dziękujemy, wiadomość została wysłana.');
$('#name').val('');
$('#email').val('');
$('#temat').val('');
$('#wiadomosc').val('');
})
.fail(function() {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
$(formMessages).text('Oops! Wiadomość nie mogła zostać wysłana.');
});
});
});
And PHP code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
$recipient = "karol_guzikowski#wp.pl";
$subject = "Nowa wiadomość od $name";
$email_content = "Od: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Wiadomość:\n$message\n";
$email_headers = "Od: $name <$email>";
$wszystko_OK=true;
$sekret = "6Lcu9xgUAAAAAPbwLwKWILHGxu-X0cPjAhRtYM2R";
$sprawdz = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$sekret.'&response='.$_POST['g-recaptcha-response']);
$odpowiedz = json_decode($sprawdz);
if (!$odpowiedz->success){
$wszystko_OK=false;
http_response_code(600);
echo "Proszę zaznaczyć reCAPTCHE";
}
if($wszystko_OK==true){
mail($recipient, $subject, $email_content, $email_headers);
}
}
$(function() {
var form = $('#formularz');
var formMessages = $('#form-messages');
$(form).submit(function(e) {
e.preventDefault();
//Recaptcha Validation
if (!$('#g-recaptcha-response').val().trim().length) {
alert("Recaptcha is required")
return false;
}
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function() {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text('Dziękujemy, wiadomość została wysłana.');
$('#name').val('');
$('#email').val('');
$('#temat').val('');
$('#wiadomosc').val('');
})
.fail(function() {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
$(formMessages).text('Oops! Wiadomość nie mogła zostać wysłana.');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form">
<div id="form-messages"></div>
<form id="formularz" method="post" action="mailer.php">
<div class="line">
<input id="name" name="name" type="text" placeholder="Imię" />
<input id="email" name="email" type="email" placeholder="E-mail" required/>
</div>
<div class="line2">
<input id="temat" name="temat" type="text" placeholder="Temat" />
<textarea id="wiadomosc" name="message" placeholder="Wiadomość" required></textarea>
</div>
<div class="line3">
<div class="g-recaptcha captcha" data-sitekey="6Lcu9xgUAAAAAPbwLwKWILHGxu-X0cPjAhRtYM2R"></div>
<input id="submit" name="submit" type="submit" value="Wyślij">
<div style="clear:both;"></div>
</div>
</form>
</div>
Hope this will work for you.
<form class="p-b-lg" id="enquiry-form" method="post" action="">
<div class="form-group">
<input class="form-control form-control-lg" placeholder="Email" name="email1" type="email">
</div>
<div class="form-group">
<input class="form-control form-control-lg" placeholder="Contact Phone" name="number" type="number" required>
</div>
<div class="form-group">
<div class="g-recaptcha" id="rcaptcha" data-sitekey="sitekey goes here"></div>
<span id="captcha" style="margin-left:100px;color:red" />
</div>
<div class="form-group">
<button class="btn btn-lg btn-secondary-outline team-btn contact-btn" type="submit" name="submit">Send</button>
</div>
</form>
<?php
if(isset($_POST['submit'])){
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
//your site secret key
$secret = 'secret key goes here';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success) {
$email1 = $_POST['email1'];
$contact_phone = $_POST['contact_phone'];
<?php }
}
else { ?>
<script>alert("Please fill captcha.");</script>
<?php }
}
?>
Related
can somebody please tell me why this code is not working I want to sent form data to PHP by post method but my PHP is not receiving any request
here is my signup form
signupmodal.php
<form action="<?php htmlentities($_SERVER['PHP_SELF']) ?>" method="post" id="signupForm">
<div class="form-group">
<label for="forUserName">User Name:</label>
<input type="text" name="username" id="username" class="form-control" placeholder="Enter User Name" aria-describedby="helpId">
</div>
<div class="form-group">
<label for="forEmail">Email:</label>
<input type="email" name="email" id="email" class="form-control" placeholder="Enter Your Email" aria-describedby="helpId">
</div>
<div class="form-group">
<label for="">password:</label>
<input type="password" name="password" id="password" class="form-control" placeholder="Enter Password" aria-describedby="helpId">
</div>
<div class="form-group">
<label for="forConfirmPassword">Confirm Password</label>
<input type="password" name="cpassword" id="cpassword" class="form-control" placeholder="Enter Confirm Password" aria-describedby="helpId">
</div>
<input type="submit" class="btn btn-primary" value="SignUp" id="subbtn" onclick="myFunction()">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
<?php echo json_encode($_POST);
// echo $_POST['email'];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
echo $username;
if ($password == $cpassword) {
//code
} else
echo '<div class="alert alert-danger" role="alert">
<strong>danger</strong>
</div>';
} ?>
</div>
script.js
function myFunction() {
console.log(window.location.href);
$('form').on('submit', function (event) {
$.ajax({
type: 'POST',
url: 'includes/signupmodal.php',
data: $('form#signupForm').serialize(),
success: function () {
data = $('form#signupForm').serialize();
console.log(data);
},
});
event.preventDefault();
});
}
I want to submit my data using ajax without loading the page so, please tell me where I am wrong
You are only running myFunction() when you click the submit button and by then it's too late to add a submit event listener.
I suggest you add your listener when the document is ready.
Remove the onclick="myFunction()" from your submit button and add this to your script
jQuery(function() {
myFunction() // executes when the document has completely loaded
})
// or even just
// jQuery(myFunction)
See https://api.jquery.com/jquery/#jQuery3
I was wondering if anyone could help me with my issue, When ever the form is submitted the street form does not show up in the email I receive. I don't understand why it might not be working I've looked through the php and JS but cant understand why it won't work. Here i the JS:
(function($){
$(document).ready(function() {
/* ---------------------------------------------- /*
* Contact form ajax
/* ---------------------------------------------- */
$('#contact-form').find('input,textarea').jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault();
var submit = $('#contact-form submit');
var ajaxResponse = $('#contact-response');
var name = $('#contact-form [name="name"]').val();
var lastname = $('#contact-form [name="lastname"]').val();
var address = $('#contact-form [name="address"]').val();
var email = $('#contact-form [name="email"]').val();
var message = $('#contact-form [name="message"]').val();
$.ajax({
type: 'POST',
url: 'assets/php/contact.php',
dataType: 'json',
data: {
name: name,
lastname: lastname,
address: address,
email: email,
message: message,
},
cache: false,
beforeSend: function(result) {
submit.empty();
submit.append('<i class="fa fa-cog fa-spin"></i> Wait...');
},
success: function(result) {
if(result.sendstatus == 1) {
ajaxResponse.html(result.message);
$form.fadeOut(500);
} else {
ajaxResponse.html(result.message);
}
}
});
}
});
}); })(jQuery);
Here is the HTML:
<div class="row">
<div name="contactform" class="col-sm-8 col-sm-offset-2">
<form id="contact-form" method="post" novalidate>
<div class="row">
<div class="col-md-6 form-group">
<label class="sr-only">First Name</label>
<input type="text" class="form-control input-lg" name="name" placeholder="First Name" value="" required="">
<p class="help-block text-danger"></p>
</div>
<div class="col-md-6 form-group">
<label class="sr-only">Last Name</label>
<input type="text" class="form-control input-lg" name="lastname" placeholder="Last Name" value="" required="">
<p class="help-block text-danger"></p>
</div>
<div class="col-md-6 form-group">
<label class="sr-only">Address</label>
<input type="text" class="form-control input-lg" name="address" placeholder="Address" value="" required="">
<p class="help-block text-danger"></p>
</div>
<div class="col-md-12 form-group">
<label class="sr-only">E-mail Address</label>
<input type="email" class="form-control input-lg" name="email" placeholder="E-mail Address" value="" required="">
<p class="help-block text-danger"></p>
</div>
<div class="col-md-12 form-group">
<textarea class="form-control input-lg" rows="7" name="message" placeholder="Message - Please include Address and Telephone number" required=""></textarea>
<p class="help-block text-danger"></p>
</div>
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-lg btn-round btn-dark" >Send Email</button>
</div>
</div><!-- .row -->
</form>
<!-- Ajax response -->
<div id="contact-response" class="ajax-response text-center"></div>
</div>
</div>
And here is the php:
<?php
// Mail settings
$to = "****#*******.co.uk";
$subject = "PB Enquiry Form - " . $_REQUEST['lastname'];
// You can put here your email
$header = "From:****#*******.co.uk\r\n";
$header.= "MIME-Version: 1.0\r\n";
$header.= "Content-Type: text/plain; charset=utf-8\r\n";
$header.= "X-Priority: 1\r\n";
if (isset($_POST["name"]) && isset($_POST["lastname"]) && isset($_POST["email"]) && isset($_POST["message"])) {
$content = "First Name: " . $_POST["name"] . "\r\n";
$content .= "Last Name: " . $_POST["lastname"] . "\r\n";
$content .= "Address: " . $_POST["address"] . "\r\n";
$content .= "Email: " . $_POST["email"] . "\r\n";
$content .= "Message: " . $_POST["message"] . "\r\n";
if (mail($to, $subject, $content, $header)) {
$result = array(
"message" => "Thank you for contacting us.",
"sendstatus" => 1
);
echo json_encode($result);
} else {
$result = array(
"message" => "Sorry, something is wrong.",
"sendstatus" => 0
);
echo json_encode($result);
}
}
I cannot figure out why it won't work and would be delighted if someone could help me.
If you do have a solution then please give an example of how to input the solution as I am new to the languages, Thank you!
I was wondering if anyone could help me with my issue,
When ever the form is submitted the street form does not show up in the email I receive. I don't understand why it might not be working I've looked through the php and JS but cant understand why it won't work.
Here i the JS co
(function($){ $(document).ready(function() {
/* ---------------------------------------------- /*
* Contact form ajax
/* ---------------------------------------------- */
$('#contact-form').find('input,textarea').jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault();
var submit = $('#contact-form submit');
var ajaxResponse = $('#contact-response');
var name = $('#contact-form [name="name"]').val();
var lastname = $('#contact-form [name="lastname"]').val();
var email = $('#contact-form [name="email"]').val();
var street = $('#contact-form [name="street"]').val();
var message = $('#contact-form [name="message"]').val();
$.ajax({
type: 'POST',
url: 'assets/php/contact.php',
dataType: 'json',
data: {
name: name,
lastname: lastname,
email: email,
street: street,
message: message,
},
cache: false,
beforeSend: function(result) {
submit.empty();
submit.append('<i class="fa fa-cog fa-spin"></i> Wait...');
},
success: function(result) {
if(result.sendstatus == 1) {
ajaxResponse.html(result.message);
$form.fadeOut(500);
} else {
ajaxResponse.html(result.message);
}
}
});
}
});
}); })(jQuery);
Here is the php:
<?php
// Mail settings
$to = "";
$subject = "PB Enquiry Form - " . $_REQUEST['lastname'];
// You can put here your email
$header = "From:\r\n";
$header.= "MIME-Version: 1.0\r\n";
$header.= "Content-Type: text/plain; charset=utf-8\r\n";
$header.= "X-Priority: 1\r\n";
if (isset($_POST["name"]) && isset($_POST["lastname"]) && isset($_POST["email"]) && isset($_POST["message"])) {
$content = "First Name: " . $_POST["name"] . "\r\n";
$content .= "Last Name: " . $_POST["lastname"] . "\r\n";
$content .= "Email: " . $_POST["email"] . "\r\n";
$content .= "Street: " . $_POST["street"] . "\r\n";
$content .= "Message: " . $_POST["message"] . "\r\n";
if (mail($to, $subject, $content, $header)) {
$result = array(
"message" => "Thank you for contacting us.",
"sendstatus" => 1
);
echo json_encode($result);
} else {
$result = array(
"message" => "Sorry, something is wrong.",
"sendstatus" => 0
);
echo json_encode($result);
}
}
And here is the html:
<form id="contact-form" method="post" novalidate>
<div class="row">
<div class="col-md-6 form-group">
<label class="sr-only">First Name</label>
<input type="text" class="form-control input-lg" name="name" placeholder="First Name" value="" required="">
<p class="help-block text-danger"></p>
</div>
<div class="col-md-6 form-group">
<label class="sr-only">Last Name</label>
<input type="text" class="form-control input-lg" name="lastname" placeholder="Last Name" value="" required="">
<p class="help-block text-danger"></p>
</div>
<div class="col-md-12 form-group">
<label class="sr-only">E-mail Address</label>
<input type="email" class="form-control input-lg" name="email" placeholder="E-mail Address" value="" required="">
<p class="help-block text-danger"></p>
</div>
<div class="col-md-12 form-group">
<label class="sr-only">Street</label>
<input type="text" class="form-control input-lg" name="street" placeholder="Street" value="" required="">
<p class="help-block text-danger"></p>
</div>
<div class="col-md-12 form-group">
<textarea class="form-control input-lg" rows="7" name="message" placeholder="Message" required=""></textarea>
<p class="help-block text-danger"></p>
</div>
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-lg btn-round btn-dark" >Send Email</button>
</div>
</div><!-- .row -->
</form>
I left the Email out on purpose,
Thank You for helping!
My contact form is sending emails twice and I cannot figure out why..
When I submit the form the sending message and succes message shows up twice, also I receive the email twice.
You can find the form on: www.dev-kevin.compoint.be/ctrl+/
I can't find the problem...
form:
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Naam" required>
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email" required>
</div>
<div class="form-group">
<input type="tel" name="tel" class="form-control" placeholder="Telefoon" required>
</div>
<div class="form-group">
<textarea name="message" class="form-control" rows="8" placeholder="Bericht" required></textarea>
</div>
<button type="submit" class="btn btn-primary">Verstuur</button>
</form>
sendemail.php:
<?php
$name = #trim(stripslashes($_POST['name']));
$from = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['tel']));
$message = #trim(stripslashes($_POST['message']));
$to = "kevin#compoint.be";
$mensaje = "Naam: $name \nEmail: $from \nTelefoon: $subject \nBericht: $message";
$pagetitle = "Bericht via de website";
$from = "FROM: Website <info#ctrl+.be>\r\n";
mail($to, $pagetitle, $mensaje, $from);
die();
Javascript:
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email versturen...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">Uw bericht is succesvol verzonden. Wij nemen zo spoedig mogelijk contact met u op.</p>').delay(1000).fadeOut();
});
});
I have this code,when i input invoice code it will get data from MySQL and fill the others text with Ajax. but my ajax don't get return from my controller, any body help me? where I'm wrong?
My controller in PHP to get data.
<?php
public function getDetail_transaction($invoice_id){
$result = $this->db->get_where('tblTransaction', array('payment_trx_id' => $invoice_id))->first_row();
$data = json_encode($result);
return $data;
}
?>
My view:
<div class="container">
<div class="row">
<div class="panel panel-default">
<div class="panel-body">
<h3>Confirm Your Payment</h3>
<div class="col-md-4">
<form name='ConfirmPayment' action="<?php echo base_url('Payment/ConfirmPayment');?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label>Invoice ID</label>
<div>
<input type="text" class="form-control" name='invoice_id' id='invoice_id' placeholder="Invoice ID" style='width:80%;'/>
<a type="submit" id='cek_invoice' class="btn cek_invoice">Cek</a>
</div>
</div>
<div class="form-group">
<label>Nama Rekening Pembayar</label>
<input type="text" class="form-control" name='user_account_name' id='user_account_name' placeholder="Nama Pembayar">
</div>
<div class="form-group">
<label>Bank Asal</label>
<input type="text" class="form-control" name='provider_bank' id='provider_bank' placeholder="Nama Pembayar">
</div>
<div class="form-group">
<label>Bank Tujuan</label>
<input type="text" class="form-control" name='payment_bank_user_name' id='payment_bank_user_name' placeholder="Bank Tujuan">
</div>
<div class="form-group">
<label>No Transafer</label>
<input type="text" class="form-control" name='no_transaction' id='no_transaction' placeholder="Jumlah di Transfer">
</div>
<div class="form-group">
<label>Transfer Date</label>
<input type="text" class="form-control" name='transfer_date' id='transfer_date' placeholder="Jumlah di Transfer">
</div>
<div class="form-group">
<label>Deskripsi</label>
<textarea class="form-control" name='description' id='description' placeholder="Jumlah di Transfer"></textarea>
</div>
<div class="form-group">
<label>Total Transfer</label>
<input type="text" class="form-control" name='total_transfer' placeholder="No total_transfer">
</div>
<div class="form-group">
<label>Bukti Transaksi (optional)</label>
<input type="file" name="scan">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
Ajax Script
$(document).ready(function(){
$("#cek_invoice").click(function(){
data_invoice = $('#invoice_id').val();
var url = "<?php echo base_url('Payment/getDetail_transaction/');?>"+'/'+data_invoice;
$.ajax({
url : url,
type: "POST",
success: function(data) {
alert(data);
$('#payment_bank_user_name').val(data.payment_bank_user_name);
},
failure: function() {
alert('fail');
}
});
});
});
you should 'echo' result after encode it! see this:
<?php
public function getDetail_transaction($invoice_id){
$result = $this->db->get_where('tblTransaction', array('payment_trx_id' => $invoice_id))->first_row();
$data = json_encode($result);
echo $data; //echo data
}
?>
in ajax you should parseJSON your data :
$(document).ready(function(){
$("#cek_invoice").click(function(){
data_invoice = $('#invoice_id').val();
var url = "<?php echo base_url('Payment/getDetail_transaction/');?>"+'/'+data_invoice;
$.ajax({
url : url,
type: "POST",
success: function(data) {
var dun = $.parseJSON(data);
$('#payment_bank_user_name').val(dun.payment_bank_user_name);
},
failure: function() {
alert('fail');
}
});
}); });
Use
echo $data;exit;
Instead of
return $data;
To display the data (after getting the response) -
var data = $.parseJSON(data);
$('#your_input_field').val(data.payment_bank_user_name);
public function getDetail_transaction($invoice_id){
$result = $this->db->get_where('tblTransaction', array('payment_trx_id' => $invoice_id))->first_row();
$data = json_encode($result);
echo $data;
}
and your javascript edit the below line
success: function(data) {
alert(data);
var obj = $.parseJSON(data);
$('#payment_bank_user_name').val(obj.payment_bank_user_name);
},