Using PHPMailer to reveive message from the contact form SMTP server - ajax

I have been trying to create a contact form where anyone can send an email to the website host. I have tried using PHPMailer with the Gmail SMTP server. I have also installed composer as suggested in some posts. Nothing seems to be working. Here is the code:
<?php
require 'PHPMailerAutoload.php';
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost', 'root', '', 'perfectcup');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$fname = mysqli_real_escape_string($mysqli, $_POST['fname']);
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
$message= mysqli_real_escape_string($mysqli, $_POST['message']);
$email2 = "";
$subject = "Test Message";
if (strlen($fname) > 50) {
echo 'fname_long';
} elseif (strlen($fname) < 2) {
echo 'fname_short';
} elseif (strlen($email) > 50) {
echo 'email_long';
} elseif (strlen($email) < 2) {
echo 'email_short';
} elseif (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo 'eformat';
} elseif (strlen($message) > 500) {
echo 'message_long';
} elseif (strlen($message) < 3) {
echo 'message_short';
} else {
//MAILER
require '/phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer();
error_reporting(E_ALL);
ini_set('display_errors','1');
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.mail.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'youremail#gmail.com'; // SMTP username
$mail->Password = 'passowrd'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
$mail->AddReplyTo($email);
$mail->From = $email2;
$mail->FromName = $fname;
$mail->SMTPDebug=2;
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if (!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'true';
}
}
?>
This is the code that I have used for the contact form:
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#contact").click(function () {
fname = $("#fname").val();
email = $("#email").val();
message = $("#message").val();
$.ajax({
type: "POST",
url: "sendmsg.php",
data: "fname=" + fname + "&email=" + email + "&message=" + message,
success: function (html) {
if (html == 'true') {
$("#add_err2").html('<div class="alert alert-success"> \
<strong>Message Sent!</strong> \ \
</div>');
} else if (html == 'fname_long') {
$("#add_err2").html('<div class="alert alert-danger"> \
<strong>First Name</strong> must cannot exceed 50 characters. \ \
</div>');
} else if (html == 'fname_short') {
$("#add_err2").html('<div class="alert alert-danger"> \
<strong>First Name</strong> must exceed 2 characters. \ \
</div>');
} else if (html == 'email_long') {
$("#add_err2").html('<div class="alert alert-danger"> \
<strong>Email</strong> must cannot exceed 50 characters. \ \
</div>');
} else if (html == 'email_short') {
$("#add_err2").html('<div class="alert alert-danger"> \
<strong>Email</strong> must exceed 2 characters. \ \
</div>');
} else if (html == 'eformat') {
$("#add_err2").html('<div class="alert alert-danger"> \
<strong>Email</strong> format incorrect. \ \
</div>');
} else if (html == 'message_long') {
$("#add_err2").html('<div class="alert alert-danger"> \
<strong>Message</strong> must cannot exceed 50 characters. \ \
</div>');
} else if (html == 'message_short') {
$("#add_err2").html('<div class="alert alert-danger"> \
<strong>Message</strong> must exceed 2 characters. \ \
</div>');
} else {
$("#add_err2").html('<div class="alert alert-danger"> \
<strong>Error</strong> processing request. Please try again. \ \
</div>');
}
},
beforeSend: function () {
$("#add_err2").html("loading...");
}
});
return false;
});
});
</script>
</head>
<body>
<div class="brand">The Perfect Cup</div>
<div class="address-bar">3481 Melrose Place | Beverly Hills, CA 90210 | 123.456.7890</div>
<!-- Navigation -->
<?php require_once 'nav.php'; ?>
<div class="container">
<div class="row">
<div class="box">
<div class="col-lg-12">
<hr>
<h2 class="intro-text text-center">Contact
<strong>The Perfect Cup</strong>
</h2>
<hr>
</div>
<div class="col-md-8">
<iframe src="https://www.google.com/maps/embed?pb=!1m16!1m12!1m3!1d105743.04700852593!2d-118.43314319603537!3d34.08309263846107!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!2m1!1s3481%20Melrose%20Place%20Beverly%20Hills%2C%20CA%2090210!5e0!3m2!1sen!2sus!4v1624811422150!5m2!1sen!2sus" width="100%" height="400" style="border:0;" allowfullscreen="" loading="lazy"></iframe>
</div>
<div class="col-md-4">
<p>Phone:
<strong>123.456.7890</strong>
</p>
<p>Email:
<strong>info#theperfectcup.com</strong>
</p>
<p>Address:
<strong>3481 Melrose Place
<br>Beverly Hills, CA 90210</strong>
</p>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="row">
<div class="box">
<div class="col-lg-12">
<hr>
<h2 class="intro-text text-center">Contact
<strong>form</strong>
</h2>
<hr>
<div id="add_err2"></div>
<form role="form">
<div class="row">
<div class="form-group col-lg-4">
<label>Name</label>
<input type="text" id="fname" name="fname" maxlength="25" class="form-control">
</div>
<div class="form-group col-lg-4">
<label>Email Address</label>
<input type="email" id="email" name="email" maxlength="25" class="form-control">
</div>
<div class="clearfix"></div>
<div class="form-group col-lg-12">
<label>Message</label>
<textarea class="form-control" rows="6"></textarea>
</div>
<div class="form-group col-lg-12">
<button type="submit" id="contact" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- /.container -->
<footer>
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<p>Copyright ©The Perfect Cup 2020</p>
</div>
</div>
</div>
</footer>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>

