php echo codeigniter into javascript array - javascript

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

Related

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

Multiple Ajax Forms using Wordpress Loop

I am trying to make multiple Ajax forms work in a Wordpress loop. I have given the form and fields in each form a unique ID. I'm trying to reference each form within the javascript in order to submit the AJAX form but instead the page refreshes as if it's trying to submit the form using php. I am no expert and can't figure out how this works. The script works for an individual form as I can reference the actual form_id directly within the javascript. I want to be able to submit the form on each post within the loop without having to refresh the page. Thanks in advance for your help.
Javascript in the template that contains the loop.
<script>
var form_id = $(this).closest("form").attr('id');
form_id.validate({
highlight: function(element, errorClass, validClass) {
$(element).parent('label').addClass('errors');
},
unhighlight: function(element, errorClass, validClass) {
$(element).parent('label').removeClass('errors');
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: '<?php echo admin_url(); ?>admin-ajax.php',
data: form_id.serialize(),
beforeSend: function() {
$("input[name=submit],button", form).attr('disabled', 'disabled');
$("div.loading", form).show();
$("div.status", form).hide();
},
success: function(result) {
if (result == 1 || result == '1') {
$("div.loading", form).hide();
$("div.thanks").slideDown();
document.forms["leadForm"].reset();
} else {
$("div.loading", form).hide();
$("input[name=submit],button", form).removeAttr('disabled');
$("div.status", form).html(result).show();
}
}
});
}
});
</script>
The form within the loop.
<?php $pid = get_the_ID(); ?>
<form name="leadForm" method="post" id="leadForm-<?php echo $pid; ?>" action="#">
<div class="grid-x grid-padding-x">
<div class="medium-12 cell">
<textarea tabindex="2" rows="6" cols="30" maxlength="350" title="Please enter a message" name="message" id="message-<?php echo $pid; ?>" placeholder="Your message" ></textarea>
</div>
<div class="medium-6 cell">
<label>Full Name
<input type="text" placeholder="Full Name" class="required" autocomplete="off" name="fullname" id="fullname-<?php echo $pid; ?>" >
</label>
</div>
<div class="medium-6 cell">
<label>Email Address
<input type="email" placeholder="Email Address" class="required" autocomplete="off" name="email" id="email-<?php echo $pid; ?>" >
</label>
</div>
<div class="medium-12 cell">
<label>Phone Number
<input type="tel" placeholder="Phone Number" class="required" autocomplete="off" name="phone" id="phone-<?php echo $pid; ?>" >
</label>
</div>
<div class="medium-12 cell">
<button class="button submit radius expanded" type="submit" >Send</button>
<div class="loading" style="display:none;" >
<img src="<?php echo get_template_directory_uri(); ?>/images/progress.gif" alt="Loading..." />
</div>
<div class="status callout radius alert small" style="display:none; text-align:center;">There was an error sending your message.
</div>
<div class="thanks callout radius success small" style="display:none; text-align:center;">Thank you.
</div>
<input type="hidden" name="current_url" value="<?php echo the_permalink(); ?>" class="button" />
<input type="hidden" name="current_title" value="<?php echo the_title(); ?>" class="button" />
</div>
</div>
</form>
The php script within the Wordpress - functions.php
<?php
add_action('wp_ajax_nopriv_leadForm', 'core_leadForm');
add_action('wp_ajax_leadForm', 'core_leadForm');
function core_leadForm()
{
if (!((isset($_POST['fullname']) && !empty($_POST['fullname'])) && (isset($_POST['email']) && !empty($_POST['email'])) && (isset($_POST['phone']) && !empty($_POST['phone'])) && (isset($_POST['message']) && !empty($_POST['message'])) ))
{
echo 'Enter all fields';
}
else if (!is_email($_POST['email']))
{
echo 'Email is not valid';
}
else
{
if (function_exists('ot_get_option'))
{
//$to = ot_get_option('cont_email');
$to = 'email#website.com';
}
else
{
$to = '';
}
}
}
ob_start();
?>
<br>
<table>
<tr>
<td><b><u>CONTACT DETAILS</u></b><br>
<br></td>
<td> </td>
</tr>
<tr>
<td><b>Full Name:</b></td>
<td><?php echo $_POST['fullname'] ?></td>
</tr>
<tr>
<td><b>Phone Number:</b></td>
<td><?php echo $_POST['phone'] ?></td>
</tr>
<tr>
<td><b>Email Address:</b></td>
<td><?php echo $_POST['email'] ?></td>
</tr>
<tr>
<td><b>Link:</b></td>
<td><?php echo $_POST['current_title'] ?></td>
</tr>
<tr>
<td><b>Message:</b></td>
<td><?php echo $_POST['message'] ?></td>
</tr>
</table>
<?php
$message = ob_get_contents();
ob_end_clean();
$subject = 'NEW MESSAGE';
$headers[] = 'From: ' . $_POST["fullname"] . ' <' . $_POST["email"] . '>';
add_filter('wp_mail_content_type', 'core_html_content_type');
function core_html_content_type()
{
return 'text/html';
}
if (wp_mail($to, $subject, $message, $headers))
{
// echo "test";
echo 1;
}
else
{
echo 'Your message failed to send. Please try again.';
}
die();
?>
Hard to replicate all the issues that WP might have with your code. But it would be one of these:
this when used outside of an reference to an html object refers to window. .closest travels up the dom tree, not down, so it will not find forms within the window object. The same effect of what you want to achieve can be achieved by $('form').attr('id'), i.e. return the id of the 1st form found.
You need to ensure $ is defined before using, this is a WP quirk of using the shipped version of jquery, you substitute the word jQuery for $
I see no evidence that jQuery is loaded by the time you use it, you are also using another library, .validate, make use of $(document).ready();
Also on a side note, learn how to use the console (e.g. in chrome), you can output js here to test variables, any errors in your code will output here too.

