Send Email and Insert from the same form - javascript

I have a page where I have this form that sends the data in an email.
I want that when I click the submit button, other than sending the data through email, I want to send the data in a page where I have an INSERT script.
Here's the code of my page:
<!doctype html>
<html lang="en">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<?php
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/config.php';
session_start();
if (!empty($_SESSION['_contact_form_error'])) {
$error = $_SESSION['_contact_form_error'];
unset($_SESSION['_contact_form_error']);
}
if (!empty($_SESSION['_contact_form_success'])) {
$success = true;
unset($_SESSION['_contact_form_success']);
}
?>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Appointmenta</title>
<!-- reCAPTCHA Javascript -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 offset-md-2">
<div class="card mt-5">
<div class="card-body">
<h1 class="card-title">
Add an Appointment
</h1>
<?php
if (!empty($success)) {
?>
<div class="alert alert-success">Message sent successfully.</div>
<?php
}
?>
<?php
if (!empty($error)) {
?>
<div class="alert alert-danger"><?= $error ?></div>
<?php
}
?>
<?php $Field1= $_POST['Field1']; ?>
<?php $Field2= $_POST['Field2']; ?>
<?php $Field3= $_POST['Field3']; ?>
<?php $Field4= $_POST['Field4']; ?>
<?php $Field5= $_POST['Field5']; ?>
<?php $Field6= $_POST['Field6']; ?>
<?php $Field7= $_POST['Field7']; ?>
<?php $Field8= $_POST['Field8']; ?>
<?php $Field9= $_POST['Field9']; ?>
<form id="target" method="post">
<div class="form-group">
<label for="name">Field 1</label>
<input type="text" name="Field1" id="Field1" class="form-control"
value="<?php echo $Field1?>">
</div>
<div class="form-group">
<label for="subject">Field 2</label>
<input type="text" name="Field2" id="Field2" class="form-control"
value="<?php echo $Field2?>">
</div>
<div class="form-group">
<label for="email">Field 3</label>
<input type="text" name="Field3" id="Field3" class="form-control"
value="<?php echo $Field3?>">
</div>
<div class="form-group">
<label for="subject">Field 4</label>
<input type="text" name="Field4" id="Field4" class="form-control"
value="<?php echo $Field4?>">
</div>
<div class="form-group">
<label for="subject">Field 5</label>
<input type="text" name="Field5" id="Field5" class="form-control"
value="<?php echo $Field5?>">
</div>
<div class="form-group">
<label for="subject">Field 6</label>
<input type="text" name="Field6" id="Field6" class="form-control"
value="<?php echo $Field6?>">
</div>
<div class="form-group">
<label for="subject">Field 7</label>
<input type="text" name="Field7" id="Field7" class="form-control"
value="<?php echo $Field7?>">
</div>
<div class="form-group">
<label for="subject">Field 8</label>
<input type="text" name="Field8" id="Field8" class="form-control"
value="<?php echo $Field8?>">
</div>
<div class="form-group">
<label for="message">Field 9</label>
<input type="text" name="Field9" id="Field9" class="form-control"
value="<?php echo $Field9?>">
</div>
<div class="form-group text-center">
<div align="center" class="g-recaptcha" data-sitekey="<?= CONTACTFORM_RECAPTCHA_SITE_KEY ?>"></div>
</div>
<button "name="submit" class="btn btn-primary btn-block"> Send Email</button>
</form>
<form action="../list.php">
<p><br></p>
<button class="btn btn-primary btn-block">Return home.</button>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script language="Javascript">
<!--
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
method: 'POST',
url: 'submit.php',
data: $( this ).serialize()
});
});
-->
</script>
When I click on 'Send Email' nothing happens.
**I want to click 'Send Email' and see the message 'Message sent successfully'. At the same time I want that same data to be sent to appointment.php, which inserts the data into a table. I'd prefer that 'appointment.php' doesn't even open, I want to stay on index.php when I click 'Send Email'**
Code of submit.php
<?php
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/functions.php';
require_once __DIR__.'/config.php';
session_start();
// Basic check to make sure the form was submitted.
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
echo "The form must be submitted with POST data.";
exit();
}
require "appointment.php";
// Do some validation, check to make sure the name, email and message are valid.
if (empty($_POST['g-recaptcha-response'])) {
echo "Please complete the CAPTCHA.";
}
$recaptcha = new \ReCaptcha\ReCaptcha(CONTACTFORM_RECAPTCHA_SECRET_KEY);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_REQUEST['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$errors = $resp->getErrorCodes();
$error = $errors[0];
$recaptchaErrorMapping = [
'missing-input-secret' => 'No reCAPTCHA secret key was submitted.',
'invalid-input-secret' => 'The submitted reCAPTCHA secret key was invalid.',
'missing-input-response' => 'No reCAPTCHA response was submitted.',
'invalid-input-response' => 'The submitted reCAPTCHA response was invalid.',
'bad-request' => 'An unknown error occurred while trying to validate your response.',
'timeout-or-duplicate' => 'The request is no longer valid. Please try again.',
];
$errorMessage = $recaptchaErrorMapping[$error];
echo "Please retry the CAPTCHA: ".$errorMessage;
}
// Everything seems OK, time to send the email.
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = CONTACTFORM_PHPMAILER_DEBUG_LEVEL;
$mail->isSMTP();
$mail->Host = CONTACTFORM_SMTP_HOSTNAME;
$mail->SMTPAuth = true;
$mail->Username = CONTACTFORM_SMTP_USERNAME;
$mail->Password = CONTACTFORM_SMTP_PASSWORD;
$mail->SMTPSecure = CONTACTFORM_SMTP_ENCRYPTION;
$mail->Port = CONTACTFORM_SMTP_PORT;
// Recipients
$mail->setFrom(CONTACTFORM_FROM_ADDRESS, CONTACTFORM_FROM_NAME);
//$mail->addAddress(CONTACTFORM_TO_ADDRESS, CONTACTFORM_TO_NAME);
//$mail->addAddress(CONTACTFORM2_TO_ADDRESS, CONTACTFORM2_TO_NAME);
$mail->addAddress(CONTACTFORM3_TO_ADDRESS, CONTACTFORM3_TO_NAME);
//$mail->addAddress(CONTACTFORM4_TO_ADDRESS, CONTACTFORM4_TO_NAME);
//$mail->addReplyTo("marketing#lgp-italia.it");
// Content
$mail->Subject = "Appointment at ".$_POST['Field1'];
$mail->Body = <<<EOT
Appointment at: {$_POST['Field1']}, {$_POST['Field2']}
{$_POST['Field3']}
{$_POST['Field4']}
{$_POST['Field5']}
{$_POST['Field6']}
{$_POST['Field7']}
EOT;
$mail->send();
} catch (Exception $e) {
echo "An error occurred while trying to send your message: ". $mail->ErrorInfo;
}
Code of appointment.php
<?php
if (isset($_POST['submit'])) {
require "../../../security/config.php";
require "../../../security/common.php";
try {
$connection = new PDO($dsn, $username, $password, $options);
$new_call = array(
"Field1" => $_POST['Field1'],
[...]
);
echo var_dump("1");
$sql = sprintf(
"INSERT INTO %s (%s) values (%s)",
"db.appointments",
implode(", ", array_keys($new_call)),
":" . implode(", :", array_keys($new_call))
);
echo var_dump("2");
$statement = $connection->prepare($sql);
$statement->execute($new_call);
echo var_dump("3");
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
echo var_dump("4");
}
echo var_dump("5");
?>

Related

Fill html input from sql query using button in PHP

I have 2 inputs with name and surname, from a database I bring all the values ​​and when pressing a button on the form I would like the inputs to be completed with the data. When there is no data left to show, it should throw a warning. I leave the code of what I have done so far.
<?php
function customersData(){
try {
$pdo = conect();
$sql = "Select CTE_LASTNAME,CTE_NAME
From customers
Where id_store= 1150";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$usuarios = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $customers;
} catch(PDOException $e) {
echo 'Error: '.$e->getMessage();
}
}
$data=customersData();
?>
<html>
<body>
<form>
<div class="form-group">
<div class="col-xs-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="ficha">
</div>
<div class="mb-3">
<label for="lastname" class="form-label">Lastname</label>
<input type="text" class="form-control" id="ficha">
</div>
</div>
<button type="submit" class="btn btn-primary" id="btnData">Show Data</button>
</form>
<script>
var btnData = document.getElementById("btnData");
btnData.addEventListener("click",function(e){
e.preventDefault();
});
</script>
</body>
</html>
You probably want to use Ajax, I added JQuery to simplify it.
Try it, and manage your id_store variable.
<?php
function customersData($id) {
try {
$pdo = conect();
$sql = "Select CTE_LASTNAME,CTE_NAME
From customers
Where id_store=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id]);
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'Error: '.$e->getMessage();
}
}
if (!empty($_GET["get_data"])) {
$data = customersData(intval($_GET["get_data"]));
echo json_encode($data);
exit();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"></script>
</head>
<body>
<form>
<div class="form-group">
<div class="col-xs-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name">
</div>
<div class="mb-3">
<label for="lastname" class="form-label">Lastname</label>
<input type="text" class="form-control" id="lastname">
</div>
</div>
<button type="button" class="btn btn-primary" id="btnData">Show Data</button>
</form>
<script>
$("#btnData").click(function (ev) {
$.get(window.location.href, {
"get_data": 1150
}, function (result) {
let obj = JSON.parse(result);
$("#name").val(obj.CTE_NAME);
$("#lastname").val(obj.CTE_LASTNAME);
});
});
</script>
</body>
</html>

I have a comment form in fullpost.php and the inserting form is in sql.php, how do I get post_id for my comments table?

I have my comment form in fullpost page and I am proccessing a form using ajax, but I don't know how to insert post_id in my comments table to specify the post comment. Kindly help
as I am trying to get the get_id in sql.php but I'm gettng an error which shows undefined post_id in line 13 sql.php
Please find my code below:
fullpost.php
?php
ob_start();
require_once('includes/header.php'); ?>
<?php
$db = new Database();
if(isset($_GET['id'])){
$id = $_GET['id'];
$query = "SELECT * FROM posts WHERE post_id ='$id'";
$post = $db->select($query);
}
$c_query = "SELECT * FROM comments WHERE post_id='$id' ORDER BY comment_id DESC";
$c_run = $db->select($c_query);
?>
<div class ="col-8">
<div class="content-area">
<?php if($post):?>
<?php while($row = $post->fetch_array()):?>
<h2 class="title-full-post"><?php echo $row['title'];?></h2>
<p class="content-area-auth"><?php echo formatDate($row['created_date']);?> By
<a class="content-area-author" href=""><?php echo $row['author']; ?></a></p>
<img class="post-img" src="assets/images/<?php echo $row['image']; ?>">
<p class="content-area-body"><?php echo $row['body'];?><br /><br /><br />
</p>
<?php endwhile; ?>
<?php endif; ?>
<div class="comment">
<h2>Recent Comments</h2>
<?php
if($c_run):
while($r = $c_run->fetch_assoc()):
?>
<p><?php echo $r['name']; echo $r['date']; ?></p>
<p><?php echo $r['comment']; ?></p>
<!--<input type='button' name='reply' id='reply' value='Reply' onclick='replyComment("<?php echo $message_id?>")' />-->
<hr>
<?php
endwhile;
endif;
?>
</div>
<div class="comments-area" id="editbutton">
<h2>Comment Below</h2>
<form action="fullpost" id ="commentForm" method="post" class="form-commment">
<input type="hidden" name="commentId" value="<?php echo $id ?>">
<label for="">Name</label><span style="color: red;">*</span>
<input type="text" name="name" id="commentName" class="form-control-comment" placeholder="Type your Name..">
<label for="">Email</label>
<input type="Email" name="email" id="commentEmail" class="form-control-comment" placeholder="Type your Email..">
<label for="">Website</label>
<input type="text" name="website" id="commentWebsite" class="form-control-comment" placeholder="Type your Website..">
<label for="">Comment</label>
<textarea name="comment" id="commentMessage" class="form-control-comment form-text-area">Comment ...</textarea>
<input type="submit" id="submitComment" name="submitComment" class="btn-comment" value="Post Comment">
<span id="errorMessage"></span>
<span id="successMessage"></span>
</form>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#commentForm").submit(function(event){
event.preventDefault();
var commentName = $("#commentName").val();
var commentEmail = $("#commentEmail").val();
var commentWebsite = $("#commentWebsite").val();
var commentMessage = $("#commentMessage").val();
if(commentName == '' || commentEmail == '' || commentMessage == '' ){
$("#errorMessage").html("Fill all the required fields");
} else{
$("#errorMessage").html('');
$.ajax({
url: "sql.php",
type: "POST",
async: false,
data:{
"done": 1,
"username": commentName,
"useremail": commentEmail,
"userwebsite": commentWebsite,
"usercomment": commentMessage,
"commentId": commentId
},
success: function(data){
//$("#name").val('');
//$("#message").val('');
$("form").trigger("reset");
$("#successMessage").fadeIn().html(data);
}
});
}
});
});
</script>
</div><!--End of Content Area-->
</div><!--end of col-8-->
<?php require_once('includes/footer.php'); ?>
<!--- this is sql.php-->
<?php
require_once('config/config.php');
require_once('libraries/database.php');
require_once('helpers/format_helpers.php');
//require_once('includes/header.php');
//$conn= new mysqli('localhost','root','','myblog');
$db = new Database();
//$id = $_GET['id'];
/*Insert comments*/
if(isset($_POST['done'])){
$name = mysqli_real_escape_string($db->link, $_POST['username']);
$email = mysqli_real_escape_string($db->link, $_POST['useremail']);
$website = mysqli_real_escape_string($db->link, $_POST['userwebsite']);
$comment = mysqli_real_escape_string($db->link, $_POST['usercomment']);
$postId = mysqli_real_escape_string($db->link, $_POST
['commentId']);
if(!empty($name && $email && $comment)){
// $conn= new mysqli('localhost','root','','myblog');
$i_query ="INSERT INTO comments(name, email, website, comment, post_id)VALUES('$name','$email','$website','$comment','$postId')";
$insert_query =$db->insert($i_query);
if($insert_query){
echo "Comment has been submitted and waiting for approval..";
} else{
$error_message ="Please try again..comment not submitted";
}
} else{
$error_message ="All(*)Fields Are required";
}
}
Any assistance would be greatly appreciated
You can use mysql_insert_id() to return the last ID generated my MySQL.
If you show your Database class I can give you an example.

