mail function not working with google captcha - php

<div class="row">
<div class="col-xs-12 col-lg-10 col-lg-offset-1">
<form method="post" action="" name="contactForm" id="contactform" class="clearfix">
<fieldset>
<div class="float-left">
<div class="coolfx fadeInUp">
<!--<span>*Name<label for="name"></label></span>-->
<span><input type="text" id="contactName" name="name" placeholder="*Name" class="text" required></span>
</div>
<div class="coolfx fadeInUp" >
<!--<span>*Email<label for="email"></label></span>-->
<span><input type="email" id="contactEmail" name="email" placeholder="*Email" class="email" required></span>
</div>
<div class="coolfx fadeInUp">
<!--<span>Phone<label for="phone"></label></span>-->
<span><input type="text" id="contactPhone" name="phonenumber" placeholder="Phone" class="text" required></span>
</div>
</div>
<div class="float-right">
<div class="contactform message coolfx fadeInUp">
<!--<span>Message<label for="message"></label></span>-->
<span><textarea id="contactMessage" placeholder="*Message" name="message" class="textarea" required></textarea></span>
</div>
</div>
</fieldset>
<div class="float-right"><div class="g-recaptcha" data-sitekey="6LfsPBgTAAAAAPDkaI1HeSyDm_ecF0iihVsFYBKh"></div></div>
<div class="coolfx fadeInUp">
<input name="send" type="submit" class="submit" id="submit" value="Send Email">
</div>
<?php
if(isset($_POST['g-recaptcha-response']))
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "******************************";// hide for security
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) AND $data->success==true) {?>
<script type="text/javascript">
$(function() {
$("#contactform .submit").click(function() {
var data = {
name: $("#contactName").val(),
email: $("#contactEmail").val(),
phone: $("#contactPhone").val(),
message: $("#contactMessage").val()
};
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function(){
$('.success').fadeIn(1000);
}
});
});
});
</script>
<?php }else {
echo"this is spam"
}?>
I am new in j query how to use j query code inside the php code and also how to verify google captcha code before submit a mail function nothing working .
before google captcha working my code properly but now nothing working.
thanks

You need to handle the Captcha inside email.php. Before getting other posted field values you can check for Capcha response. Also don't forget that you need to post the captcha field (g-recaptcha-response) value like you post name, phone, email and messsage.

Related

API "POST" shows successful but won't reflect changes on database