Related

How to save state of page even after reloading or closing the browser?

I am working on a quiz application using laravel as backend and vuejs to render the questions on the frontend. The thing that is confusing me how to store the state of quiz even after candidate reloads the page or he/she accidentally close the browser. I am thinking about saving the quiz progress in the database. Is there any better approach than this?
<template>
<div>
<div class="container quiz-steps" v-for="(question,index) in questions" v-bind:key="index">
<div v-show="index === currentIndex && timer>0">
<div>
<span class="badge badge-danger">{{ minutes }}</span>
<span class="badge badge-danger">{{ seconds }}</span>
</div>
<div class="progress">
<div class="progress-bar bg-danger" role="progressbar" :style="{width: returnTimerWidth()}" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<br>
<div class="container-quiz-question-pills">
<ul class="nav nav-pills quiz-question-pills">
<li> {{ wrong }}<i class="icon-remove"></i></li>
<li> {{ right }} <i class="icon-ok"></i></li>
</ul>
</div>
<div class="question-content">
<p>{{ question.question }}</p>
<!-- Material unchecked -->
<div class="form-check">
<input type="radio" v-model="picked" class="form-check-input" value="1" id="radio1" name="materialExampleRadios">
<label class="form-check-label" for="radio1">{{ question.option1 }}</label>
</div>
<!-- Material checked -->
<div class="form-check">
<input type="radio" v-model="picked" class="form-check-input" value="2" id="radio2" name="materialExampleRadios">
<label class="form-check-label" for="radio2">{{ question.option2 }}</label>
</div>
<div class="form-check">
<input type="radio" v-model="picked" class="form-check-input" value="3" id="radio3" name="materialExampleRadios">
<label class="form-check-label" for="radio3">{{ question.option3 }}</label>
</div>
<div class="form-check">
<input type="radio" v-model="picked" class="form-check-input" value="3" id="radio4" name="materialExampleRadios">
<label class="form-check-label" for="radio4">{{ question.option4 }}</label>
</div>
enter code here
</div>
<br><br><br><br>
<div>
<span> {{index+1}} / {{questions.length}} </span>
<button type="button" class="btn btn-outline-danger float-right btn-next" #click="nextQuestion(question.isCorrect)">Next</button>
</div>
<br>
<div class="progress">
<div class="progress-bar bg-danger" role="progressbar" :style="{width: returnWidth(index)}" aria-valuenow="100" aria-valuemin=0 aria-valuemax="100"></div>
</div>
</div>
</div>
<div v-if="currentIndex === questions.length || timer==0">
<div class="container thankyou-quiz-page">
<div class="text-center">
<p>Thnakyou for taking the Quiz!</p>
<br>
<div class="thankyou-msg">
<p>You have answered <span>{{ right }}</span> correct answers out of <span>{{ questions.length }}</span>. Your total time was <span>{{ minutesTaken }}:{{ secondsTaken }}</span>. The answers were sent to the administrator and he will contact you shortly.</p>
<p>Your total marks are {{ calculateScore() }}</p>
</div>
<br><br>
<div class="text-center quiz-choice">
Retake the Quiz<br>
Next Quiz
</div>
</div>
<br><br>
<div class="thankyou-message-button">
<button type="button" class="btn ">Retake the Quiz</button>
<button type="button" class="btn float-right ">Next Quiz</button>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
name:'TEST',
props:['quizId'],
data(){
return{
currentIndex:0,
picked:'',
right:0,
wrong:0,
questions:[
],
timer:0,
total:0,
minutes:0,
seconds:0,
minutesTaken:0,
secondsTaken:0,
remainingTime:0,
done:false,
interval: '',
negative: 0,
totalMarks: 0,
type: 0
}
},
methods:{
nextQuestion:function(e){
if(this.picked){
if(e==this.picked){
this.right++;
}
else{
this.wrong++;
}
}
this.currentIndex++;
if(this.currentIndex == this.questions.length){
this.timer = 0;
}
this.picked = '';
},
returnWidth(e){
if( e==0 ){
return 0+'%';
}
else {
return e / this.questions.length * 100+'%';
}
},
returnTimerWidth(){
if( this.remainingTime == 0 )
{
return 0+'%';
}
else{
return this.remainingTime / this.total * 100 + '%';
}
},
loadQuestions(){
axios.get("http://192.168.1.3:8000/api/quiz/"+this.quizId).
then( ({ data }) => ( this.questions = data.data.questions,
this.timer = data.data.timeAllowed * 60,
this.total = this.timer,
this.negative = data.data.negativePercentage,
this.getTime(this)
) )
},
getTime(){
let interval = setInterval( () => {
this.minutes = parseInt(this.timer / 60, 10);
this.seconds = parseInt(this.timer % 60, 10);
this.minutes = this.minutes < 10 ? "0" + this.minutes : this.minutes;
this.seconds = this.seconds < 10 ? "0" + this.seconds : this.seconds;
if (--this.timer <0 ) {
// this.timer = 0;
this.totalTime();
clearInterval(interval);
}
else{
this.remainingTime++;
this.returnTimerWidth();
}
}, 1000);
},
totalTime(){
this.minutesTaken = parseInt(this.remainingTime / 60, 10);
this.secondsTaken = parseInt(this.remainingTime % 60, 10);
this.minutesTaken = this.minutesTaken < 10 ? "0" + this.minutesTaken : this.minutesTaken;
this.secondsTaken = this.secondsTaken < 10 ? "0" + this.secondsTaken : this.secondsTaken;
},
calculateScore(){
this.totalMarks = this.right - ( this.wrong * this.negative );
// if(this.type==1){
// axios.post('http://192.168.1.3:8000/api/quizMarks', {
// Marks: this.totalMarks
// })
// .then(function (response) {
// console.log(response);
// })
// .catch(function () {
// // console.log(error);
// });
//
// }
// else if(this.type==0){
// axios.post('http://192.168.1.3:8000/api/quizMarks', {
// Marks: this.totalMarks
// })
// .then(function (response) {
// console.log(response);
// })
// .catch(function () {
// // console.log(error);
// });
// }
return this.totalMarks;
}
},
created() {
this.loadQuestions();
}
}
</script>
One way is to use local storage and check if the key exists once the page is loaded.
A cleaner way is to use vuex https://vuex.vuejs.org/ and a local storage plugin such as vuex persist.