Hide/Show toggle echo results in php

I am trying to toggle results i have echo'd out of table but i am having no luck.
I have tried the same code in HTML and it works perfectly.
Ive been working on this for a while now, and was wondering if someone could point me in the right direction.
What I've tired
Adding the javascript inside the php echo.
Adding a counter to the id, to make it unique on loop
Placing each line of the echo results in echo(""); tags.
adding a counter, to make the id unique on loop.
PHP
$i = 1;
while ($output = $fc_sel->fetch_assoc()) {
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name']; //echo out product name
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc']; //echo out product desc
echo"
<div id='first_product'>
<button onclick='toggle_visibility('tog')'>Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick='toggle_visibility('tog')'> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
";
}
}
JAVASCRIPT
<script>
//turn entire div into toggle
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block' || e.style.display == '')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
The single quotes in onclick='toggle_visibility('tog')' are conflicting with the outer single quotes. So either escape them or use double quotes in either the outer pair or the inner pair.
Then in PHP, remove the <?php echo. Just put the HTML in PHP. The echo only complicates things. If you need dynamic data in your HTML, just inject it at that place with <?php ... ?>. But so far I haven't seen any of that in your HTML: it is static.
Here is a working snippet, after having made that change in two places:
//turn entire div into toggle
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block' || e.style.display == '')
e.style.display = 'none';
else
e.style.display = 'block';
}
<div id='first_product'>
<button onclick="toggle_visibility('tog')">Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick="toggle_visibility('tog')"> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
Edit after modification of the question
The code in the question was extended so the HTML is produced in a loop now.
You should now take care to produce unique id values only. So you'll probably want to add <?=$i?> at several places, like this:
<?php
session_start();
// ....
$i = 1;
while ($output = $fc_sel->fetch_assoc()) {
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name'];
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc'];
?>
<div id='first_product<?=$i>'>
<button onclick="toggle_visibility('tog<?=$i>')">Toggle</button>
<div id='tog<?=$i>'>
<div id='red_head<?=$i>'>
...etc. Note that the PHP was closed before the HTML output started. Do this, instead of a large echo. Then at the end of it, open PHP tag again to end the loop:
<?php
}
?>
please modify your code
echo "
<div id='first_product'>
<button onclick='toggle_visibility(\"tog\")'>Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick='toggle_visibility(\"tog\")'> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
"
<button value='tog' onclick='toggle_visibility(this)'>Toggle</button>
Just use "this" and assign value to button its working
Try this ;)
<?php
$i = 1;
while($output = $fc_sel->fetch_assoc()){
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name']; //echo out product name
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc']; //echo out product desc
?>
<div id="first_product<?php echo $i; ?>">
<button onclick="javascript:toggle_visibility('tog<?php echo $i; ?>')">Toggle</button>
<div id="tog<?php echo $i; ?>">
<div id="red_head<?php echo $i; ?>">
<p id="menu_title<?php echo $i; ?>" class ="hidden" onclick="toggle_visibility('tog<?php echo $i; ?>')"> Add your first menu item</p>
</div>
<h3 id="menu<?php echo $i; ?>">Menu Section</h3>
<form name="first_prod" id="first_prod<?php echo $i; ?>" enctype="multipart/form-data" action="testing.php" method="POST" accept-charset="utf-8">
<label id="cat_label<?php echo $i; ?>" name="cat_label">Name</label>
<input type="text" id="cat_name<?php echo $i; ?>" name="cat_name" value="">
<label id="desc_label<?php echo $i; ?>" name="desc_label">Description</label>
<input type="text" id="cat_desc<?php echo $i; ?>" name="cat_desc" value="">
</form>
</div>
</div>
<?php
$i++;
}
?>