I have a basic web application that has been coded in php.
The app carries out CRUD operations by making use of an API made through PHP. When I try to use my update.php API endpoint, I get a successful response but no changes reflect in db.
Project Structure
Project_Structure
update.php in api/mailbox
<?php
// include database and object files
include_once '../config/database.php';
include_once '../objects/mailbox.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare mailbox object
$mailbox = new Mailbox($db);
//For diagnostics
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data[""];
// set ID property of product to be edited
$mailbox_id->mailbox_id = $data->mailbox_id;
// set mailbox property values
$mailbox->username = $_POST['username'];
$mailbox->password = base64_encode($_POST['password']);
$mailbox->name = $_POST['name'];
$mailbox->quota = $_POST['quota'];
$mailbox->modified = date('Y-m-d H:i:s');
$mailbox->active = $_POST['active'];
$mailbox->mailbox_id = $_POST['mailbox_id'];
// create the mailbox
if($mailbox->update()){
$mailbox_arr=array(
"status" => true,
"message" => "Successfully Updated Mailbox"
);
}
else{
$mailbox_arr=array(
"status" => false,
"message" => "Mailbox already exists!"
);
}
print_r(json_encode($mailbox_arr));
?>
mailbox.php(in objects folder)
// update mailbox
function update(){
$query = "UPDATE
". $this->table_name ."
SET
username='".$this->username."', password='".$this->password."', name='".$this->name."', quota='".$this->quota."', modified='".$this->modified."', active='".$this->active."'
WHERE
mailbox_id= '".$this->mailbox_id."'";
// prepare query
$stmt = $this->conn->prepare($query);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
update.php (The rendered page, on clicking update, the error is: **Mailbox already exists)**
<?php
$content = '<div class="container"
<div class="row">
<!-- left column -->
<div class="col-md-12">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Update Mailbox</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form">
<div class="box-body">
<div class="form-group">
<div class="form-group">
<label for="exampleMBID1">Mailbox ID</label>
<input type="text" class="form-control" id="mailbox_id" placeholder="Mailbox ID" disabled>
</div>
<label for="exampleInputUserName1">User Name</label>
<input type="text" class="form-control" id="username" placeholder="Enter Username e.g jsmith">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="password" placeholder="Enter Password">
</div>
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name of User">
</div>
<div class="form-group">
<label for="exampleInputMaildir1">Maildir</label>
<input type="text" class="form-control" id="maildir" placeholder="Enter Maildir" disabled>
</div>
<div class="form-group">
<label for="exampleInputQuota1">Quota (0=Unlimited)</label>
<input type="text" class="form-control" id="quota" placeholder="Enter Quota">
</div>
<div class="form-group">
<label for="examplelocalpart1">Local Part</label>
<input type="text" class="form-control" id="local_part" placeholder="localpart" disabled>
</div>
<div class="form-group">
<label for="exampledomain1">Domain</label>
<input type="text" class="form-control" id="domain" placeholder="domain" disabled>
</div>
<div class="form-group">
<label for="examplecreated1">Created</label>
<input type="text" class="form-control" id="created" placeholder="Created" disabled>
</div>
<div class="form-group">
<label for="examplemodified1">Modified</label>
<input type="text" class="form-control" id="modified" placeholder="Modified">
</div>
<div class="form-group">
<label for="exampleactive1">Active (0=Not Active, 1=Active)</label>
<input type="text" class="form-control" id="active" placeholder="Enter 0 or 1">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<input type="button" class="btn btn-primary" onClick="UpdateMailbox()" value="Update"></input>
</div>
</form>
</div>
<!-- /.box -->
</div>
</div>
</div>';
include('../master.php');
?>
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "../api/mailbox/read_single.php?mailbox_id=<?php echo $_GET['mailbox_id']; ?>",
dataType: 'json',
success: function(data) {
$('#username').val(data['username']);
$('#password').val(data['password']);
$('#name').val(data['name']);
$('#maildir').val(data['maildir']);
$('#quota').val(data['quota']);
$('#local_part').val(data['local_part']);
$('#domain').val(data['domain']);
$('#created').val(data['created']);
$('#modified').val(data['modified']);
$('#active').val(data['active']);
$('#mailbox_id').val(data['mailbox_id']);
},
error: function (result) {
console.log(result);
},
});
});
function UpdateMailbox(){
$.ajax(
{
type: "POST",
url: '../api/mailbox/update.php',
dataType: 'json',
data: {
mailbox_id: <?php echo $_GET['mailbox_id']; ?>,
username: $("#username").val(),
password: $("#password").val(),
name: $("#name").val(),
maildir: $("#maildir").val(),
quota: $("#quota").val(),
domain: $("#domain").val(),
modified: $("#modified").val(),
active: $("#active").val()
},
error: function (result) {
alert(result.responseText);
},
success: function (result) {
if (result['status'] == true) {
alert("Successfully Updated Mailbox!");
window.location.href = '/MailEasy/mailbox/listAll.php';
}
else {
alert(result['message']);
}
}
});
}
</script>
1) Why is not updating when using web UI?
2) When using postman, it shows successful, why are requests not reaching the database?
Postman --> Successful response but no changes in db.
Php webpage --> Mailbox already exists.
Thank you

Using 2 recaptcha on same page and getting different values for both via AJAX