How to display success popup message after clicking on submit button in codeigniter php

Displaying a custom popup message as thank you after clicking on submit button.I have used codeigniter framework.I have a section as request form once the user filled the data and clicked on submit button a pop up message should be displayed on that section as thank you message.Here is my code.
<div class="col-md-3 requestfree">
<img src="<?= base_url(); ?>theme/images/icon1.png" class="requesting">
<h3 class="request">REQUEST</h3>
<h5 class="free"> FREE QUOTE</h5>
<h5 class="receive">You will receive quote within 24 hours</h5>
<form name="contact" id="contactform" enctype="multipart/form-data" method="post" action="<?php echo base_url();?>welcome/request">
<?php if (isset($msg)): ?>
<?= $msg; ?>
<?php endif; ?>
<div class="name"><span class="mandatory"></span>
<input type="text" class="form-control" name="name" placeholder="Name" required>
<?= form_error('name', '<div class="error">', '</div>'); ?>
</div>
<div class="name">
<input type="text" class="form-control" name="phone" placeholder="Phone" required>
<?= form_error('phone', '<div class="error">', '</div>'); ?>
</div>
<div class="email">
<input type="email" class="form-control" name="email" placeholder="Email" required>
<?= form_error('email', '<div class="error">', '</div>'); ?>
</div>
<div class="description">
<textarea name="description" style="width:100%;overflow:auto;" placeholder="Description" required></textarea>
</div>
<div class="">
<div class="captchas">
<img src="captcha.php?rand=<?= rand(); ?>" class="captchass" id='captchaimg'/>
<p class="change">click to change</p>
</div>
<div class="captcha">
<input type="text" class="form-control"id="captcha_code" name="captcha_code" style="background-color: #EAD5D2;border: none;">
</div>
</div>
<button type="submit" class="btn btn-success" onclick="return validate();">Submit</button>
<p class="privacy">We respect your privacy</p>
</form>
</div>
Controller:
function request()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<br /><span class="error"> ','</span>');
$this->form_validation->set_rules('name','First Name' , 'required');
$this->form_validation->set_rules('email','Email','required|valid_email');
$this->form_validation->set_rules('phone','Mobile Number','required|numeric');
$this->form_validation->set_rules('description','Description','required');
if($this->form_validation->run()== FALSE)
{
$data['mainpage']='index';
$this->load->view('templates/template',$data);
}
else
{
echo "hi";
//get the form data
$name = $this->input->post('name');
$from_email = $this->input->post('email');
$phone = $this->input->post('phone');
$description = $this->input->post('description');
//set to_email id to which you want to receive mails
$to_email = 'gmail#gmail.com';
$config=Array(
'protocol'=> 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com', //smtp host name
'smtp_port' => '465', //smtp port number
'smtp_user' => 'mail#gmail.com',
'smtp_pass' => '*******', //$from_email password
'mailtype' =>'html',
'newline' =>"\r\n",
'crlf' =>"\r\n",
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$message = array();
$message[] = 'Username : '.trim($name).' ';
$message[] = 'Phone Number : '.trim($phone).' ';
$message[] = 'Description : '.trim($description).' ';
$message = implode(PHP_EOL, $message);
//send mail
$this->load->library('email',$config);
$this->email->from($from_email);
$this->email->to($to_email);
$this->email->subject('Request Free Quote');
$this->email->message($message);
$this->email->set_newline("\r\n");
if ($this->email->send())
{
// mail sent
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Your mail has been sent successfully!</div>');
redirect('welcome');
}
else
{
//error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">There is error in sending mail! Please try again later</div>');
redirect('welcome');
}
}
}

