Get data with ajax from php and mysql - javascript

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

Related

How to submit form including image on button click [duplicate]

This question already has answers here:
Sending formdata for file upload using ajax
(3 answers)
Closed 9 months ago.
I have this HTML:
<form id="form" enctype="multipart/form-data">
<div class="row">
<div class="col">
<div class="mb-3">
<label for="design_title" class="form-label">Ttile of the design</label>
<input type="text" name="design" class="form-control" id="design_title">
</div>
</div>
<div class="col">
<div class="mb-3">
<label for="design" class="form-label">Upload a new design</label>
<input type="file" name="design" class="form-control" id="design">
</div>
</div>
</div>
<div class="mb-3">
<div class="row">
<div class="col">
<label for="fontsize" class="form-label">Enter the font size</label>
<input type="number" name="design_font_size" class="form-control" id="fontsize">
</div>
<div class="col">
<label for="position_x" class="form-label">Position X</label>
<input type="number" name="design_x" class="form-control" id="position_x">
</div>
<div class="col">
<label for="position_y" class="form-label">Position Y</label>
<input type="number" name="design_y" class="form-control" id="position_y">
</div>
</div>
</div>
<div class="mb-3">
<label class="form-label" for="domain">Choose a domain</label>
<select name="domain" id="domain" class="form-control" data-form="design_output">
<option value="">--Choose--</option>
<?php
$get_domain = mysqli_query( $mysqli, "SELECT * FROM eg_domains");
if( mysqli_num_rows( $get_domain ) > 0 ) {
while( $get_result = mysqli_fetch_array( $get_domain, MYSQLI_ASSOC ) ) {
$domain_name = $get_result['domain_name'];
$company = $get_result['company_name'];
$domain_id = $get_result['domain_id'];
echo "<option value='$domain_id'>$domain_name ($company)</option>";
}
}
?>
</select>
</div>
<button type="button" class="btn btn-primary ajax-btn output-desing" data-form="output_design">Output Design</button>
<button type="submit" class="btn btn-success ajax-btn">Save Design</button>
<div class="mt-3">
<div class="result"></div>
</div>
</form>
Now, on Output Design button click I want to get all the data including image.
So, I am doing this in JQuery/Ajax:
$(document).on("click", ".output-desing", function (e) {
e.preventDefault();
var form = document.querySelector(".output-desing");
var form_name = form.dataset.form;
var data = $("#form").serialize() + "&form=" + form_name;
// var data = '1';
console.log(data);
$.ajax({
dataType: "html",
type: "GET",
url: 'helper/process.php',
data: data,
contentType: false,
cache: false,
processData: false,
beforeSend: function () {
$(".output-design").val("Please wait...");
},
success: function (data) {
$(".output-design").html(data);
}
});
});
But I can get only form data not image data.
How can I get all the data including image data on that button click?
Anyways, I fix it this way:
var form = document.querySelector(".output-desing");
var form_name = form.dataset.form;
var data = new FormData(document.getElementById("form"));
data.append('form', form_name);

backend not adding books to android app sql