I have 2 Google Recaptcha's on same page in different forms (Login and Register Forms). I had to put both the forms on the same page due to the designing requirements which can't be changed. Now the problem is that the 1st form is the login form followed by the register form in the 2nd. Now, the recaptcha on the login form takes effect for register form as well. I mean that I can see recaptcha on both the forms but the one in register form doesn't work (which means it doesn't sends the correct value to the PHP page where the form will be processed). When I tried verifying the recaptcha on the login form and submitting the register form it worked. This means that the 1st loaded recaptcha (on the login form) is working for both which should not be. Both the recaptchas should work separately for each forms. Also, when I get the values of both the recaptchas via AJAX to send to the PHP page for the server side validation I am using captcha: grecaptcha.getResponse() for both. THIS CAN BE THE ACTUAL PROBLEM I GUESS. If I could get separate values for both maybe the things would have gone down well. Any help would be appreciated.
Here are my codes.
<div class="container">
<div class="row">
<div class="col-md-6">
<h3 class="com-reps cr-panel">Login Now</h3>
</div>
<div class="col-md-6">
<h3 class="com-reps cr-panel">Register Now</h3>
</div>
<div class="col-md-6">
<div class="post-holder">
<div class="login-message"></div>
<div class="post-content">
<form method="post" action="">
<div class="form-group">
<input type="text" id="uname" class="form-control" placeholder="Username">
</div>
<div class="form-group">
<input type="password" id="pass" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="<?php echo $mainf['set_recaptcha_sitekey']; ?>"></div>
</div>
<div class="form-group">
<input type="submit" id="login" value="Log In" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
<div class="col-md-6">
<div class="post-holder">
<div class="register-message"></div>
<div class="post-content">
<form method="post" action="">
<div class="form-group">
<input type="text" id="name" class="form-control" placeholder="Full Name">
</div>
<div class="form-group">
<input type="text" id="username" class="form-control" placeholder="Username">
</div>
<div class="form-group">
<input type="password" id="password" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<input type="password" id="cpass" class="form-control" placeholder="Confirm Password">
</div>
<div class="form-group">
<input type="text" id="email" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="text" id="dob" class="form-control" placeholder="Date of Birth">
</div>
<div class="form-group">
Sex
<input type="radio" id="sex" name="sex"> Male
<input type="radio" id="sex" name="sex"> Female
</div>
<div class="form-group">
<input type="checkbox" id="legal" name="legal"> I accept the Terms of Service and Privacy Policy.
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="<?php echo $mainf['set_recaptcha_sitekey']; ?>"></div>
</div>
<div class="form-group">
<input type="submit" id="submit" value="Register" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#login").click(function(){
var dataString = {
uname: $("#uname").val(),
pass: $("#pass").val(),
captcha: grecaptcha.getResponse()
};
$.ajax({
type: "POST",
//dataType : "json",
url: "processes/login.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#login").val("Please wait...");
$(".login-message").hide();
},
success: function(html){
$('.login-message').html(html).fadeIn();
if($('.login-message').find('#responseBox').hasClass('alert-success')){
setTimeout(function(){
window.location.replace("index.php");
}, 500);
}else{
$("#login").val("Log In");
}
}
});
return false;
});
$("#submit").click(function(){
var dataString = {
name: $("#name").val(),
uname: $("#username").val(),
pass: $("#password").val(),
cpass: $("#cpass").val(),
email: $("#email").val(),
dob: $("#dob").val(),
sex: $("input[name='sex']:checked").val(),
captcha: grecaptcha.getResponse()
};
$.ajax({
type: "POST",
//dataType : "json",
url: "processes/register.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").val("Please wait...");
$(".register-message").hide();
},
success: function(html){
$('.register-message').html(html).fadeIn();
$("#submit").val("Register");
}
});
return false;
});
});
</script>
I got the solution. In case someone comes looking for this it will help them.
In both HTML Forms replace
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
to
<div id="recaptcha1"></div> and <div id="recaptcha2"></div> respectively.
Then replace your script calling from
<script src="https://www.google.com/recaptcha/api.js></script>
to
<script src="https://www.google.com/recaptcha/api.js?onload=myCallBack&render=explicit" async defer></script>
And insert these code in your <script></script>. Note that this should be outside of $(document).ready(function() { and above your next form submission AJAX codes.
var recaptcha1;
var recaptcha2;
var myCallBack = function() {
recaptcha1 = grecaptcha.render('recaptcha1', {
'sitekey' : 'YOUR_SITE_KEY'
});
recaptcha2 = grecaptcha.render('recaptcha2', {
'sitekey' : 'YOUR_SITE_KEY'
});
};
Next and last thing, change the captcha: grecaptcha.getResponse() in your form submission AJAX code to captcha: grecaptcha.getResponse(recaptcha1) and captcha: grecaptcha.getResponse(recaptcha2) respectively (for both AJAX codes of login and register forms in my case). For full form submission code please refer to the code in my question above. Just replace the captcha: part here as said.
Done! Now you can proceed to server side validation in your language (PHP or ASP whatever).

Ajax request is retrieving an empy array in PHP

I have a "form" with this code:
<div class="form-wrap" id="contact-form">
<div class="form-innerwrap">
<div class="text-input">
<input type="text" name="name" id="name" required />
<label for="name"><?= CONTACT_FORM_NAME ?></label>
</div>
<div class="text-input">
<input type="email" name="email" id="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<label for="email">E-mail</label>
</div>
<div class="text-input">
<input type="text" name="contact" id="contact" required />
<label for="name"><?= CONTACT ?></label>
</div>
<div class="text-input text-textarea">
<textarea type="info" id="info" name="info">
</textarea>
<label for="email"><?= CONTACT_FORM_MENSSAGE ?></label>
</div>
<input type="hidden" name="lang" id="lang" value="<?= $_SESSION['language'] ?>">
<div class="form-button">
<button type="submit" class="btn contacts-button btn-gowe" id="btn-info" data-btnhover="<?= CONTACT_FORM_BTN ?>"> <span><?= CONTACT_FORM_BTN ?></span> </button>
</div>
</div>
</div>
Then I have a ajax request to sent the input values to php:
$("#btn-info").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var contact = $("#contact").val();
var info = $("#info").val();
var lang = $("#lang").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name='+ name + '&email='+ email +'&contact='+contact+'&info='+info+'&lang='+lang;
$.ajax({
type: "POST",
url: "includes/sendEmail.php",
data: dataString,
cache: false,
success: function(result){
var result = result.split("||");
if (result[0]== "true"){
$("#contact-modal").show();
}
}
});
return false;
});
However when I make a var_dump of $REQUEST the return is an empty array.
Can anyone help me with this problem?
I had already spent several hours to try to understand what is wrong in my code.
Thanks for helping.