PHP and HTML form mail send with javascript alert not working [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I have very limited knowledge. I tried my best to understand. I want to send mail from a contact form, upon success show an alert message and remain on the same page. the mail is not sending and seems likeI have some bugs in the code. kindly help.
<form action="" method="post">
<div class="col-md-6">
<input name="name" type="text" class="form-control" placeholder="Name">
</div>
<div class="col-md-6">
<input name="email" type=“text” class="form-control" placeholder="Email">
</div>
<div class="col-md-12">
<input name="subject" type="text" class="form-control" placeholder="Subject">
</div>
<div class="col-md-12">
<textarea name="message" class="form-control" placeholder="Message" rows="4"></textarea>
</div>
<div class="col-md-8">
<input type="submit" class="form-control text-uppercase" name="send" value="submit" />
</div>
</form>
<?php
if ($_POST['send']) {
$ToEmail = 'info#autonomousdata.com';
$EmailSubject = $_POST['subject'];
$mailheader = "From: ".$_POST['email']."\r\n";
$mailheader .= "Reply-To: ".$_POST['email']."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n" .
"X-Mailer: PHP/" . phpversion();
$MESSAGE_BODY = "Name: ".$_POST['name']."\n";
$MESSAGE_BODY .= "Email: ".$_POST['email']."\n";
$MESSAGE_BODY .= "Comment: ".$_POST['message']."";
if(mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader)!==true) {
?>
<script type='text/javascript'> alert('failed to send the mail'); </script>
<?php
die('Fail to send');
} else{
?>
<script type='text/javascript'>alert('Thank you for contacting us! All information received will always remain confidential. We will contact you as soon as we review your message.');
</script>
<?php
}
}
?>
The HTML form had dubious quotation marks around the type='text' and I modified the php to add some rudimentary checking of variables and also sanitisation ~ hope it will help.
<form action="" method="post">
<div class="col-md-6">
<input name="name" type="text" class="form-control" placeholder="Name">
</div>
<div class="col-md-6"><!-- // incorrect quotation used on `text` //-->
<input name="email" type='text' class="form-control" placeholder="Email">
</div>
<div class="col-md-12">
<input name="subject" type="text" class="form-control" placeholder="Subject">
</div>
<div class="col-md-12">
<textarea name="message" class="form-control" placeholder="Message" rows="4"></textarea>
</div>
<div class="col-md-8">
<input type="submit" class="form-control text-uppercase" name="send" value="submit" />
</div>
</form>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['subject'],$_POST['email'],$_POST['name'],$_POST['message'] ) ){
$to = 'info#autonomousdata.com';
$name = filter_input( INPUT_POST, 'name', FILTER_SANITIZE_STRING );
$subject = filter_input( INPUT_POST, 'subject', FILTER_SANITIZE_STRING );
$message = filter_input( INPUT_POST, 'message', FILTER_SANITIZE_STRING );
$email = filter_var( filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING ), FILTER_VALIDATE_EMAIL );
$headers=array();
$headers[]="From: {$email}";
$headers[]="Reply-To: {$email}";
$headers[]="Content-type: text/html; charset=iso-8859-1";
$headers[]="X-Mailer: PHP/" . phpversion();
/* generate final headers string */
$headers=implode( "\r\n", $headers );
$message=array();
$message[]="Name: {$name}";
$message[]="Email: {$email}";
$message[]="Comment: {$message}";
/* generate final message string */
$message=implode( "\n", $message );
$result=#mail( $to, $subject, $message, $headers );
switch( $result ){
case true:
$msg='Thank you for contacting us! All information received will always remain confidential. We will contact you as soon as we review your message.';
break;
case false:
$msg='failed to send the mail';
break;
}
echo "<script type='text/javascript'>alert('{$msg}');</script>";
}
?>
The test page, in it's entirety, that I set up to test the basic functionality of the script. As this was all run locally I cannot confirm whether the email would be sent - it looks correct however.
<?php
?>
<!doctype html>
<html>
<head>
<title>Basic Contact Form - investigating email send failure.</title>
<script type='text/javascript' charset='utf-8'></script>
<style type='text/css' charset='utf-8'>
form{
width:50%;
}
form,output,input[type='text'],textarea,input[type='button'],input[type='submit']{
display:block;
box-sizing:border-box;
padding:0.5rem;
margin:0.5rem;
}
output{
color:red;
}
input[type='text'],textarea{
width:60%;
}
</style>
</head>
<body>
<form action="" method="post">
<div class="col-md-6">
<input name="name" type="text" class="form-control" placeholder="Name">
</div>
<div class="col-md-6"><!-- // incorrect quotation used on `text` //-->
<input name="email" type='text' class="form-control" placeholder="Email">
</div>
<div class="col-md-12">
<input name="subject" type="text" class="form-control" placeholder="Subject">
</div>
<div class="col-md-12">
<textarea name="message" class="form-control" placeholder="Message" rows="4"></textarea>
</div>
<div class="col-md-8">
<input type="submit" class="form-control text-uppercase" name="send" value="submit" />
</div>
<output id='msgs'></output>
</form>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['subject'],$_POST['email'],$_POST['name'],$_POST['message'] ) ){
$to = 'info#autonomousdata.com';
$name = filter_input( INPUT_POST, 'name', FILTER_SANITIZE_STRING );
$subject = filter_input( INPUT_POST, 'subject', FILTER_SANITIZE_STRING );
$message = filter_input( INPUT_POST, 'message', FILTER_SANITIZE_STRING );
$email = filter_var( filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING ), FILTER_VALIDATE_EMAIL );
if( !$to or !$name or !$subject or !$message or !$email ){
echo "Error: one or more required variables are not available.";
} else {
$headers=array();
$headers[]="From: {$email}";
$headers[]="Reply-To: {$email}";
$headers[]="Content-type: text/html; charset=iso-8859-1";
$headers[]="X-Mailer: PHP/" . phpversion();
/* generate final headers string */
$headers=implode( "\r\n", $headers );
$message=array();
$message[]="Name: {$name}";
$message[]="Email: {$email}";
$message[]="Comment: {$message}";
/* generate final message string */
$message=implode( "\n", $message );
$result=#mail( $to, $subject, $message, $headers );
switch( $result ){
case true:
$msg='Thank you for contacting us! All information received will always remain confidential. We will contact you as soon as we review your message.';
break;
case false:
$msg='Failed to send the mail';
break;
}
/* Let the user know the status of the form submission somehow */
echo "
<script type='text/javascript'>
document.getElementById('msgs').innerHTML='{$msg}';
/*
alert('{$msg}');
*/
</script>";
}
}
?>
</body>
</html>