i have made an ebook android app everything works fine but the backend code of admin age which is written in php and javascript .the admin has a function to add book known as savebook the "savebook" function is not working please help me guys....every time i try to add a book i it just shows a failed message but when i add the book to the database manually via phpmyadmin it works here is the code to that function
the problem is in last function (what is think) but stil i would appreciate if you guys find some other mistake in the code the whole website is working but this only function is not working the app in on android platform the backend is done using codeigniter and the app is linked to a database which maintains the details of book
<?php
$this->load->view('admin/comman/header');
?>
<div class="clearfix"></div>
<div class="content-wrapper">
<div class="container-fluid">
<!-- Breadcrumb-->
<div class="row pt-2 pb-2">
<div class="col-sm-9">
<h4 class="page-title">Add Book</h4>
<ol class="breadcrumb">
<li class="breadcrumb-item">Dashboard</li>
<li class="breadcrumb-item">Books</li>
<li class="breadcrumb-item active" aria-current="page">Add Book</li>
</ol>
</div>
<div class="col-sm-3">
<div class="btn-group float-sm-right">
Books List
</div>
</div>
</div>
<!-- End Breadcrumb-->
<div class="row">
<div class="col-lg-10 mx-auto">
<div class="card">
<div class="card-body">
<div class="card-title">Add Book
<form id="edit_video_form" enctype="multipart/form-data">
<div class="form-group">
<label for="input-1">Book Name</label>
<input type="text" required value="" class="form-control" name="input_name" id="input-1">
</div>
<input type="hidden" name="id" value="">
<div class="form-group">
<label for="input-3">Book Cost</label>
<select name="select_cost" required class="form-control" id="purpose">
<option value="0">Free</option>
<option value="1">Paid</option>
</select>
</div>
<div class="form-group" id="business" style="display:none">
<label for="input-1">Book price</label>
<input type="text" required value="" class="form-control" name="input_price" id="input-1" placeholder="Enter Book Price">
</div>
<div class="form-group">
<label for="input-2">Book Category</label>
<!-- DropDown -->
<select name="select_category" required class="form-control">
<option value="">Select Category</option>
<?php $i = 1;
foreach($categorylist as $cat) { ?>
<option required value="<?php echo $cat->cat_id; ?>"><?php echo $cat->cat_name; ?></option>
<?php $i++;
} ?>
</select>
</div>
<div class="form-group">
<label for="input-2">Book Author</label>
<!-- DropDown -->
<select name="select_author" required class="form-control">
<option value="">Select Author</option>
<?php $i = 1;
foreach($authorlist as $cat) { ?>
<option value="<?php echo $cat->a_id; ?>"><?php echo $cat->a_title; ?></option>
<?php $i++;
} ?>
</select>
</div>
<div class="form-group">
<label for="input-1"> Book Cover Poster</label>
<input type="file" required class="form-control" name="input_bookcover" id="input-1" placeholder="select Book Cover image"
onchange="readURL(this,'showImage')">
<input type="hidden" name="input_bookcover" value="">
<p class="noteMsg">Note: Image Size must be less than 2MB.Image Height and Width less than 1000px.</p>
<img id="showImage" src="<?php echo base_url() . 'assets/images/placeholder.png'; ?>" height="100" width="100" alt="your image"/>
</div>
<div class="form-group">
<label for="input-1"> Upload Sample Book</label>
<input type="file" required class="form-control" name="input_sample_book" id="input-1" placeholder="select Sample Book">
<input type="hidden" name="input_sample_book" value="">
</div>
<div class="form-group">
<label for="input-1"> Upload Full Book</label>
<input type="file" required class="form-control" name="input_full_book" id="input-1" placeholder="select Full Book">
<input type="hidden" name="input_full_book" value="">
</div>
<div class="form-group">
<label for="input-1">Book Description</label>
<textarea cols="40" rows="5" style="height: 150px" type="text" required value="" class="form-control" name="input_description"
id="input-1"></textarea>
</div>
<div class="form-group">
<button type="button" onclick="savebook()" class="btn btn-primary shadow-primary px-5">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
$this->load->view('admin/comman/footerpage');
?>
<script type="text/javascript">
$('#purpose').on('change', function () {
if (this.value === '1') {
$("#business").show();
} else {
$("#business").hide();
}
});
function savebook() {
var wallpaper_title = jQuery('input[name=wallpaper_title]').val();
if (wallpaper_title == '') {
toastr.error('Please enter Book Name');
return false;
}
$("#dvloader").show();
var formData = new FormData($("#edit_video_form")[0]);
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>index.php/admin/savebook',
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function (resp) {
$("#dvloader").hide();
if (resp.status == '200') {
document.getElementById("edit_video_form").reset();
toastr.success(resp.msg, 'success');
setTimeout(function () {
location.reload();
}, 500);
} else {
toastr.error(resp.msg);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#dvloader").hide();
toastr.error(errorThrown.msg, 'failed');
}
});
}
</script>
here is the database code
enter code here
public function savebook(){
$input_name = $_POST['input_name'];
$input_description = $_POST['input_description'];
$input_price = $_POST['input_price'];
$select_category = $_POST['select_category'];
$select_author = $_POST['select_author'];
$select_cost = $_POST['select_cost'];
$is_feature = "yes";
$b_status = "enable";
$fa_id = $_POST['select_author'];
$input_bookcover=$this->imageupload($_FILES['input_bookcover'],'input_bookcover', FCPATH . 'assets/images/book');
if (isset($_FILES['input_sample_book']) && !empty($_FILES['input_sample_book']['name'])) {
$input_sample_book=$this->fileupload($_FILES['input_sample_book'],'input_sample_book', FCPATH . 'assets/images/book');
}
if (isset($_FILES['input_full_book']) && !empty($_FILES['input_full_book']['name'])) {
$input_full_book=$this->fileupload($_FILES['input_full_book'],'input_full_book', FCPATH . 'assets/images/book');
}
$data = array(
'b_title' => $input_name,
'b_description' => $input_description,
'is_paid' => $select_cost,
'sample_b_url' => $input_sample_book,
'b_url' => $input_full_book,
'b_price' => $input_price,
'fcat_id'=> $select_category,
'b_image' => $input_bookcover,
'is_feature' => $is_feature,
'b_status' => $b_status,
'fa_id' => $fa_id,
'b_date' => date('Y-m-d h:i:s')
);
$res_id=$this->Adminmodel->add_book($data);
if($res_id){
$res=array('status'=>'200','msg'=>'Book added successfully.','id'=>$res_id);
echo json_encode($res);exit;
}else{
$res=array('status'=>'400','msg'=>'fail');
echo json_encode($res);exit;
}
}