gallery images does not get updated in database

I have an event management company website. https://redcarpetevents.in. the only issue is i cannot update the image gallery. i can upload new images, that works fine. but when i edit the images already in the database, it is not getting updated.
routes.php
Route::get('admin/editGalleryForm/{type}/{editId}', array('as'=>'editGalleryForm','before'=>'authAdmin','uses'=>'AdminController#editGalleryForm'));
Route::post('admin/editGallery', array('as'=>'editGallery','before'=>'csrf|xss_clean|authAdmin','uses'=>'FormController#editGallery'));
Model.php
public static function editGallery($data){
$gallery = Gallery::find($data['editId']);
$gallery->type = $data['type'];
$gallery->tag = $data['tag'];
$gallery->position = $data['order'];
if (isset($data['status'])) {
$gallery->status = $data['status'];
}else{
$gallery->status = 'off';
}
if (isset($data['home'])) {
$gallery->home = $data['home'];
}else{
$gallery->home = 'off';
}
if (isset($data['title'])) {
$gallery->title = $data['title'];
}
if($gallery->update()){
return true;
}else{
return false;
}
}
public static function getGalleryCounts(){
$galleryCounts = array();
$galleryCounts['all'] = count(Gallery::all());
$galleryCounts['allActive'] = count(Gallery::where('status','=','on')->get());
$galleryCounts['allInActive'] = count(Gallery::where('status','=','off')->get());
$galleryCounts['personal'] = count(Gallery::where('type','=','1')->get());
$galleryCounts['personalActive'] = count(Gallery::where('type','=','1')->where('status','=','on')->get());
$galleryCounts['personalInActive'] = count(Gallery::where('type','=','1')->where('status','=','off')->get());
$galleryCounts['corporate'] = count(Gallery::where('type','=','2')->get());
$galleryCounts['corporateActive'] = count(Gallery::where('type','=','2')->where('status','=','on')->get());
$galleryCounts['corporateInActive'] = count(Gallery::where('type','=','2')->where('status','=','off')->get());
return $galleryCounts;
}
Admincontroller.php
public function editGalleryForm($type,$id){
$data['id'] = $id;
$data['type'] = $type;
$data['galleryCounts'] = Gallery::getGalleryCounts();
$data['image'] = Gallery::getGalleryById($id);
$data['personalTags'] = GalleryTag::getPersonalActive();
$data['corporateTags'] = GalleryTag::getCorporateActive();
return View::make('admin.editGalleryForm', $data);
}
Formcontroller.php
public function editGallery(){
$type = Input::get('type');
$editId = Input::get('Id');
$filename=Input::get('image');
$rules = array(
'order'=>'Numeric');
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
$data['type'] = $type;
$data['Id'] = $editId;
return Redirect::route('editGalleryForm',$data)->withInput()->withErrors($validation);
}
if ($validation->passes()) {
$fileName='';
if (Input::hasFile('image')) {
$name = Input::file('image')->getClientOriginalName();
$destinationPath = 'assets/img/gallery/';
$data['Id'] = $Id;
$fileName = $name;
Input::file('image')->move($destinationPath, $fileName);
//Gallery::convertImage($destinationPath,$fileName);
}
$editGallery = Gallery::editGallery(Input::all());
if ($editGallery) {
$data['success'] = 'Gallery Image Updated!';
$data['type'] = $type;
return Redirect::route('newGallery',$data);
}
else
{
$data['failure'] = 'Operation failed!';
$data['type'] = $type;
return Redirect::route('newGallery',$data);
}
}
}
this is the form
#extends('admin.layouts.master')
#section('pageHeader')
<h2>Edit Gallery Image</h2>
<ol class="breadcrumb">
<li>{{HTML::linkRoute('adminHome','Dashboard')}}</li>
<li>{{HTML::linkRoute('newGallery','Gallery',array('type'=>$type))}}</li>
<li class="active">Edit Gallery Image</li>
</ol>
#stop
#section('content')
<div class="cl-mcont">
<div class="status_bar">
<div class="butpro butstyle {{($type=='1')? 'status_active':''}}"><a href="{{URL::route('newGallery',array('type'=>'1'))}}">
<div class="sub"><h2>PERSONAL</h2><span id="total_clientes">{{$galleryCounts['personal']}} Image{{($galleryCounts['personal'] > 1)? 's':''}}</span></div>
<div class="stat">{{$galleryCounts['personalActive']}} <i style="color:#00FF00" class="fa fa-check"></i> {{$galleryCounts['personalInActive']}} <i style="color:#FF0000" class="fa fa-times"></i></div>
</a></div>
<div class="butpro butstyle {{($type=='2')? 'status_active':''}}"><a href="{{URL::route('newGallery',array('type'=>'2'))}}">
<div class="sub"><h2>CORPORATE</h2><span id="total_clientes">{{$galleryCounts['corporate']}} Image{{($galleryCounts['corporate'] > 1)? 's':''}}</span></div>
<div class="stat">{{$galleryCounts['corporateActive']}} <i style="color:#00FF00" class="fa fa-check"></i> {{$galleryCounts['corporateInActive']}} <i style="color:#FF0000" class="fa fa-times"></i></div>
</a></div>
</div>
<div class="row">
<div class="col-md-12">
{{Form::open(array('action'=>'editGallery','method'=>'POST','files'=>true,'class'=>'form-horizontal'))}}
<div class="form-group">
{{Form::label('forType', 'Type', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::select('type', array('1'=>'personal','2'=>'corporate'), ($image->type=='2')? '2':'1', array('class'=>'form-control','onChange'=>'tagChange(this)'))}}
<div class="color-danger">{{$errors->first('type')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forTag', 'Tag', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<select class="form-control" id="tags" name="tag">
#if($type == 2)
#foreach($corporateTags as $tag)
<option {{($image->tag == $tag->id)? 'selected':''}} value="{{$tag->id}}">{{$tag->name}}</option>
#endforeach
#else
#foreach($personalTags as $tag)
<option {{($image->tag == $tag->id)? 'selected':''}} value="{{$tag->id}}">{{$tag->name}}</option>
#endforeach
#endif
</select>
<div class="color-danger">{{$errors->first('tag')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forTitle', 'Title', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::text('title', $image->title, array('class'=>'form-control','placeholder'=>'Image Title'))}}
<div class="color-danger">{{$errors->first('title')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forImage', 'Gallery Image', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::file('forimage', array('class'=>'form-control','placeholder'=>'image'))}} (600 X 400)px
<div class="color-danger">{{$errors->first('image')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('', '', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<div class="col-md-2 padding photo">
<img src="{{asset('assets/img/gallery/'.$image->image)}}" width="200px" height="120px">
</div>
</div>
</div>
<div class="form-group">
{{Form::label('forOrder', 'Order', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::text('order', $image->position, array('class'=>'form-control','placeholder'=>'Image Order'))}}
<div class="color-danger">{{$errors->first('order')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forStatus', 'Publish Status', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<div class="switch" data-on="success">
<input type="checkbox" name="status"{{($image->status=='on')? 'checked':''}}>
</div>
</div>
</div>
<div class="form-group">
{{Form::label('forShow', 'Show on Homepage', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<div class="switch" data-on="success">
<input type="checkbox" name="home"{{($image->home=='on')? 'checked':''}}>
</div>
</div>
</div>
{{Form::text('editId', $image->id, array('style'=>'display:none'))}}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
{{Form::submit('Update Gallery', array('class'=>'btn btn-primary'))}}
{{HTML::linkRoute('newGallery','Cancel',array('type'=>$type),array('class'=>'btn btn-default'))}}
</div>
</div>
{{Form::token().Form::close()}}
</div>
</div>
</div>
#stop
#section('customScripts')
<script type="text/javascript">
function tagChange(element){
console.log(element.value);
$('#tags').empty();
$.ajax({
url:'{{URL::route("getTagsAjax")}}',
type:'POST',
data:{'type':element.value},
dataType:'JSON',
success:function(data){
console.log(data);
for (var i = 0; i <= data.length; i++) {
$('#tags').append('<option value="'+data[i].id+'">'+data[i].name+'</option>');
};
}
});
}
</script>
#stop

recaptcha v2 not getting the "success"

I’m having trouble in the implementation of recaptcha v2 chekbox. I first implemented in my form and it only works in local server. After failing in many attempts I search for some code and I’m using it raw from the tutorial and keep getting error.
Url: https://afrumex.com/google_reCAPTCHA/prueba.html
Hope someone could help. Thanks!!
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ajax Contact Form</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>
<!-- ajax contact form -->
<section style="margin-top: 50px;">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<h5 class="card-header">Ajax Contact Form</h5>
<div class="card-body">
<form class="contact__form" method="post" action="mail.php">
<!-- form message -->
<div class="row">
<div class="col-12">
<div class="contact__msg" style="display: none">
<p>Your message was sent successfully.</p>
</div>
</div>
</div>
<!-- end message -->
<!-- form element -->
<div class="row">
<div class="col-md-6 form-group">
<input name="name" type="text" class="form-control" placeholder="Name" required>
</div>
<div class="col-md-6 form-group">
<input name="email" type="email" class="form-control" placeholder="Email" required>
</div>
<div class="col-md-6 form-group">
<input name="phone" type="text" class="form-control" placeholder="Phone" required>
</div>
<div class="col-md-6 form-group">
<input name="subject" type="text" class="form-control" placeholder="Subject" required>
</div>
<div class="col-12 form-group">
<textarea name="message" class="form-control" rows="3" placeholder="Message" required></textarea>
</div>
<div class="col-12 form-group">
<div class="g-recaptcha" data-sitekey="my site key here"></div>
</div>
<div class="col-12">
<input name="submit" type="submit" class="btn btn-success" value="Send Message">
</div>
</div>
<!-- end form element -->
</form>
</div>
</div>
</div>
</div>
</div>
</section>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="main.js"></script>
</body>
</html>
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// access
$secretKey = 'my secret key here';
$captcha = $_POST['g-recaptcha-response'];
if(!$captcha){
echo '<p class="alert alert-warning">Please check the the captcha form1.</p>';
exit;
}
# FIX: Replace this email with recipient email
$mail_to = "demo#gmail.com";
# Sender Data
$subject = trim($_POST["subject"]);
$name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST["name"])));
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$phone = trim($_POST["phone"]);
$message = trim($_POST["message"]);
if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($phone) OR empty($subject) OR empty($message)) {
# Set a 400 (bad request) response code and exit.
http_response_code(400);
echo '<p class="alert alert-warning">Please complete the form and try again.</p>';
exit;
}
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$captcha&remoteip=$ip");
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<p class="alert alert-warning">Please check the the captcha form2.</p>';
} else {
# Mail Content
$content = "Name: $name\n";
$content .= "Email: $email\n\n";
$content .= "Phone: $phone\n";
$content .= "Message:\n$message\n";
# email headers.
$headers = "From: $name <$email>";
# Send the email.
$success = mail($mail_to, $subject, $content, $headers);
if ($success) {
# Set a 200 (okay) response code.
http_response_code(200);
echo '<p class="alert alert-success">Thank You! Your message has been sent.</p>';
} else {
# Set a 500 (internal server error) response code.
http_response_code(500);
echo '<p class="alert alert-warning">Oops! Something went wrong, we couldnt send your message.</p>';
}
}
} else {
# Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo '<p class="alert alert-warning">There was a problem with your submission, please try again.</p>';
}
?>
I had exactly the same problem and I posted my solution under the earlier question.
My tested solution is:
$google_url = "https://www.google.com/recaptcha/api/siteverify";
$secret_key = 'YOUR_SECRET_KEY';
$response = $_POST['g-recaptcha-response'];
$message = 'Google reCaptcha Test';
if(!empty($response))
{
$url = $google_url."?secret=".$secret_key."&response=".$response;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, TRUE);
$curlData = curl_exec($curl);
curl_close($curl);
$res = json_decode($curlData, TRUE);
if($res['success'] == 'true')
$message = "Success!";
else
$message = "Enter captcha again!";
}
After struggling for a while trying to implement checkbox recaptcha v2 in my form, I tried to implement invisible recaptcha v2, and this one works perfectly. I don’t know how this can happen! You can see in function here.
I don't know if it has something to do with my ssl certificate (from let's encrypt).
This tutorial help me a lot.
Thanks for the comments ehacinom!!

AJAX code not working on iPad only

We've created an event check-in page where nonprofits can add volunteers at an event. The page is working great on all platforms besides iPad. (iPhone Safari is working.)
On iPad, clicking id=add-volunteer button has no effect. Desired behavior is that clicking the button adds the volunteer name to the list of registered volunteers and saves the user info on the backend. (Other backend tasks such as sending an invite email should occur on the backend as well.)
HTML
<form id="form-add" method="post">
<input type="hidden" name="csrfmiddlewaretoken">
<div class="row one-margin-bottom center">
<div id="new-volunteers" class="small-12 medium-8 small-centered columns">
<h6 class="left">Add volunteer</h6>
<div class="row">
<div class="input-right small-6 columns">
<input class="center" id="new-firstname" name="user_firstname" placeholder="First name" type="text" required="">
</div>
<div class="input-right small-6 columns">
<input class="center" id="new-lastname" name="user_lastname" placeholder="Last name" type="text" required="">
</div>
<div class="input-right small-12 medium-12 columns">
<input class="lead center" id="new-email" name="user_email" placeholder="Email address" type="email" required="">
</div>
</div>
<div class="no-margin-top qtr-margin-bottom checkbox center">
<input type="checkbox" name="invite-optin" id="invite-optin" class="custom-checkbox" checked="">
<label for="invite-optin">Invite volunteer to openCurrents</label>
</div>
<a id="add-volunteer" class="half-margin-bottom button round small secondary">
Add volunteer
</a>
</div>
</div>
</form>
<form id="form-checkin" method="post">
<input type="hidden" name="csrfmiddlewaretoken">
<div class="row">
<div class="small-12 medium-8 small-centered columns">
<h6 class="left half-margin-bottom">Registered volunteers</h6>
<div class="row">
<div class="left small-8 columns">
<p class="small-text half-margin-top half-margin-bottom"><strong>Name / Email</strong></p>
</div>
<div class="right small-4 columns">
<p class="small-text half-margin-top half-margin-bottom"><strong>Check in</strong></p>
</div>
</div>
</div>
</div>
<div class="row">
<div id="registered-volunteers" class="small-12 medium-8 small-centered columns">
</div>
</div>
</form>
<div class="row">
<a href="/org-admin/" class="button round small secondary">
Back to org home
</a>
</div>
JS
let onCheckClick = function(event) {
let name = event.target.name;
let elem = $(`#${name}`);
let userid = elem.val();
let isChecked = elem.prop("checked");
$.ajax({
url: "{% url 'openCurrents:event_checkin' event_id %}",
type: 'POST',
data : {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[1].value,
userid: userid,
checkin: isChecked
},
dataType : "json",
context: document.body
}).done(function( data ){
// console.log('checkin request:');
// console.log(data);
if (isChecked) {
let dt = new Date();
$(`#vol-status-${userid}`).text(`${dt.toLocaleTimeString()}`);
$(`#vol-status-${userid}`).show();
}
else {
$(`#vol-status-${userid}`).text(`${data.responseText} min.`);
}
}).fail(function (data) {
// console.log('checkin error:')
// console.log(data);
elem.prop('checked', false);
$('#live-dashboard-error').slideDown();
});;
};
$(document).ready(function(){
// bind all existing checkbox to checkin
$("input[name^='vol-checkin']").click(onCheckClick);
$("#add-volunteer").click(function(event){
if ($(this).attr('disabled') === 'disabled') {
$('#live-dashboard-checkin-disabled').slideDown();
return;
}
if ($('#new-firstname').val() == '' || $('#new-lastname').val() == '' || $('#new-email').val() == '') {
$('#vol-error').slideDown();
} else if ( !(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($('#new-email').val() )) ) {
$('#vol-error').slideUp();
$('#email-error').slideDown();
} else {
$('#vol-error').slideUp();
$('#email-error').slideUp();
let new_firstname = $('#new-firstname').val();
let new_lastname = $('#new-lastname').val();
let new_email = $('#new-email').val();
let invite_optin = $('#invite-optin').prop('checked');
let process_signup_url;
let form_data = {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
user_firstname: new_firstname,
user_lastname: new_lastname,
user_email: new_email.toLowerCase()
};
if (invite_optin) {
process_signup_url = "{% url 'openCurrents:process_signup' endpoint=True verify_email=True %}"
form_data['org_admin_id'] = {{ user.id }};
}
else {
process_signup_url = "{% url 'openCurrents:process_signup' endpoint=True verify_email=False %}"
}
form_data['signup_status'] = 'vol'
$.ajax({
url: process_signup_url,
type: 'POST',
data: form_data,
dataType : "json",
}).done(function( data ) {
// console.log('signup response:')
// console.log(data);
let userid = data;
let form_data = {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
userid: userid
}
$.ajax({
url: "{% url 'openCurrents:event_register_live' eventid=event.id %}",
type: 'POST',
data: form_data,
dataType : "json",
}).done(function( data ) {
//console.log('register_live response:')
//console.log(data);
// hide any error messages present
$('#vol-exist').slideUp();
$('#live-dashboard-error-register').slideUp();
$('#live-dashboard-error').slideUp();
$('#vol-error').slideUp();
$('#email-error').slideUp();
$('#live-dashboard-not-in-progress').slideUp();
if (data.event_status >= 0) {
$('#registered-volunteers').prepend(`
<div class="row"> \
<div class="left small-9 columns"> \
<p class="half-margin-top"> \
${new_firstname} \
${new_lastname} \
</p> \
</div> \
<div class="right small-3 columns"> \
<input {% if checkin_disabled %}disabled{% endif %} type="checkbox" id="vol-checkin-${userid}" name="vol-checkin-${userid}" value="${userid}" class="hidden checkin-checkbox"/> \
<label class="checkin-checkbox-icon" for="vol-checkin-${userid}"> \
<i class="fa fa-lg fa-check-circle"></i> \
</label> \
</div> \
</div> \
`)
// clear form inputs
$('#new-firstname').val('');
$('#new-lastname').val('');
$('#new-email').val('');
$('#invite-optin').attr("checked", true);
// bind new checkbox to checkin
$(`input[name='vol-checkin-${userid}']`).click(onCheckClick);
if (data.event_status == 1) {
$(`input[name='vol-checkin-${userid}']`).trigger('click')
} else {
$('#live-dashboard-not-in-progress').slideDown();
}
}
else {
$('#new-firstname').val('');
$('#new-lastname').val('');
$('#new-email').val('');
$('#invite-optin').attr("checked", true);
$('#vol-exist').slideDown();
}
}).fail( function (data) {
// console.log('register_live error:')
// console.log(data);
$('#live-dashboard-error').slideDown();
});
}).fail(function (data) {
// console.log('signup error:')
// console.log(data);
$('#live-dashboard-error').slideDown();
});
}
});

AJAX - Complex user activation for login

Now this may sound complicated but I have a page called activation.php where after the user has registered using my reg.php page, they get sent an email with their activation link - activation.php then a get method of k to make activation.php?k=activation-code-here
I made it so it returns the status of the activation, e.g - success of error.
On my reg.php page, I want to make it so it uses ajax to open a sweetAlert popup saying 'Activation Success'. It will get the popup depending on if the users 'activ_status' changed from 0 to 1 in the database when they access the activation.php page with a correct activation key.
Here is my code :
Activation.php
<?php
include('inc/conf/db_.php');
$result = '';
if(empty($_GET['k']) || (!$_GET['k']))
{
header('Location: login.php');
exit();
$result = 'Hacker Tried Accessing Auth Page';
}
$key = mysqli_real_escape_string($con,$_GET["k"]);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php
if (!empty($key))
{
$query = "SELECT * FROM users WHERE activ_key = '$key'";
$result = mysqli_query($con,$query) or die('error');
if (mysqli_num_rows($result))
{
$row = mysqli_fetch_array($result);
if ($row['activ_status']!='1')
{
$query = "update users set activ_status='1' where activ_key='$key'";
$result = mysqli_query($con,$query) or die('error');
$result = 'Successfuly Activated, Return To Your Other Page.';
}
else
{
$result = "Account Already Activated";
}
}
else
{
$result = 'Invalid Access Token';
}
}
else
{
$result = 'Error';
}
?>
<?php include('inc/login_header.php'); ?>
<div class="accountbg"></div>
<div class="wrapper-page">
<div class="panel panel-color panel-primary panel-pages">
<div class="panel-body">
<br>
<center><div id="result"></center>
<br>
<h3 class="text-center m-t-0 m-b-30"> <span class=""><?php echo site_settings('site_name'); ?></h3>
<h4 class="text-muted text-center m-t-0"><b>Activation Status</b></h4>
<br>
<center><img src="assets/images/loading.gif"></center>
<br>
<center><div class="alert alert-info"><button type="button" class="close"></button><?php echo $result; ?></div></center>
<?php return $result; ?>
</body>
</html>
My reg.php page
<?php
include('inc/conf/db_.php');
if (session_status() == PHP_SESSION_ACTIVE) {
session_start();
}
if(isset($_SESSION['user_i']) || isset($_SESSION['login'])) {
header('Location: index.php');
exit();
}
else if (session_status() == PHP_SESSION_NONE) {
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link href="assets/plugins/bootstrap-sweetalert/sweet-alert.css" rel="stylesheet" type="text/css">
<?php include('inc/login_header.php'); ?>
<div class="accountbg"></div>
<div class="wrapper-page">
<div class="panel panel-color panel-primary panel-pages">
<div class="panel-body">
<center><img src="assets/images/loading.gif" id="loading-image" style="display:none"/></center>
<h3 class="text-center m-t-0 m-b-30"> <span class=""><?php echo site_settings('site_name'); ?></h3>
<h4 class="text-muted text-center m-t-0"><b>Sign Up</b></h4>
<form id="registered_form" class="form-horizontal m-t-20">
<div class="form-group has-feedback">
<div class="col-xs-12"> <input class="form-control" name="email" type="email" required="" placeholder="Email"></div>
<span class="fa fa-envelope form-control-feedback text-muted" style="margin-top: 3%;"></span>
</div>
<div class="form-group has-feedback">
<div class="col-xs-12"> <input class="form-control" name="username" type="text" required="" placeholder="Username"></div>
<span class="fa fa-user form-control-feedback text-muted" style="margin-top: 3%;"></span>
</div>
<div class="form-group has-feedback">
<div class="col-xs-12"> <input class="form-control" name="password" type="password" required="" placeholder="Password"></div>
<span class="fa fa-lock form-control-feedback text-muted" style="margin-top: 3%;"></span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LeGFxYUAAAAAOqjyovTS3H0D1HS4IBgoHMvG4y_"></div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="checkbox checkbox-primary" style="text-align: center;"> <input type="checkbox" name="checkbox" value="agree"> <label for="checkbox-signup"> I accept Terms and Conditions </label></div>
</div>
</div>
<div class="form-group text-center m-t-20">
<div class="col-xs-12"> <button class="btn btn-primary w-md waves-effect waves-light" type="submit" id="reg_button" style="width: 100%;" >Register</button></div>
</div>
<div class="form-group m-t-30 m-b-0">
<div class="col-sm-12 text-center"> Already have an account?</div>
</div>
</form>
</div>
</div>
</div>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="assets/js/jquery.validate.js"></script>
<script src="assets/plugins/bootstrap-sweetalert/sweet-alert.min.js"></script>
<script>
$(document).ready(function()
{
jQuery.validator.addMethod("noSpace", function(value, element)
{
return value.indexOf(" ") < 0 && value != "";
}, "Spaces are not allowed");
$("#registered_form").submit(function()
{
if ($("#registered_form").valid())
{
$('#loading-image').show();
var data1 = $('#registered_form').serialize();
$.ajax({
type: "POST",
url: "inc/pgs/register.php",
data: data1,
success: function(msg)
{
$('#loading-image').hide();
console.log(msg);
if(msg == '')
{
swal({
title: "Registration Success!",
text: "Your registration was successful! Check your email and click on your activation link to be able to access your account. NOTE: Keep this page open",
type: "success",
timer: 15000,
showConfirmButton: false
});
}
else
{
swal("Registration Error!", msg, "error");
}
}
});
$.ajax({
type: "GET",
url: "activation.php",
data: data1,
success: function(msg)
{
if(msg == 'Successfuly Activated, Return To Your Other Page.')
{
swal({
title: "Activation Success",
text: "You can now login!",
type: "success",
timer: 15000,
showConfirmButton: false
});
}
}
});
}
return false;
});
});
</script>
</body>
</html>
<?php } ?>
I found a piece of code that might help me. It doesn't seem to be loading the modal up though:
$.ajax({
url: 'activation.php',
type: 'GET',
dataType: 'jsonp',
cache: 'false',
timeout: 32000,
success: function(data) {
if(data == 'Successfuly Activated, Return To Your Other Page.')
{
swal("Activation Completed!", "You can now login using the link at the bottom of the page - Already have an account?", "success")
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[refresh]: " + textStatus);
console.log(jqXHR);
ajaxCall();
},
});
Please clearly explain the problem you are having that is preventing the code from working as you intend.
If my interpretation is correct, you want to update the registration page that user keeps open while activating in another window, and then reflect the change on the registration page using AJAX. In fact, in this case you want to send data from the server to your client (you want something to change when a change happens on the server in the database). In this case, a simple solution is to repeatedly request the status (for instance every 2 seconds) using setTimeout. Other solutions exist but are probably overkill, such as long polling or web sockets.

Resources