Check if a connected user matches the value of a Javascript variable - javascript

As part of a version of FullCalendar with user accounts, I would like to check if the current session matches the value of one of the fields of one or more events created via fullcalendar.
My events are generated as follows:
SQL query:
$sql = "SELECT id, title, description, organisateur, orgaavailable, donator, start, end, color FROM events ";
$req = $bdd->prepare($sql);
$req->execute();
$events = $req->fetchAll();
My events are pre-generated via the following javascript function (which allows me to automatically replace the content of the fields of a form by the content of what has been retrieved from my database)
eventRender: function(event, element, view) {
element.bind('click', function() {
$('#ModalEdit #id').val(event.id);
$('#ModalEdit #title').val(event.title);
$('#ModalEdit #description').val(event.description);
$('#ModalEdit #organisateur').val(event.organisateur);
$('#ModalEdit #orgaavailable').val(event.orgaavailable);
$('#ModalEdit #donator').val(event.donator);
$('#ModalEdit #color').val(event.color);
$('#ModalEdit').modal('show');
});
},
Finally, my event is parsed in JSON via a PHP loop
events: [
<?php foreach($events as $event):
$start = explode(" ", $event['start']);
$end = explode(" ", $event['end']);
if($start[1] == '00:00:00'){
$start = $start[0];
}else{
$start = $event['start'];
}
if($end[1] == '00:00:00'){
$end = $end[0];
}else{
$end = $event['end'];
}
$title = addslashes($event['title']);
$description = addslashes($event['description']);
$organisateur = addslashes($event['organisateur']);
$orgaavailable = addslashes($event['orgaavailable']);
$donator = addslashes($event['donator']);
if ($userlogged == $organisateur)
{
$vartest = 1;
}else{
$vartest = 0;
}
?>
{
id: '<?php echo $event['id']; ?>',
title: '<?php echo $title; ?>',
test : '<?php echo $vartest; ?>',
description: "<?php echo $description; ?>",
organisateur: '<?php echo $organisateur; ?>',
orgaavailable: '<?php echo $orgaavailable; ?>',
donator: '<?php echo $donator; ?>',
start: '<?php echo $start; ?>',
end: '<?php echo $end; ?>',
color: '<?php echo $event['color']; ?>',
},
<?php endforeach; ?>
]
After that, my form is displayed in a modal and the fields are pre-filled with the information retrieved from my database (the form being too big, I don't know if I can put its code here)
The problem is that I can't see how I could compare the value of my session ($_SESSION['user_session']) with the value of what is parse in the "organisateur" value: by the variable $organisateur to know if my connected user is the user indicated in $organisateur.
For information, I performed a test in my code that fills in the value 1 in the variable $vartest if $userlogged == $organizer ($userlogged being a variable retrieving the content of $_SESSION['user_session']) or the value 0 if the condition is not met.
The variable $vartest is then parsed next to the value "test :"
This condition works perfectly, 1 is displayed in the parse of the event belonging to the connected user and conversely, a 0 is displayed if it is not the case.
The parse is well formed when I look at the source code generated by my browser
Thanks in advance !

Related

how to store php variable passed as id to javascript in a javascript variable

I am trying to pass div id to javascript and print it out on console as :
<?php echo 67;?>
The 67 is id here. I was wondering how can I store this value in my javascript variable storeid as var storeid = 67?
My code:
echo "<h2 class='editme' id='<?php echo $id;?>' contentEditable='true'> Hello</h2>";
echo "<script>
$('h2.editme').click(function(){
console.log(this.id);
var storeid;
});
</script>";
Also, I want to use that id value to update the values in my sql. I can only test my code once I could somehow get the value of that id. How can I store the value of the id to javascript variable?
My code (This is to update sql once I get the id) - Not sure if it's right I can test it after getting id value:
echo "<h2 class='editme' id='<?php echo $id;?>' contentEditable='true'> Hello</h2>";
echo "<script>
$('h2.editme').click(function(){
var content2 = $(this).html();
console.log(this.id);
var storeid;//once I get the id
$.ajax({
url: 'updateDescription(storeid, content2)',
success: function(respon) {
$('.editme').html(respon);
}
});
});
</script>";
function updateDescription($user_unique_id, $content2)
{
try {
require "testing.php";
$sql = "UPDATE icecream SET
desc = :desc
WHERE id = :id";
$stmt->bindParam(':desc', $content2, PDO::PARAM_STR);
$stmt->bindParam(':id', $user_unique_id);
$stmt->execute();
echo 'Record updated';
} catch (PDOException $e) {
echo 'Connection failed ' . $e->getMessage();
}
}
this way:
echo '<script>
var storeid = '. $id .'
</script>';
more readable way:
// somefile.php
<?php
$id = 67;
?>
<h2 class='editme' id='<?php echo $id;?>' contentEditable='true'> Hello</h2>
<script>
var storeid = <?php echo $id; ?>
// rest of javascript code
</script>
<?php
// rest of the php code

'Unexpected token ;' when trying to pass PHP variable in jQuery AJAX request

So im trying to run a PHP script that sets a deleted field in the database to poplulate if you drag a certain text element to the droppable area.
At the moment i have this droppable area:
<div class="dropbin" id="dropbin" >
<span class="fa fa-trash-o noSelect hover-cursor" style="font-size: 20pt; line-height: 225px;"> </span>
</div>
and this draggable text:
<div id='dragme' data-toggle='modal' data-target='#editNoteNameModal' class='display-inline'>" . $data['NoteName'] . "</div>
The area im having an issue with is this:
$("#dropbin").droppable
({
accept: '#dragme',
hoverClass: "drag-enter",
drop: function(event)
{
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
var deletedby = <? if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>
var data = {noteid1: noteid, deletedby1: deletedby};
if (confirm('Delete the note?')==true)
{
$('#dragme').hide();
debugger
$.ajax({
type: 'POST',
url: 'deleteNote.php',
datatype: 'json',
data: data,
success: function(result)
{
alert("Success");
}
});
window.location = "http://discovertheplanet.net/general_notes.php";
}
else
{
window.location = "http://discovertheplanet.net/general_notes.php";
}
}
});
EDIT: The line i get the error on is:
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
Im currently getting an "Unexpected token ;" and its stopping the droppable from working.
Just a side note, if i run it without the variables it hits everything apart from:
url: 'deleteNote.php',
Also inside deleteNote.php is this incase it helps:
<?php
include "connectionDetails.php";
?>
<?php
if (isset($_POST['noteid1'], $_POST['deletedby1']))
{
$noteid2 = $_POST['noteid1'];
$deletedby2 = $_POST['deletedby1'];
// echo "Hello...". $noteid;
$stmt = "UPDATE Notes SET Deleted = GETDATE() WHERE NoteID = (?)";
$params = array($noteid2);
$stmt = sqlsrv_query($conn, $stmt, $params);
if ($stmt === false)
{
die( print_r(sqlsrv_errors(), true));
}
}
else
{
echo "No Data";
}
?>
(I deliberatley don't have deletedby in the database just yet, ignore that)
Could anyone possibly help me to get this to work?
Try to add quotes in these lines and add php after <? in second line:
var noteid = "<?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>";
var deletedby = "<?php if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>";
OR
var noteid = "<?=isset($_POST['noteid']) ? $_POST['noteid'] : "" ?>";
var deletedby = "<?=isset($_SESSION['username']) ? $_SESSION['username'] : "" ?>";

Ajax function on button press

I am trying to get information to post via PHP on button click, everything in my code looks right, and when I view the page source everything is filled in the way it should be. When I pull up the debugger when the button is clicked it does not make any calls at all, here is my button
<button type="button">Continue</button>
here is my ajax call
$(document).ready(function() {
$("button").click(function(){
var Id = <?php echo $give ?>;
var Ids = <?php echo $rec ?>;
var ex = <?php echo $exchange ?>;
var ret = <?php echo $tost ?>;
var email = <?php echo $email ?>;
var name = <?php echo $name ?>;
var pe = <?php echo $pe ?>;
var re = <?php echo $re ?>;
$.post("postts.php", {
Id: Id,
Ids: Ids,
ex: ex,
ret: ret,
email: email,
name: name,
pe: pe,
re: re
}, function(data){
alert(data);
$("p").text(data);
}, 'json' );
});
});
all of my vars will populate with the correct information, I just don't know why when I click the button it does nothing. I am not sure if I have made a typo, or if my syntax is wrong, this is only the second time I have done something like this.
You have error in writing variable values from PHP to JavaScript, you must wrap PHP output by quotation marks, so JavaScipt will "see" string ;)
instead of:
var email = <?php echo $email ?>;
write:
var mail = '<?php echo $email ?>';

Best way to pass sensitive variables on click event?

I am looking for a secure way of passing sensitive variables to a php file via ajax. At the moment i have been using data attributes but the values can be changed using something like firebug.
HTML:
<div class="strip">
<?php
if($hide == 0) {
echo '<h2 class="action" data-type="1" data-id="<?php echo $id; ?>" data-action="0">Hide Business</h2>';
}
if($hide == 1) {
echo '<h2 class="action" data-type="1" data-id="<?php echo $id; ?>" data-action="1">Un-Hide Business</h2>';
}
?>
<h2 class="action" data-type="1" data-id="<?php echo $id; ?>" data-action="2">Delete Business</h2>
</div>
JavaScript/JQuery:
$(".action").click(function() {
var type = $(this).data("type");
var id = $(this).data("id");
var action = $(this).data("action");
$.ajax({
url : 'assets/php/confirm.php',
type : 'POST',
data : "type="+type+"&action="+action+"&ids="+id,
success : function (result) {
alert(result);
}
});
});
PHP:
if(isset($_POST['type'], $_POST['action'], $_POST['ids'])) {
$type = $_POST['type'];
$action = $_POST['action'];
$ids = explode(",", $_POST['ids']);
$count = count($ids);
if($type == 0) {
if($action == 1) {
$stmt = $mysqli->prepare("DELETE FROM deals WHERE id=?");
} else {
$stmt = $mysqli->prepare("UPDATE deals SET hide=0 WHERE id=?");
}
} else {
if($action == 1) {
$stmt = $mysqli->prepare("DELETE FROM businesses WHERE id=?");
} else {
$stmt = $mysqli->prepare("UPDATE businesses SET hide=0 WHERE id=?");
}
}
for($i = 0; $i < $count; $i++) {
$stmt->bind_param('s', $ids[$i]);
$stmt->execute();
$stmt->close();
}
echo 'Success updated '.$_POST['ids'];
}
The variables that need to be secure are the data-type, data-id, data-action values. Reason being i dont want the wrong database entries being deleted.
I dont know of any alternatives, so any help would be great.
If you want to stop the user changing them, then you can't get them from the user at all. Store the data on the server instead.
If you want to limit what values you'll accept from the user, then limit them on the server. Perform authentication and authorization. Make sure the values being changed are ones the logged in user is allowed to change.
As your code on the client - inside the browser - can not be hidden, you should secure the connection between client and web server - use SSL/TSL for that...

jQuery Calender - More than one event per day

I have a calendar on my site that uses javascript/jquery to place events in the calendar. All the events are stored in a MySQL database with the title and Unix timestamp.
My problem is that this method (shown in the code below) only allows one event per day, and creating two rows with the same date, only uses the latter of the two. There are several instances where I need two or more events in one day.
My code:
var CalendarEvent = function (time, title) {
this.time = time;
this.title = title;
}
var allEvents = {
<?php require_once 'ndx/mysql.php';
$events = mysqli_query($con, "SELECT * FROM events");
while($lse = mysqli_fetch_array($events)):
$date = date('Y-m-d', $lse['timestamp']);
$notime = $lse['notime'];
if($notime != 'true'){
$time = date('g:i a', $lse['timestamp']);
}else{
$time = '';
}
$event = addslashes($lse['title']);
?>
'<?php echo $date; ?>': [
new CalendarEvent('<?php echo $time; ?>', '<?php echo $event; ?>')
],
<?php endwhile; ?>

Categories

Resources