Google Calendar API V3 insert event method - javascript

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>

Related

Send Email and Insert from the same form

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");
?>

Combining two or more submit buttons into one

I have submit buttons for different section of the webpage. The submit button is used to update the forms and database with the text value in the form fields. Currently, each submit button updates the forms (tied to their respective PKEY id, "consideration_no") only in their own sections. I want to update all the sections forms with one button click.
As you can see from the code below, there are 2 submit buttons. I have tried to link two together through IDs but it did not work for me.
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$question = $answer = "";
$question_err = $answer_err = "";
if(isset($_POST["dg_no"]) && !empty($_POST["dg_no"])){
//counter for array
$counter = 0;
// Get hidden input value
$dg_no = $_POST['dg_no'];
$consideration_no = $_REQUEST['consideration_no'];
$answer = $_POST['answer'];
// Check input errors before inserting in database
if(empty($answer_err)){
// Validate address address
$input_answer = trim($_POST["answer"]);
if(empty($input_answer)){
$answer_err = "Please enter an answer.";
} else{
$answer = $input_answer;
$answer1[$counter] = $input_answer;
}
// Prepare an Submit statement
$sql = 'Update "PDPC".consideration SET answer=:answer WHERE consideration_no = :consideration_no';
if($stmt = $pdo->prepare($sql)){
$stmt->bindParam(":answer", $param_answer);
$stmt->bindParam(":consideration_no", $param_consideration_no);
//$stmt->bindParam(":dg_no", $param_dg_no);
//Set Parameter in while loop, hence new set of parameter for every new form is created and executed.
//Could change the counter loop to a dynamic loop with foreach array.
while ($counter<15){
$param_answer = $answer[$counter];
$param_consideration_no = $consideration_no[$counter];
$stmt->execute();
//$param_dg_no = $dg_no;
// Attempt to execute the prepared statement
//debugggggg
/* $message = $consideration_no[$counter];
$message1 = $answer[$counter];
$message2 = 'lol';
echo "<script type='text/javascript'>alert('$message, $message1, $message2 ');</script>"; */
$counter++;
//apparently redirecting can be placed in the loop, and fields will still get changed.
//header("location: home1.php?dm_no=".$_GET["dm_no"]);
header("location: home1.php?dm_no=".$_GET["dm_no"]);
}
}
if($stmt->execute()){
//Records Submitd successfully. Redirect to landing page
header("location: home1.php?dm_no=".$_GET["dm_no"]);
exit();
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
unset($stmt);
}
// Close connection
unset($pdo);
} else{
/* --- DISPLAY/READ TABLE, SEE SECTIONS AND ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
// Check existence of dg_no parameter before processing further
if(isset($_GET["dg_no"]) && !empty(trim($_GET["dg_no"]))){
// Get URL parameter
$dg_no = trim($_GET["dg_no"]);
// Prepare a select statement
$sql = 'SELECT * FROM "PDPC".consideration WHERE (dg_fkey = :dg_no AND code_no = 1) ORDER BY consideration_no';
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":dg_no", $param_no);
// Set parameters
//$param_no = $dg_no;
$param_no = trim($_GET["dg_no"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() > 0){
SubSection($subsection1_1); //Consent Collection Subsection
while($row = $stmt->fetch()){
// Retrieve individual field value
$consideration_no = $row["consideration_no"];
$question = $row["question"];
$answer = $row["answer"];
$dg_no = $_GET['dg_no'];
//...time to show the questions and answers with the while loop...
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
}
//...after the loop, show the Submit and Cancel button, coz we only need 1 set each section.
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
}
}
else{
echo "Oops! Something went wrong. Please try again later.";
}
}
Section($section2); //Collection section
// Prepare a select statement
$sql = 'SELECT * FROM "PDPC".consideration WHERE (dg_fkey = :dg_no AND code_no = 2) ORDER BY consideration_no';
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":dg_no", $param_no);
// Set parameters
//$param_no = $dg_no;
$param_no = trim($_GET["dg_no"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() > 0){
SubSection($subsection2); //Consent Collection Subsection
while($row = $stmt->fetch()){
// Retrieve individual field value
$consideration_no = $row["consideration_no"];
$question = $row["question"];
$answer = $row["answer"];
$dg_no = $_GET['dg_no'];
//...time to show the questions and answers with the while loop...
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
}
//...after the loop, show the Submit and Cancel button, coz we only need 1 set each section.
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
}
}
else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
unset($stmt);
// Close connection
unset($pdo);
}
else{
// URL doesn't contain dg_no parameter. Redirect to error page
header("location: error.php");
exit();
}
}
I want it to update all the fields, in different sections, with one submit button
your code was bit difficult to read, but from what i understood you are trying to combine two or more form submissions into one. It's quiet simple
<form method="POST" action="save.php">
<input type=text name=name[] />
<input type=text name=name[] />
</form>
by using the [] to identify the input element you can have multiple values with the same name where you can access them from the PHP script as an array.
For example the above example will produce an array as follows
<?php
print_r($_POST['name']); //("name" => Array....
is this clear enough for you? if not drop a comment, i will explain more. As a side note i do recommend you look into using template engine, and also a framework in your coding project.
Here's what I see when i separate the html into a new file. I tried to remove the excess forms but when I open the last collapsible section, it instantly executes a submit action and brings me back to the home page.
<button class="collapsible"><?php echo $section ?></button>
<div class="content">
<button class="collapsible"><?php echo $subsection ?></button>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<?php
//while loop start
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
//while loop ends
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
//while loop start
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
//while loop ends
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php

Ajax : function is not working

I don't know why my code does not work onclick, but there is no pop up. The AJAX function var phone and id got data, but the AJAX did not. Is there anything wrong with the script? Does the AJAX need a jQuery library?
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"></script>
<script type="text/javascript">
function clickButton() {
var phone = document.getElementById('phone').value;
var id = document.getElementById('id').value;
$.ajax({
type: "post",
url: "userDetaiAjax.php",
data: {
'phone': phone,
'id': id
},
cache: false,
success: function(html) {
alert('Data Send');
$('#msg').html(html);
}
});
return false;
}
</script>
<div class="col">
<div class="form-group">
<h6>
<label>Name :</label>
<?php echo $name ?>
</h6>
<h6>
<label>Email :</label>
<?php echo $email ?>
</h6>
<input type="" name="phone" id="phone">
<input type="" name="id" id="id" value="<?php echo $_SESSION[" staff_id "];?>" hidden>
<h6>
<label>Phone :</label>
<?php echo $phone ?>
</h6>
<input type="submit" name="aa" value="submit2" onclick="return clickButton();">
</form>
<p id="msg"></p>
</div>
</div>
</div>
</div>
for the url
<?php
$phone = $_POST['phone'];
$id = $_POST['id'];
echo 'success';
echo $phone;
echo $id;
$a='"USR_ID"';
$b='"phone"';
include 'conn.php';
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$query = "update usr_web SET phone=:c1 WHERE usr_id=:c2";
$stid = oci_parse($conn, $query);
oci_bind_by_name($stid, ":c1", $phone);
oci_bind_by_name($stid, ":c2", $id);
$result = oci_execute($stid);
oci_free_statement($stid);
oci_commit($conn);
oci_close($conn);
echo $result;
?>
When you open the console of your browser you should see an error message like "ReferenceError: $ is not defined". So it seems that $ is not part of core.js which you have loaded. Just load the full version (https://code.jquery.com/jquery-3.3.1.min.js) and it should work.
U have error in your console:
$ is not defined
Which mean u did not include jquery, so u should add this code after ajax include:
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
U can chack your console errors with F12 key in browser and tab Console.

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.

php echo codeigniter into javascript array

I have this bit of code in my codeigniter view:
<script>
var content = [];
content[<?php echo $storageItem["id"]; ?>] = "<?php echo form_open("/account/edititem", array("class" => "form-inline"), array("id" => $storageItem["id"], "item_loc" => "inventory", "acctid" => $acct_data->account_id)); ?>
<div class="panel-body">
<div class="row">
<div class="col-xs-2">
<strong>Refine level:</strong> <input type="number" name="refine" class="form-control" value="<?php echo $storageItem["refine"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> />
</div>
<div class="col-xs-2">
<strong>Broken?:</strong> <input type="checkbox" name="attribute" class="form-control" value="1" <?php if ($storageItem["attribute"] == 1) { echo "checked"; } if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "disabled"; } ?> />
</div>
<div class="col-xs-2">
<strong>Bound?:</strong> <input type="checkbox" name="bound" class="form-control" value="1" <?php if ($storageItem["bound"] == 1) { echo "checked"; } ?> />
</div>
</div>
<br />
<div class="row">
<div class="col-xs-2">
<strong>Card 1:</strong> <input type="number" name="card0" class="form-control" value="<?php echo $storageItem["card0"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br>
</div>
<div class="col-xs-2">
<strong>Card 2:</strong> <input type="number" name="card1" class="form-control" value="<?php echo $storageItem["card1"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br>
</div>
<div class="col-xs-2">
<strong>Card 3:</strong> <input type="number" name="card2" class="form-control" value="<?php echo $storageItem["card2"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br>
</div>
<div class="col-xs-2">
<strong>Card 4:</strong> <input type="number" name="card3" class="form-control" value="<?php echo $storageItem["card3"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br>
</div>
</div>
<?php echo form_close(); ?>
</div>";
</script>
I create array named 'content' in javascript and then need to stuff almost an entire form into it to be able to create a child row in DataTables.
( for more information regarding what I've been trying to do and where these variables come from, see Datatables child row with PHP data from Codeigniter )
I've tried escaping single and double quotes (PHP complains about this), json_encode (PHP also complains about this as I still need the quotes and PHP interprets the quotes as the end of the json_encode), I've tried surrounding the entire value of the javascript array with '"' and "'", I've tried surrounding every line with ' '+ without success as well. How do I get this entire string into a form where javascript and PHP will parse it correctly and neither of them freak out?
Look at what you're doing:
<script>
var content = [];
content[<?php [..snip..] ?>] = "<?php [..snip..] ?>
^---start of javascript string
<div class="panel-body">
^---end of javascript string
^---start of another string
That means you have essentially:
variable = "some string stuff"variable-variable"more string stuff"
which is outright illegal JS.
The specific fix is to ESCAPE all of the strings in that html:
<script>
yadayada
<div class=\"panel-body\"> yada yadayada
^-----------^
But that doesn't fix the fact that this is incredibly bad code. You shouldn't be dumping loads of html into a JS string, and you should never be directly echoing text from PHP into a JS context.
If nothing else, why not generate all the content in PHP, then dump it all out as json?
<?php
$data = "blah blah blah blah";
?>
<script>
var content = <?php echo json_encode($data); ?>;

Categories

Resources