How ajax work in dynamically generated div

I am doing sales of product in which I use AJAX to capture data based on a selection from a dropdown to another one. When I dynamically create a field it works only once i want it to work N number of time.
Here is my HTML & PHP Code:
<div class="row col-md-12 mrg-top-20">
<h4 class="card-title" style="color:#ff0033">Sales Details</h4><br>
<div class="col-md-12"></div>
<div class="row col-md-12" data-duplicate="add">
<div class="col-md-4">
<label>Select <strong>Installation Date</strong></label>
<div class="form-group">
<div class="timepicker-input input-icon form-group">
<i class="ti-time"></i>
<input type="text" name="ins_date" class="form-control datepicker-1" placeholder="Datepicker" data-provide="datepicker">
</div>
</div>
</div>
<div class="col-md-4" id="sel_dynamic">
<div class="form-group">
<label>Select <strong>Manufacturer</strong></label>
<select name="manu" id="manu" class="form-control" style="width:100%">
<option disabled="disabled" selected="selected">Select Manufacturer</option>
<?php
$data = mysqli_query($conn,"SELECT * FROM manufacturer_details");
while($itemcat = mysqli_fetch_array($data))
{
?>
<option value="<?php echo $itemcat['MANUFACTURER_ID']; ?>"><?php echo $itemcat['MANUFACTURER_NAME'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Select <strong>Modal</strong></label>
<select name="modal" id="modal" class="form-control" style="width:100%">
<option value="" selected disabled="disabled">Select Modal...</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Ser<strong>ial</strong></label>
<input type="text" name="serial" placeholder="Enter Serial No" class="form-control">
</div>
</div>
<div class="col-md-4">
<label>Select <strong>AMC Start Date</strong></label>
<div class="form-group">
<div class="timepicker-input input-icon form-group">
<i class="ti-time"></i>
<input type="text" name="amc_date" class="form-control datepicker-1" placeholder="Datepicker" data-provide="datepicker" data-date-format="mm/dd/yyyy">
</div>
</div>
</div>
<div class="col-md-4">
<label>Select <strong>AMC End Date</strong></label>
<div class="form-group">
<div class="timepicker-input input-icon form-group">
<i class="ti-time"></i>
<input type="text" name="amc_edate" class="form-control datepicker-1" placeholder="Datepicker" data-provide="datepicker" data-date-format="mm/dd/yyyy">
</div>
</div>
</div>
</div>
<div>
<input type="button" id="add" data-duplicate-add="add" class="btn btn-info" value="+"/>
</div>
<div >
<input type="button" data-duplicate-remove="add" class="btn btn-info" value="-"/>
</div>
</div>
Here is My Js Script to Call Ajax Each Time
<script type="text/javascript">
$(document).ready(function()
{
$("#sel_dynamic").on("change","#manu",(function() //just try to use on change
{
var id = $("#manu").val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(html)
{
$("#modal").html(html);
}
});
});
});
</script>
Here is my Ajax File
<?php
include('script/db.php');
if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysqli_query($conn,"select * from modal_details where MANUFACTURER_ID='".$id."'");
?>
<option selected disabled="disabled">Select Modal Name</option>
<?php
while($row = mysqli_fetch_assoc($sql))
{
$id = $row['MODAL_ID'];
$data = $row['MODAL_NAME'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
?>
Whenever I create a new field dynamically my AJAX is not working.
Try this :
<script type="text/javascript">
$(document).ready(function()
{
$(document).on('change','#manu',function()
{
var id = $("#manu").val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(html)
{
$("#modal").html(html);
}
});
});
});
</script>
The comments made it clear that you are duplicating your form. I think you have duplicate IDs on your page and your jQuery event will not work anymore. An ID may only occur once.
Take a look here:
Clone form and increment
Add the class to select as shown below:
<select name="manu" id="manu" class="form-control manuClass" style="width:100%">
And use the below script
<script type="text/javascript">
$(document).ready(function()
{
$(document).on('change','.manuClass',function()
{
var id = $(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(html)
{
$(this).parent().parent().next().children().children("#modal").html(html);
}
});
});
});
</script>