Using a name selector instead of an id

How can I change the following code to work off of a name selector instead of the id?
<div id="light" class="change_group_popup">
<a class="close" href="javascript:void(0)">Close</a>
JavaScript
$('.change_group').on('click',function(){
$("#light,.white_overlay").fadeIn("slow");
});
$('.close').on('click',function(){
$("#light,.white_overlay").fadeOut("slow");
});
UPDATE:
I added more of my code to show the loop to help explain what I am doing in more detail.
$runUsers2 = mysqli_query($con,"SELECT * FROM users ORDER BY id DESC");
$numrows2 = mysqli_num_rows($run2);
if( $numrows2 ) {
while($row2 = mysqli_fetch_assoc($run2)){
if($row2['status'] == "Approved"){
//var_dump ($row2);
$approved_id = $row2['user_id'];
$approved_firstname = $row2['firstname'];
$approved_lastname = $row2['lastname'];
$approved_username = $row2['username'];
$approved_email = $row2['email'];
if ($approved_firstname == true) {
echo "Name - ". $approved_firstname . " " . $approved_lastname . "</br>" .
"Username - ". $approved_username . "</br></br>"
?>
<div class="change_group_button">
<a class="change_group" href="javascript:void(0)">Change User Permission</a>
</div><br>
<div class="change_group_popup light">
<a class="close" href="javascript:void(0)">Close</a>
<div class="group_success" style="color: red;"></div><br>
<form class="update_group" action="" method="POST">
<div class="field">
<label for="group">Group</label>
<input type="hidden" value="<?php echo $approved_id; ?>" name="approved_id" />
<input type="hidden" value="<?php echo $approved_firstname; ?>" name="approved_firstname" />
<input type="hidden" value="<?php echo $approved_lastname; ?>" name="approved_lastname" />
<input type="hidden" value="<?php echo $approved_username; ?>" name="approved_username" />
<input type="hidden" value="<?php echo $approved_email; ?>" name="approved_email" />
<select name='group_id' required>
You can get any element by name attribute by:
$('[name="someName"]')
Use DOM traversal functions to find the related element.
$(".change_group").click(function() {
var light = $(this).closest(".change_group_button").nextAll(".light").first(); // Find the next .light DIV after the button
light.add($(".white_overlay")).fadeIn("slow");
}):

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