Google Calendar API V3 insert event method

I am trying to insert an event in google calendar using google calendar api v3.
I created add_event view in which form is display with various fields.
I am passing data to controller using post method to insert_event method.
I am receiving data but its not inserting an event.
I think problem in this line : if ($client->getAccessToken()) {
Someone explain me whats wrong?
welcome.php // CI controller
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index() {
echo 'Google Calendar API EXA';
//$this->load->view('welcome_message');
$this->load->view('add_event');
$this->load->helper('url');
error_reporting(E_ALL);
ini_set('display_errors', 'On');
//including google calendar api
set_include_path(get_include_path() . PATH_SEPARATOR . $_ENV['OPENSHIFT_REPO_DIR']);
include('application/libraries/google-api-php-client-exa/autoload.php');
include('application/libraries/google-api-php-client-exa/src/Google_Client.php');
include('application/libraries/google-api-php-client-exa/src/contrib/Google_CalendarService.php');
session_start();
if ((isset($_SESSION)) && (!empty($_SESSION))) {
echo "<br>".'There are cookies'."<br>";
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
}
$client = new Google_Client();
$client->setApplicationName("Test Product");
$client->setClientId('its secret');
$client->setClientSecret('its secret');
$client->setRedirectUri('https://googlecalendar-apiexa.rhcloud.com/');
$client->setDeveloperKey('its secret');
$client->setUseObjects(true);
$cal = new Google_CalendarService($client);
if (isset($_GET['logout'])) {
echo "<br><br><font size=+2>Logging out</font>";
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
echo "<br>Google APi= " . $_GET['code'];
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
echo "<br>I got the token = " . $_SESSION['token']; // <-- not needed to get here unless location uncommented
}
if (isset($_SESSION['token'])) {
echo "<br>".'Access Granted'."<br>";
$client->setAccessToken($_SESSION['token']);
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
echo "<br><br><font size=+2><a href=$url?logout>Logout</a></font>";
}
public function insert_event() {
$summary = $this->input->post('summary');
$location = $this->input->post('location');
$timezone = $this->input->post('timezone');
$start_time = $this->input->post('start_time');
$end_time = $this->input->post('end_time');
echo $timezone;
echo $client;
if ($client->getAccessToken()) {
echo 'here';
$calList = $cal->calendarList->listCalendarList();
echo "<pre>";
echo "<hr><font size=+1>I have access to your calendar</font>";
$event = new Google_Event();
$event->setSummary($summary);
$event->setLocation($location);
$start = new Google_EventDateTime();
$start->setTimeZone($timezone);
$start->setDateTime($start_time);
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setTimeZone($timezone);
$end->setDateTime($end_time);
$event->setEnd($end);
echo "<br>" . 'tests';
$createdEvent = $cal->events->insert('yuvraj.kumbhar#exateam.com', $event);
echo 'test5' . "<br>";
//echo $createdEvent->getId();
echo "</pre>";
echo "<br><font size=+1>Event created</font>";
echo "<hr><br><font size=+1>Already connected</font> (No need to login)";
} else {
//Request authorization
$authUrl = $client->createAuthUrl();
print "<hr><br><font size=+2><a href='$authUrl'>Connect Me!</a></font>";
print "Please visit:\n$authUrl\n\n";
/* print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken); */
}
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
//add_event.php // CI view
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<?php $this->load->helper('url'); ?>
<?php ?>
<div class="container-fluid">
<div class="row-fluid">
</div>
<?php //echo base_url();?>
<form method="post"
action="<?php echo base_url();?>index.php/welcome/insert_event"
name="add_event"
id="add_event"
role="form"
>
<div class="widget-box">
<div class="widget-title">
<h5>
Add Event
</h5>
</div>
<div class="control-group">
<label class="control-label"><span class="required">*</span>Summary</label>
<div class="controls">
<input type="text" id="summary" name="summary" value=" <?php echo (isset($summary)) ? $summary : '' ?>"/>
</div>
</div>
<div class="control-group">
<label class="control-label"><span class="required">*</span>Location</label>
<div class="controls">
<input type="text" id="location" name="location" value="<?php echo (isset($location)) ? $location : '' ?>"/>
</div>
</div>
<div class="control-group">
<label class="control-label"><span class="required">*</span>TimeZone</label>
<div class="controls">
<input type="text" id="timezone" name="timezone" value="<?php echo (isset($timezone)) ? $timezone : '' ?>"/>
</div>
</div>
<div class="control-group">
<label class="control-label"><span class="required">*</span>Start Time</label>
<div class="controls">
<input type="text" id="start_time" name="start_time" value="<?php echo (isset($start_time)) ? $start_time : '' ?>"/>
</div>
</div>
<div class="control-group">
<label class="control-label"><span class="required">*</span>End Time</label>
<div class="controls">
<input type="text" id="end_time" name="end_time" value="<?php echo (isset($end_time)) ? $end_time : '' ?>"/>
</div>
</div>
<br> <input type="submit" value="Add Event">
<!--<button type="button" class="btn btn-primary" name="<?php //echo (isset($submit_name)) ? $submit_name : '' ?>" onclick="handle_submit('<?php //echo $this->form_name ?>', '<?php //echo site_url($this->page_name . "/" . $submit_name) ?>');" value="<?php echo $submit_value; ?>">
<?php //echo $submit_value; ?> </button>-->
</div>
</form>
</div>

Categories

Resources