unable to insert record through jquery ajax

Right now I am facing a problem : I am trying to insert records in the database with the help of jQuery & Ajax. Unfortunately, I tried to alert inserted values but It doesn't show. I also checked through serialize function and I am unable to do that.
Here is my code of ajax
<script type="text/javascript">
$(document).ready(function(){
$("#add_new").click(function(){
$("#add").slideToggle();
});
$("#submit").click(function(){
var stud_no=$("#roll").val();
if(stud_no==''){
$("#msg").html("Input Roll Number");
} else {
var datastr = $("#sampleform").serialize();
alert(datastr);
$.ajax({
type:'POST',
url:'add_it.php',
data:datastr,
success:function(response){
$("#my_form")[0].reset();
$("#msg").html("Student Successfully Added");
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
});
});
</script>
Here is body code :
<body>
<a id="add_new">+add new item</a><br /><br />
<div id="msg"></div><br />
<div id="add">
<form id="sampleform">
<fieldset>
<div class="form-group row">
<label for="roll" class="col-sm-2 col-form-label">Roll Number</label>
<div class="col-sm-6">
<input type="text" name="roll" class="form-control" id="roll">
</div>
</div>
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-6">
<input type="text" name="name" class="form-control" id="name">
</div>
</div>
<div class="form-group row">
<label for="clas" class="col-sm-2 col-form-label">Class</label>
<div class="col-sm-6">
<input type="text" name="standard" class="form-control" id="standard">
</div>
</div>
<div class="form-group row">
<label for="mail" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-6">
<input type="email" name="mail" class="form-control" id="mail">
</div>
</div>
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</fieldset>
</fieldset>
</form>
</div>
Here is my add_it.php
<?php
include('connectdb.php');
$stud_no = trim($_POST['stud_no']);
$name = trim($_POST['name']);
$standard = trim($_POST['standard']);
$mail = trim($_POST['mail']);
$query = "insert into student (stud_no,name,standard,email) values ('$stud_no','$name','$standard','$mail')";
mysqli_query($con,$query) or die (mysqli_error());
?>
Your HTML form fields doesnt have any of these variables sent. You need to add name="email" etc to your form fields.
So for example the email field has to look like this:
<input type="email" name="email" class="form-control" id="mail">
id, class etc is not sent in POST - and therefor can not be recieved in the other end.
Jquery's serialize() function also only handles "name" fields.
https://api.jquery.com/serialize/
Snippet :
For a form element's value to be included in the serialized string, the element must have a name attribute

How to submit form on one page to a different page using ajax call in jquery

I have a page called page2.php. It has a form that allows you to search via jquery ajax call. The code is below. My question is, I have a different form on page1.php. How can I submit the form on page1.php to go to page2.php and have it execute the page2.php code below using the data from the form on page1.php? I know this is most likely simple, having a brain fart right now.
$(function() {
$.validate({
form: '#form_search',
validateOnBlur: false,
errorMessagePosition: 'top',
onSuccess: function(form) {
var formval = $(form).serialize();
var formurl = '/page2.php?a=search';
$('#form_results').html('<div class="form_wait_search">Searching, please wait...<br><img src="/images/search-loader.gif"></div>');
$.ajax({
type: 'POST',
url: formurl,
data: formval,
success: function(data){
var json = $.parseJSON(data);
$('#form_errors').html(json.message);
$('#form_results').html(json.results);
}
});
return false;
}
});
});
UPDATE
Here is the forms Im referring to.
On page1.php this is like a module on the right side bar. Just a form that I want to post to page2.php
<div class="scontent_box1">
<strong class="box_title"><i class="fa fa-search fa-flip-horizontal"></i> Find Locations</strong>
<form method="post" action="/page2.php">
<div class="form-group">
<label>Street Address</label>
<input type="text" class="form-control" name="ad" placeholder="Enter Street Address...">
</div>
<div class="form-group">
<label>City, State or Zip Code</label>
<input type="text" class="form-control" name="ct" placeholder="Enter City, State or Zip Code...">
</div>
<button type="submit" class="btn btn-default blue_btn">Search</button>
</form>
</div>
Now here is the form on page2.php that executes the ajax code above. I want page1.php to submit to page2.php and envoke the same jquery code above.
<div class="row no_gutters">
<div class="search_page">
<div id="form_errors"></div>
<form method="post" id="form_search">
<div class="form-group">
<label for="ad">Street Address<span class="reqfld">*</span></label>
<input type="text" class="form-control" data-validation="required" id="ad" name="ad" placeholder="Enter Street Address..." value="">
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="ct">City, State or Zip Code<span class="reqfld">*</span></label>
<input type="text" class="form-control input-sm" data-validation="required" id="ct" name="ct" placeholder="Enter City Name..." value="">
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 col-xs-12">
<button type="submit" class="btn btn-default blue_btn btn-block">Search Locations</button>
</div>
<div class="col-md-8"></div>
</div>
</form>
</div>
<div id="form_results"></div>
</div>

Categories