without page reload how to insert the data using below javascript

Using e.preventDefault(); values not insert in to database,if comment e.preventDefault(); data inserted in to database, without page reload how to insert the data using below javascript code please suggest me
Insert form
<form class="form-horizontal msg_fixed_bottom send_message_form" method="POST" role="form" action="<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_communication">
<div class="panel-footer" id="myForm" >
<div class="input-group submit_group">
<input id="messagee" name="messagee" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" id="submit" name="submit">Send</button>
</span>
</div>
</div>
</form>
script
<script>
$(document).ready(function () {
scrollDown();
$("#submit").click(function (e) {
e.preventDefault();
var message = $("#messagee").val();
$('#chat_log').append('<div class="row msg_container base_sent active"><div class="col-md-10 col-xs-10"><div class="messages msg_receive"><p>' + message + '</p></div></div></div>');
$('#messagee').val('');
scrollDown();
});
});
function scrollDown() {
$('.msg_container_base').animate({scrollTop: $('.msg_container_base').prop("scrollHeight")}, 0);
}
</script>
HTML
<form id="data_form" class="form-horizontal msg_fixed_bottom send_message_form">
<div class="panel-footer" id="myForm" >
<div class="input-group submit_group">
<input id="messagee" name="messagee" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" id="submit" name="submit" type="submit">Send</button>
</span>
</div>
</div>
JavaScript
$(document).ready(function(){
$('#data_form').on('submit', function(e){
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_communication',
data: form_data,
success:function(data)
{
alert('Success');
},
error:function()
{
alert('failed');
}
});
e.preventDefault();
});
});
insert form
<form class="form-horizontal msg_fixed_bottom send_message_form" id="data_form" method="POST" role="form" action="#">
<div class="panel-footer" id="myForm" >
<div class="input-group submit_group">
<input id="messagee" name="messagee" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" id="submit" name="submit">Send</button>
</span>
</div>
</div>
</form>
javascript
<script>
$(document).ready(function(){
$('#data_form').on('submit', function(e){
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_communication',
data: form_data,
success:function(data)
{
var message = $("#messagee").val();
$('#chat_log').append('<div class="row msg_container base_sent active"><div class="col-md-10 col-xs-10"><div class="messages msg_receive"><p>' + message + '</p></div></div></div>');
scrollDown();
function scrollDown() {
$('.msg_container_base').animate({scrollTop: $('.msg_container_base').prop("scrollHeight")}, 0);
}
},
error:function()
{
alert('failed');
}
});
e.preventDefault();
});
});
</script>
You can use ajax for submitting the data without page reload.
<script type="text/javascript">
// Ajax post
$(document).ready(function() {
$(".submit").click(function(event) {
event.preventDefault();
var messagee= $("input#messagee").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "your_controller/your_function",
dataType: 'json',
data: {
messagee: messagee
},
success: function(res) {
if (res) {
// Show Entered Value
//sussess message here
}
}
});
});
});
Your Controller:
// This function call from AJAX
public function your_function() {
$data = array(
'messagee' => $this->input->post('messagee')
);
//Either you can print value or you can send value to database
echo json_encode($data);
}
your form:
<form class="form-horizontal msg_fixed_bottom send_message_form" method="POST" role="form" id="msg-form">
<div class="panel-footer" id="myForm" >
<div class="input-group submit_group">
<input id="messagee" name="messagee" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." />
<span class="input-group-btn">
<input type="submit" class="btn btn-primary btn-sm" id="submit" name="submit" value="Submit">
</span>
</div>
</div>
</form>
your ajax
<script>
$(document).ready(function(){
$("#msg-form").submit(function(e){
e.preventDefault();
var msg = $("#messagee").val();
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_communication',
data: {msg:msg},
success:function(data)
{
alert('SUCCESS!!');
},
error:function()
{
alert('fail');
}
});
});
});
</script>
I think this will work fine. Now add your additional append functionality in the success area by yourself. thanks.

How to make a reCAPTCHA required?

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 }
}
?>

Categories