Passing javascript variable from modal to php on the same page - javascript

I am actually stucking up with this problem for a day.I just want to perform edit operation on this script.My main page which is called customer-grid-screen.php
the code comes as follows
<?php include("header.inc.php");
include("left.inc.php");
include('config.php');?>
<div id="page-content-wrapper">
<?php include("pagetitile.inc.php"); ?>
<div id="page-content">
<div class="clearfix mrg10B"><span class="button-content">Add</span></div>
<div class="example-box">
<div class="example-code">
<table class="table table-condensed">
<thead>
<tr>
<th>Name</th>
<th>Details</th>
<th>Domain</th>
<th>Vertical</th>
<th>Taxanomy</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$result = mysql_query("SELECT * FROM customer_mast ORDER BY customer_id") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
if($row<1) {
echo "</tr>";
echo "<tr>";
echo "<td colspan='6' class='text-center pad25A'>No Record</td>";
echo "</tr>";
}
else
{
foreach($row AS $key => $value){
$row[$key] = stripslashes($value);
}
echo "<tr>";
echo "<td><a href='customer-screen.php'>" . nl2br( $row['customer_name']) . "</td>";
if(!empty($row['customer_details'])){
echo "<td><a href='customer-screen.php'>". nl2br( $row['customer_details']) . "</td>";
}
else{
echo "<td><a href='customer-screen.php'>-</td>";
}
if(!empty( $row['domain']))
{
echo "<td><a href='customer-screen.php'>". nl2br( $row['domain']) . "</td>";}
else{
echo "<td><a href='customer-screen.php'>-</td>";
}
if(!empty($row['vertical'])){
echo "<td><a href='customer-screen.php'>". nl2br( $row['vertical']) . "</td>";}
else{
echo "<td><a href='customer-screen.php'>-</td>";
}
if(!empty($row['taxanomy'])){
echo "<td><a href='customer-screen.php'>". nl2br( $row['taxanomy']) . "</td>";
}
else
{ echo "<td><a href='customer-screen.php'>-</td>";}
echo $row['customer_id'];
echo "<td>
<a href='javascript:?id={$row['customer_id']}' data-id={$row['customer_id']} class='btn small bg-blue-alt tooltip-button modal-customeredit' data-placement='top' title='Edit'><i class='glyph-icon icon-edit' ></i>
</a>
<a href='customer_delete.php?id={$row['customer_id']}' class='btn small bg-red tooltip-button confirm' data-placement='top' title='Remove'><i class='glyph-icon icon-remove'></i>
</a>
</td>";}}
?>
</tbody>
</table>
</div>
</div>
</div><!-- #page-content -->
</div>
</div>
<?php include("footer.inc.php"); ?>
I have to perform edit operation through modal pop up.i implemented the code as follows.
footer.inc.php
------------
<!-- Project Edit MAINLY SEE THIS-->
<div class="hide" id="modal-projedit" title="Edit Project Info">
<div class="pad10A">
<h3>Edit Project Info</h3>
<p class="font-gray-dark"> Fides Admin uses colors & styles from both the default theme color schemes and the included core color helpers. </p>
<div class="divider mrg25B"></div>
<form id="project-edit" action="" class="col-md-12 center-margin" method="">
<div class="form-row">
<div class="form-label col-md-3">
<label for="name">
Project Name:
<span class="required">*</span>
</label>
</div>
<div class="form-input col-md-9">
<input id="name" name="name" placeholder="Name" data-required="true" class="parsley-validated" type="text">
</div>
</div>
<div class="divider"></div>
<div class="form-row">
<div class="form-input col-md-8 col-md-offset-3">
<a href="javascript:;" class="btn medium primary-bg radius-all-4" id="project-edit-valid" onclick="javascript:$('#project-edit').parsley( 'validate' );" title="Validate!">
<span class="button-content">
Update
</span>
</a>
</div>
</div>
</form>
</div>
</div>
//modal window script:
$( ".modal-customeredit" ).click(function() {
var myGroupId = $(this).data('id');
alert( myGroupId); //i can able to alert the paricular row id i want to edit i dont know to pass it through php.
$( "#modal-customeredit" ).dialog({
modal: true,
minWidth: 700,
minHeight: 200,
dialogClass: "modal-dialog",
show: "fadeIn"
});
$('.ui-widget-overlay').addClass('bg-black opacity-60');
});
//same page php file
<?php
$id=???; (get id not working)
$sql="SELECT * FROM `customer_mast` where customer_id='$id'";
$result=mysql_query($sql);
if($result==false)
{
die(mysql_error());
}
else{
$row = mysql_fetch_array($result);}
if (isset($_POST['submit'])){
foreach($_POST AS $key => $value) { $_POST[$key] = mysql_real_escape_string($value); }
$sql = "UPDATE `customer_mast` SET `customer_name` = '{$_POST['customer_name']}' , `customer_details` = '{$_POST['customer_details']}',`domain` = '{$_POST['domain']}' ,`vertical` = '{$_POST['vertical']}' ,`taxanomy` = '{$_POST['taxanomy']}' WHERE `customer_id` = '$id' ";
mysql_query($sql) or die(mysql_error());
echo (mysql_affected_rows()) ? "Edited row.<br />" : "Nothing changed. <br />";
header("Location:customer-grid.php");}
?>
Can anybody please explain me how i can pass that id value to the php script on same page and peform my edit operation.I can explain more if you have doubts,I have gone through many things to to make it correct.Nothing helped me.Please give your suggestion.

You should see how AJAX is working to pass a value to PHP.
$( "#modal-customeredit" ).dialog({
modal: true,
minWidth: 700,
minHeight: 200,
dialogClass: "modal-dialog",
show: "fadeIn"
buttons: {
Edit: function() {
// Sample ajax request ( see the documentation)
$.ajax({
type: "POST",
url: "request.php",
data: { id: myGroupId }, // data retrieve on server-side ($_POST['id'])
dataType : 'html|json|...' // expected data returned
})
.success(function( msg ) {
alert( "Data Saved: " + msg );
});
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
// stop event when form is submit
return false;
});
You have all the element to do it by yourself. Just one more advice, try to separate your files. For instance execute your treatment in another file as request.php.
Edit :
Sample for your request.php (I will return json).
<?php
header('Content-type: application/json'); // Tell the app that you want return json
$id= $_POST['id']; // correspond to your retrieved data in ajax function
// ... Your SQL request and other treatment
// The result return
echo json_encode($result);
?>
The data are now send back to your ajax function in .success( data ).

Related

AJAX comment system, ajax not working

I am making a comment system for my blog that I am creating and currently I have two problems with it. The form appears under every post. But only works on the top post. The rest of the forms simply don't work.
The another problem I have is that I'm using ajax and the form does add the record to SQL but I still have to refresh my page for it to show. I want it to show automatically straight away after it is added.
tl:dr
Two problems:
The only form that works is the first one under the first post, the rest simply don't work
Ajax doesn't automatically show the comments, need to refresh to seem them
Code:
JQuery
function post()
{
var comment = document.getElementById("comment").value;
var name = document.getElementById("name").value;
var mail = document.getElementById("mail").value;
var post_id = document.getElementById("post_id").value;
if(comment && name && mail)
{
$.ajax
({
type: 'post',
url: 'php/comment.php',
data:
{
user_comm:comment,
user_name:name,
user_mail:mail,
post_id:post_id,
},
success: function (response)
{
document.getElementById("comments").innerHTML=response+document.getElementById("comments").innerHTML;
document.getElementById("comment").value="";
document.getElementById("name").value="";
document.getElementById("mail").value="";
}
});
}
return false;
}
Index.php
<div class="container">
<div class="row">
<div class="col-lg-8">
<?php
$result = mysql_query('SELECT * FROM `posts` ORDER BY id DESC') or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$id_post = $row['id'];
$post_title = $row['post_title'];
$post_date = $row['date_created'];
$post_img = $row['post_img'];
$post_first = $row['post_first'];
$post_second = $row['post_second'];
echo " <!-- Blog Post Content Column -->
<h1> " . $row['post_title'] . " </h1><p class='lead'>
by <a href='#'>Matt</a></p> <hr>
<p><span class='glyphicon glyphicon-time'>" . $row['date_created'] . "</span></p>
<img class='img-responsive' style='width: 900px;height: 300px;' src=" . $row['post_img'] . "> <hr>
<p class='lead'>" . $row['post_first'] . "</p>
<p>" . $row['post_second'] . "</p> <hr>";
?>
<!-- Comments Form -->
<div class='well'>
<h4>Leave a Comment:</h4>
<div class="new-com-cnt">
<form method='post' onsubmit="return post();">
<input type='hidden' id='post_id'name='post_id' value='<?php echo $id_post; ?>'>
<div class='form-group'>
<input type="text" id="name" name="name-com" value="" placeholder="Your name" />
<input type="text" id="mail" name="mail-com" value="" placeholder="Your e-mail adress" />
<textarea type='text' id='comment' name='comment' class="form-control" rows='3'></textarea>
</div>
<input type="submit" value="Post Comment">
</form>
</div>
</div>
<hr>
<?php
$resultcomments = mysql_query("SELECT * FROM `comment` WHERE post_id = '$id_post' ORDER BY `date` DESC") or die(mysql_error());
while($affcom = mysql_fetch_assoc($resultcomments)){
$name = $affcom['name'];
$email = $affcom['mail'];
$comment = $affcom['comment'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
?>
<!-- Posted Comments -->
<div id='comments'class='media'>
<a class='pull-left' href='#'>
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'><?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
}
?>
</div>
comment.php
include_once('../../acp/db/db.php');
$link = mysql_connect($dbhost, $dbuser, $dbpassword, $dbname);
mysql_select_db($dbname);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
if(isset($_POST['user_comm']) && isset($_POST['user_name']) && isset($_POST['user_mail']))
{
$comment=$_POST['user_comm'];
$name=$_POST['user_name'];
$mail=$_POST['user_mail'];
$post_id=$_POST['post_id'];
$insert=mysql_query("INSERT INTO comment (name,mail,comment,post_id) VALUES ('$name', '$mail', '$comment', '$post_id')");
$select=mysql_query("SELECT * FROM `comment` WHERE post_id = '$id_post' ORDER BY `date` DESC");
if($row=mysql_fetch_array($select))
{
$name=$row['name'];
$comment=$row['comment'];
$date=$row['date'];
?>
<div class='media'>
<a class='pull-left' href='#'>
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'><?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
exit;
}
?>
This is the first time I am playing around with AJAX :) so be easy on me Any help will be appreciated.
I tested all your code. It's working now. I commented it overall, so search after "NB" (lat. for "Nota bene") in codes, in order to see were I made relevant changes. I'll describe here some problems with it and I'll also give you some recommendations - if I may. At last I'll insert the three corrected pages.
Problems:
One big problem was, that you were using the $id_post variable in
the SELECT sql statement (in comment.php), which does not exist
in comment.php code.
Other problem: DOM elements had same ids. The DOM elements inside
loop-forms must have unique id attributes. You must always have
unique id attributes in html elements. Give them the form
id="<early-id><post_id>" for example.
There were also other problems in more places. I commented overall,
so you'll have to read my codes.
Recommendations:
Use mysqli_ instead of mysql_ functions, because mysql
extension were completely removed from PHP >= 7.0.
Use exception handling, especially when dealing with db access.
Don't write HTML code from inside php. Alternate php with html if you
wish, but don't do echo "<div class=...></div>" for example. This
is actually very important if you use an IDE which can format your
html code. If this code is inside php, you have no chance for this
beautifying process. therefore you can miss important html-tags
without knowing it, because your IDE didn't showed you where tags are
really missing in page.
In html tags: use same name as id. Example: id=mail<?php echo
$post_id; ?>, name=mail<?php echo $post_id; ?>. Exception: radio
buttons, checkboxes and all tags which can form a group. Then, each
tag would have a unique id, but all of them would receive the same
name.
Use '' overall and "" inside them. Maintain this "standard", you'll see it's a lot better than the inverse.
Corrected pages:
Index.php:
<?php
try {
$con = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
if (!$con) {
throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>NB: TITLE</title>
<!-- NB: Added my scripts for testing -->
<link href="Vendor/Bootstrap-sass-3.3.7/Bootstrap.css" rel="stylesheet" type="text/css" />
<script src="Vendor/jquery-3.1.0/jquery.min.js" type="text/javascript"></script>
<script src="Vendor/Bootstrap-sass-3.3.7/assets/javascripts/bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-8">
<?php
$result = mysqli_query($con, 'SELECT * FROM `posts` ORDER BY id DESC');
if (!$result) {
throw new Exception('The query could not be executed!');
}
while ($row = mysqli_fetch_array($result)) {
// NB: Unified $post_id name overall (instead of $id_post).
$post_id = $row['id'];
$post_title = $row['post_title'];
$post_date = $row['date_created'];
$post_img = $row['post_img'];
$post_first = $row['post_first'];
$post_second = $row['post_second'];
?>
<!-- Blog Post Content Column -->
<!--
NB: Extracted html code from php and added here, where it should be.
-->
<h1>
<?php echo $post_title; ?>
</h1>
<p class="lead">
by Matt
</p>
<hr/>
<p>
<span class="glyphicon glyphicon-time">
<?php echo $post_date; ?>
</span>
</p>
<img class="img-responsive" style="width: 1200px; height: 100px;" src="<?php echo $post_img; ?>">
<hr/>
<p class="lead">
<?php echo $post_first; ?>
</p>
<p>
<?php echo $post_second; ?>
</p>
<hr/>
<!-- Comments Form -->
<div class="well">
<h4>Leave a Comment:</h4>
<div class="new-com-cnt">
<form method="post" onsubmit="return post('<?php echo $post_id; ?>');">
<!--
NB: Deleted hidden input (not needed!) and was missing post_id in "id" attribute!
So: transfered post_id value to post() function as argument. See js too.
-->
<!--
NB: Added post_id to the "id" attributes. See js too.
-->
<div class="form-group">
<input type="text" id="name<?php echo $post_id; ?>" name="name-com" value="" placeholder="Your name" />
<input type="text" id="mail<?php echo $post_id; ?>" name="mail-com" value="" placeholder="Your e-mail adress" />
<textarea type="text" id="comment<?php echo $post_id; ?>" name="comment" class="form-control" rows="3"></textarea>
</div>
<input type="submit" value="Post Comment">
</form>
</div>
</div>
<hr>
<!--
NB: Added new "comments" outer-container in order to append
new comment to it and added post_id value into its "id" attribute.
See the js too.
-->
<div id="comments<?php echo $post_id; ?>" class="comments-container">
<?php
$resultComments = mysqli_query($con, 'SELECT * FROM `comment` WHERE post_id = ' . $post_id . ' ORDER BY `date` DESC');
if (!$resultComments) {
throw new Exception('The query could not be executed!');
}
while ($affcom = mysqli_fetch_assoc($resultComments)) {
$name = $affcom['name'];
$email = $affcom['mail'];
$comment = $affcom['comment'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . $default . "&s=" . $size;
?>
<!-- Posted Comments -->
<!--
NB: deleted id attribute "comments", because I added an outer
container to hold the insert results, e.g. the div
with the class "comments-container".
-->
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="<?php echo $grav_url; ?>" >
</a>
<div class="media-body">
<?php echo $name; ?>
<h4 class="media-heading">
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
?>
</div>
<?php
}
?>
</div>
</div>
</div>
</body>
</html>
<?php
$closed = mysqli_close($con);
if (!$closed) {
throw new Exception('The database connection can not be closed!');
}
} catch (Exception $exception) {
// NB: Here you should just DISPLAY the error message.
echo $exception->getMessage();
// NB: And here you should LOG your whole $exception object.
// NB: Never show the whole object to the user!
// echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
?>
comment.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>NB: TITLE</title>
</head>
<body>
<?php
try {
$con = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
if (!$con) {
throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
}
if (isset($_POST['user_comm']) && isset($_POST['user_name']) && isset($_POST['user_mail'])) {
$comment = $_POST['user_comm'];
$name = $_POST['user_name'];
$mail = $_POST['user_mail'];
$post_id = $_POST['post_id'];
// NB: NEW. CHANGE THIS TO YOUR wished DATE FORMAT.
// Use UNIX timestamps for dates, so that you make good date calculations.
$date = date("Y-m-d");
// NB: INSERT DATE IN DB TOO, so that you can select by date desc down under.
$insert = mysqli_query($con, "INSERT INTO comment (name,mail,comment,post_id, date) VALUES ('$name', '$mail', '$comment', '$post_id', '$date')");
if (!$insert) {
throw new Exception('The query could not be executed!');
}
// NB: Replaced $id_post with $post_id.
$select = mysqli_query($con, "SELECT * FROM `comment` WHERE post_id = '$post_id' ORDER BY `date` DESC");
if (!$select) {
throw new Exception('The query could not be executed!');
}
if ($row = mysqli_fetch_array($select)) {
$name = $row['name'];
// NB: Added email, because it wasn't provided.
$email = $row['mail'];
$comment = $row['comment'];
$date = $row['date'];
// NB: It wasn't provided, so I added the same value as in index.php.
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . $default . "&s=" . $size;
?>
<div class="media">
<a class='pull-left' href='#'>
<!--
NB: Where is your $grav_url value?! I added one of mine for testing.
-->
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'>
<?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
// NB: Don't use exit(). Let the code flow further, because
// you maybe want to close the db connection!
// exit();
}
$closed = mysqli_close($con);
if (!$closed) {
throw new Exception('The database connection can not be closed!');
}
} catch (Exception $exception) {
// NB: Here you should just DISPLAY the error message.
echo $exception->getMessage();
// NB: And here you should LOG your whole $exception object.
// NB: Never show the whole object to the user!
// echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
?>
</body>
</html>
Javascript file:
// NB: Added post_id as parameter. See form too.
function post(post_id) {
// NB: Added post_id value to the "id" attributes. See form too.
var comment = document.getElementById("comment" + post_id).value;
var name = document.getElementById("name" + post_id).value;
var mail = document.getElementById("mail" + post_id).value;
if (comment && name && mail) {
$.ajax({
type: 'post',
url: 'php/comment.php',
data: {
user_comm: comment,
user_name: name,
user_mail: mail,
post_id: post_id
},
success: function (response) {
// NB: Comments-post_id is now an outer container. See form.
// NB: Added post_id value to the "id" attributes. See form too.
document.getElementById("comments" + post_id).innerHTML = response + document.getElementById("comments" + post_id).innerHTML;
document.getElementById("comment" + post_id).value = "";
document.getElementById("name" + post_id).value = "";
document.getElementById("mail" + post_id).value = "";
}
});
}
return false;
}
// ******************************************************************************
// NB: Recommendation:
// ******************************************************************************
// Use jquery and ajax instead of vanilla javascript. It's no problem anymore ;-)
// Use done, fail, always instead of success, error, ....
// ******************************************************************************
//function post(post_id) {
// var comment = $('#comment' + post_id);
// var name = $('#name' + post_id);
// var mail = $('#mail' + post_id);
//
// if (comment && name && mail) {
// var ajax = $.ajax({
// method: 'POST',
// dataType: 'html',
// url: 'php/comment.php',
// data: {
// user_comm: comment.val(),
// user_name: name.val(),
// user_mail: mail.val(),
// post_id: post_id
// }
// });
// ajax.done(function (data, textStatus, jqXHR) {
// var comments = $("#comments" + post_id);
//
// // NB: I'm not sure, not tested, too tired :-) Please recherche.
// comments.html(data + comments.html());
//
// comment.val('');
// name.val('');
// mail.val('');
// });
// ajax.fail(function (jqXHR, textStatus, errorThrown) {
// // Show error in a customized messages div, for example.
// $('#flashMessage').val(textStatus + '<br />' + errorThrown);
// });
// ajax.always(function (data, textStatus, jqXHR) {
// //...
// });
// }
//
// return false;
//}
// ******************************************************************************
Good luck.
Your parent loop is generating several comments form and they all have the same id. Ids are supposed to be unique for the whole document. refer this. Perhaps this is causing other comment forms not to work except the first one.
Your second problem is not an issue. It is general behavior of how server works. When you are using ajax, it is sending data to the server which stores it in the database. Server's job is done. It cannot send the data back to the page and update the page content without refreshing the page. You can initiate another ajax call after posting to server in order to refresh the content of the page.
And though it is not related to the question. Try to be consistent with your use of single quotes and double quotes. You shouldn't randomly choose them. Decide on one and use them consistently. And yes do try to learn PDO or mysqli. I will suggest PDO.

Add Check Box to each product and use the selected Check boxes values on another page

The product list will be populated from MySql Database using PHP code and is having a check box for each product.
On that page, whenever a check box is clicked, I need that product to be highlighted and store its value to some other array type variable to pass that value to another page.
Code for product list creation:
<?php
$cnt=0;
$rslt = mysqli_query($conn,"SELECT Icode,Name,Size,Style FROM productinfo");
if(!$rslt){
die(mysqli_error($conn));
}else{
echo "<table width='100%'>";
while($row = mysqli_fetch_assoc($rslt)){
if($cnt==0){
echo "<tr>";
}
echo "<td width='30%'>
<div class='card'>
<img src='upload/"."download.jpg"."' alt='Avatar' style='width:100px' >
<div class='container'>
<h4><b>".$row['Name']." <input type='checkbox' name=".$row['Icode']." value=".$row['Icode']." onclick=' echo return OptionsSelected(this)'/> </b></h4>
<p>".$row['Size']."</p>
<p>".$row['Icode']."</p>
</div>";
?>
<!-- <button role="button" data-toggle="modal" data-id="<?php print $row['Icode']?>" onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Inquiry</button>
</div>
<?php
echo "</td>";
if($cnt==2){
$cnt=0;
echo "</tr>";
}
else
$cnt = $cnt + 1;
}
}
echo "</table>";
?>

How to disable browser features and shortcut keys to conduct fullscreen online Exam?

I am new to OES (Online Exam System). I want to conduct an Online Examination with Secure environment that user will not be able to cheat
please help do this.
I am using PHP with Codeigniter framework for back end and bootstrap, JS and JQuery for user side or front end.
I have already created a the exam module which is working fine with straight way. but I want to restrict users doing wrong ways tell me the best way to do this or suggest any link where I can get the details about.
Here is My assessment.php view file
<?php
$temp = "";
$sr_no = 0;
$assessment = $response['assessment'];
$test_time = $this->session->userdata('test_time') * 60;
$questions = $response['questions'];
$total_que = count($questions);
$i = $que_no - 1;
$question = $questions[$i];
$sr_no++;
$temp.="<div class='form-group'><input type='hidden' name='que_id' value='" . $question['que_id'] . "'>";
if ($total_que == $que_no) {
$i = $que_no - 1;
$temp.="<input type='hidden' name='que_no' value='$i'>";
} else {
$temp.="<input type='hidden' name='que_no' value='$que_no'>";
}
$temp.="<label class='col-md-2'>Que. $que_no)</label>
<label class='col-md-10'>" . $question['que_dscp'] . "</label>";
if ($question['que_type'] == "d") {
$temp.="<div class='col-lg-9 bottom'>";
if (isset($question['selected_options'])) {
$temp.="<textarea style='height: 100px;' disabled name='ans_" . $question['que_id'] . "[]' class='form-control'>" . $question['selected_options'][0] . "</textarea>";
} else {
$temp.="<textarea style='height: 100px;' name='ans_" . $question['que_id'] . "[]' class='form-control'></textarea>";
}
$temp.="</div>";
} else {
foreach ($question['options'] as $option) {
$temp.="<div class='col-lg-9 bottom'>
<div class='input-group'>
<div class='input-group-addon'>";
if ($question['que_type'] == "ma") {
if (isset($question['selected_options'])) {
if (in_array($option['option_id'], $question['selected_options'])) {
$temp.="<input type='checkbox' checked disabled >";
} else {
$temp.="<input type='checkbox' disabled >";
}
} else {
$temp.="<input type='checkbox' name='ans_" . $question['que_id'] . "[]' value='" . $option['option_id'] . "'>";
}
} else if ($question['que_type'] == "sa") {
if (isset($question['selected_options'])) {
if (in_array($option['option_id'], $question['selected_options'])) {
$temp.="<input type='radio' checked disabled >";
} else {
$temp.="<input type='radio' disabled >";
}
} else {
$temp.="<input type='radio' name='ans_" . $question['que_id'] . "[]' value='" . $option['option_id'] . "'>";
}
}
$temp.="</div>
<input type='text' readonly value='" . $option['option_dscp'] . "' class='form-control'>
</div>
</div>";
}
}
$temp.="</div>";
$temp1 = "";
$sr_no = 0;
foreach ($questions as $question1) {
$sr_no++;
$temp1.="<a href='" . base_url() . "user/assessment/index/" . $assessment['test_id'] . "/$sr_no' class='btn btn-info'>$sr_no</a> ";
}
?>
<script type="text/javascript" src="<?php echo base_url(); ?>resource/js/TimeCircles.js"></script>
<link href="<?php echo base_url(); ?>resource/css/TimeCircles.css" rel="stylesheet">
<div class="container">
<div class="page-header center">
<h1><?php echo $assessment['test_name']; ?> <small><?php echo $title; ?> </small></h1>
</div>
<?php $this->load->view('alert'); ?>
<div class="panel panel-default col-md-4" style="padding: 0;">
<!-- Default panel contents -->
<div class="panel-heading">Questions Navigation</div>
<div class="panel-body" >
<?php echo "$temp1"; ?>
</div>
<div id="test_time" data-timer="<?php echo "$test_time"; ?>"></div>
</div>
<div class="panel panel-default col-md-8" style="padding: 0;">
<!-- Default panel contents -->
<div class="panel-heading">Assessment Questions</div>
<div class="panel-body" >
<?php echo validation_errors(); ?>
<form id="signupform" action="<?php echo base_url(); ?>user/assessment/submit" class="form-horizontal" method="POST">
<input type="hidden" name='test_id' value='<?php echo $assessment['test_id']; ?>'>
<input type="hidden" name='user_id' value='<?php echo $this->session->userdata('user_id'); ?>'>
<?php echo "$temp"; ?>
<div class="form-group">
<!-- Button -->
<div class="col-md-offset-6 col-md-6">
<?php
if ($que_no == 1) {
?>
<a href="#" disabled class='btn btn-danger'>Previous</a>
<?php
} else {
?>
<a href="<?php echo base_url(); ?>user/assessment/index/<?php echo $assessment['test_id']; ?>/<?php echo ($que_no - 1); ?>" class='btn btn-info'>Previous</a>
<?php
}
if (isset($question['selected_options'])) {
?>
<button id="btn-signup" disabled type="submit" class="btn btn-danger"><i class="icon-hand-right"></i> &nbsp Save</button>
<?php
} else {
?>
<button id="btn-signup" type="submit" class="btn btn-info"><i class="icon-hand-right"></i> &nbsp Save</button>
<?php
}
if ($total_que == $que_no) {
?>
<a href="#" disabled class='btn btn-danger'>Next</a>
<?php
} else {
?>
<a href="<?php echo base_url(); ?>user/assessment/index/<?php echo $assessment['test_id']; ?>/<?php echo ($que_no + 1); ?>" class='btn btn-info'>Next</a>
<?php
}
?>
</div>
</div>
<input type="hidden" id="time_taken" name="time_taken" >
<div id="Countdown" style="width: 50%;"></div>
</form>
<a href="<?php echo base_url(); ?>user/assessment/solved/<?php echo $assessment['test_id']; ?>/<?php echo $this->session->userdata('user_id'); ?>" class='btn btn-info'>Finish Test</a>
</div>
</div>
</div>
<script>
$("#test_time").TimeCircles();
$("#Countdown").TimeCircles({
"animation": "smooth",
"bg_width": 0.8,
"fg_width": 0.1,
"circle_bg_color": "#60686F",
"time": {
"Days": {
"text": "Days",
"color": "#FFCC66",
"show": false
},
"Hours": {
"text": "Hours",
"color": "#99CCFF",
"show": false
},
"Minutes": {
"text": "Minutes",
"color": "#BBFFBB",
"show": true
},
"Seconds": {
"text": "Seconds",
"color": "#FF9999",
"show": true
}
}
});
$("#btn-signup").click(function() {
$("#time_taken").val($("#Countdown").TimeCircles().getTime());
});
</script>
<script type="text/javascript">
setInterval(ajaxCall, 1000); //300000 MS == 5 minutes
function ajaxCall() {
var test_time=$("#test_time").TimeCircles().getTime();
if(test_time >= 0){
$.post("<?php echo base_url(); ?>user/assessment/set_test_time", { test_time : test_time }, function(data, status) {
});
}else{
$.get("<?php echo base_url(); ?>user/assessment/solved/<?php echo $assessment['test_id']; ?>/<?php echo $this->session->userdata('user_id'); ?>",function(data, status) {
location.reload();
});
}
}
</script>
<script type="text/javascript">
$(function () {
$(document).bind('contextmenu', function (e) {
e.preventDefault();
});
});
function disableF5(e) { if ((e.which || e.keyCode) == 116 ||(e.which || e.keyCode)==8) e.preventDefault(); };
$(document).on("keydown", disableF5);
</script>
Here is My home.php view file from where I redirect user to assessment.php
<?php
$temp = "";
$sr_no = 0;
foreach ($assessments as $assessment) {
$solved = $assessment['solved'];
$test_id = $assessment['test_id'];
$test_name = $assessment['test_name'];
$status = $assessment['status'];
if ($status == "1") {
$status = "Active";
} else {
$status = "InActive";
}
$sr_no++;
$temp.="<tr>
<td></td>
<td>$sr_no</td>
<td>$test_name</td>
<td>$status</td>";
if($solved=="0"){
$temp.="<td><a target='_blank' class='btn btn-info' onClick='return confirm(\"Are you sure want to Start Assessment...!\");' href='javascript:window.open(\"".base_url()."user/assessment/index/$test_id\",\"User Assessment\", \"titlebar=no,toolbar=no,menubar=no,width=screen.width,height=screen.height,fullscreen=yes\");' title='Take Test'>Take Test</a></td>";
}else if($solved=="1"){
$temp.="<td><a class='ml10' href='".base_url()."user/assessment/view/$test_id' title='View'>
<i class='glyphicon glyphicon-search'></i></a></td>";
}
$temp.="</tr>";
}
?>
<link rel="stylesheet" href="<?php echo base_url(); ?>resource/css/bootstrap-table.css">
<div class="container">
<div class="page-header center">
<h1>User Assessment System! User Dashboard <small><?php echo $title; ?> </small></h1>
</div>
<?php $this->load->view('alert'); ?>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">Manage Assessment</div>
<div class="panel-body" >
<!-- Table -->
<table class="table" id="userstable" data-toggle="table" data-pagination="true" data-show-refresh="true" data-export-types="{'pdf','xml','joson','png','excel'}" data-show-export="true" data-show-toggle="true" data-show-columns="true" data-search="true">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th>#</th>
<th data-field="que_dscp" data-sortable="true">Assessment Name</th>
<th data-field="status" class="text-center">Status</th>
<th data-field="ques" class="text-center">Start/View Test</th>
</tr>
</thead>
<tbody>
<?php echo "$temp"; ?>
</tbody>
</table><br>
</div>
</div>
</div>
<script src="<?php echo base_url(); ?>resource/js/bootstrap-table.js"></script>
<!-- put your locale files after bootstrap-table.js -->
<script src="<?php echo base_url(); ?>resource/js/bootstrap-table-en-US.js"></script>
There is absolutely no way for you to restrict someone in a location not controlled by you.
No matter what you do to my browser or even my operating system, I can always just use a second computer, or my phone, or have a book lying around, or a sheet of paper, or a friend who knows stuff.
The only way to detect such a thing would be a camera filming the user the entire time.
In addition to that, you'd have to film the screen - with a camera too, not via a screen recorder, because otherwise I might just use a virtual machine for the exam, in which the browser is in full screen all the time, but I can just alt-Tab out of the VM and do whatever I want, while a screen recorder will just see the inside of the VM.
So you cannot actually restrict the user - the only thing you can try is to surveil them.
That would require at the very least one microphone and two cameras, probably more - one to film the screen (so that you can actually recognise something afterwards) and the rest to film the user and his entire possible field of view (don't forget the ceiling, there could be writing or something). The microphone, of course, is to make sure the user has no audible input during the exam - this also implies that they must not wear headphones, otherwise they might make use of some sound-based interface.
For example, I imagine a service which, upon activation by hotkey, opens an invisible browser window, captures your keyboard input, conducts a Google search upon hitting Return, lets you navigate via the arrow keys/Return/Tab/Backspace/Esc and reads to you any text that you "select".
I believe on OS X, one would only need to find a way to make windows invisible - then they could activate Voice over, set their start page to Google and create a service with Automator that opens a new browser window (invisibly), to which they can then assign a hotkey.
Also, all recordings should be transmitted in real time, otherwise the user has a chance to tamper with them.
Now that I wrote this I realise that this is probably more of a question for Information Security.
For limited browser capabilities,
You can use Javascript's window.open function, it takes certain parameters. For example look below
If you look at the third parameters, it does the tricks that you are looking for, it disables the toolbar and all those stuffs.
window.open('exampage.html','some_name_for_this_window','titlebar=no,toolbar=no,menubar=no,width=400,height=350');
Take a look at the Mozilla Docs for what other features you can disable or enable. It might help you out
And on the backend for what the user is clicking and interacting, you have codeigniter's SESSION library to take care of that
This might help you partially,
You can suppress few keydown events which might help you partially, You won't be able to disable all the events though,
window.addEventListener('keydown', function (event) {
// if the keyCode is 16 ( shift key was pressed )
// Here you can specify which key events you want to disable
if ((event.which || event.keyCode) === 16) {
// prevent default behaviour
event.preventDefault();
// Few Browser also need return false, to disable keydown events
return false;
}
});
I had a similar question which was closed. After some online search, found out this amazing software called safeexambrowser which currently works for windows and mac os. Built on Firefox/ gecko engine, it will help you to disable keyboard shortcuts and refrains user from using any other application.
This is suitable for standallone web applications. Please check if this suits your requirement.

AJAX comment system Validation problems

So i am haveing this page where it is displaying articles andunderneet each article it will have a textarea asking allowing the user to insert a comment.I did the AJAX and it works fine.Some of the validation works fine aswell(Meaning that if the textarea is left empty it will not submit the comment and display an error).The way i am doing this validation is with the ID.So i have multi forms with the same ID.For the commets to be submited it works fine but the validtion doesnt work when i go on a second form for exmaple it only works for the first form
AJAX code
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('#comment');
if (comment.val().length > 1)
{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
else
{
alert("Hello");
}
});
});
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" >
<label>New Comment</label>
<textarea id="comment" name="comment" class="comment"></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Again the problem being is the first form works fine but the second one and onwaord dont work properly
try this:
var comment = $('.comment',form);
instead of
var comment = $('#comment');
That way you're targeting the textarea belonging to the form you're validating
ps.
remove the id's from the elements or make them unique with php, all element id's should be unique

Yii autocomplete widget not working after ajax call

I included an autocomplete widget inside my view which initially(first page load) works fine and i make an ajax call to update the CListView inside my main page and thats where my autocomplete doesnt show completions(the input box is there but when the user type no suggestion is loaded)..i have seen a lot of issue about using renderPartial and ajax calls not working...anyone with a good solution or please suggest me..
here is my main view that is being refreshed by ajaxcall on the same page..
<div id="top" class="row-fluid" style="margin:0 30 auto 30; ;width:100%;">
<?php
?>
<div id="messages" style="width:35%!important;float:left;margin-left:100px;margin- right:20px!important;position:relative; overflow: hidden;">
<?php
$this->renderPartial('ajaxindex',array('dataProvider'=>$dataProvider),false,true);
?>
<!--end of portlet"-->
</div>
<!--end of messages-->
<div id="nav-panel" class="portlet" style="float:left!important;
width:40%!important;border:1px;box-shadow: 10px 10px 5px #888888;" >
<div class="panel panel-success portlet-decoration">
<!-- Default panel contents -->
<div class="panel-heading">
Filtering Panel >> Rwanda
</div>
</div>
<table class="table table-condensed">
<tr>
<th>Province</th>
<th>Critical</th>
<th>Attention</th>
<th>Normal</th>
<th>Nothing</th>
<th>error</th>
<th>count</th>
</tr>
<?php
$i=1;
$countNothing=0;
$countNormal=0;
$countAttention=0;
$countCritical=0;
$countError=0;
$countAll=0;
foreach($messagesByProvinces as $messagesByProvince){
$province=Province::Model()->findByPk($i);
$provinceParams=null;
$messageParams=null;
$critical=0;
$attention=0;
$normal=0;
$nothing=0;
$error=0;
$count=count($messagesByProvince);
foreach($messagesByProvince as $message){
$countAll++;
if($message->indice==0){
$nothing++;
$countNothing++;
}
elseif($message->indice==1){
$normal++;
$countNormal++;
}
elseif($message->indice==2){
$attention++;
$countAttention++;
}
elseif($message->indice==3){
$critical++;
$countCritical++;
}
else {
$error++;
$countError++;
}
}
if($filter!==null){
$provinceParams=array('message/getProvincereport','id'=>$province->id,'start_date'=>$filter['start_date'],'end_date'=>$filter['end_date']);
$messageParams=array('message/LoadMessages','province_id'=>$province->id,'start_date'=>$filter['start_date'],'end_date'=>$filter['end_date']);
}
else {
$provinceParams=array('message/getProvincereport','id'=>$province->id);
$messageParams=array('message/LoadMessages','province_id'=>$province->id);
}
echo "<tr><td>".CHtml::link($province->name,$provinceParams)."</td>
<td><span class='badge badge-important'>".CHtml::ajaxLink($critical,$this->associate('indice',3,$messageParams),array('update'=>'#messages','success'=>'js:function(data){
var $response=$(data);
var newData=$response.find(".container-fluid").html();
$("#messages").html(newData);
} '))."</span></td>";
Here is the view that is rendered in renderPartial
<script>
function showInput(id){
if(document.getElementById('message-body-'+id).style.display=='block')
document.getElementById('message-body-'+id).style.display='none';
else
document.getElementById('message-body-'+id).style.display='block';
;
}
</script>
<?php
/* #var $this MessageController */
/* #var $dataProvider CActiveDataProvider */
?>
<div id="portlet-messages" class="portlet" style="float:left!important;
width:100% !important;max-height:450px;overflow:auto;
overflow-x:hidden;" >
<div class="panel panel-primary portlet-decoration">
<!-- Default panel contents -->
<div class="panel-heading">
<i class="icon-envelope"></i> Messages
</div>
</div>
<table class="table table-striped">
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'summaryText'=>'',
'enablePagination'=>false,
'itemView'=>'_ajaxview',
)); ?>
</table>
</div>
and the the embed view that contains the bogus code of from CAutoComplete Widget..
<?php
$indiceDisplay='Error';
$label="label-default";
if($data->indice==0){
$indiceDisplay="Nothing";
$label="label-info";
}
elseif($data->indice==1){
$indiceDisplay="Normal";
$label="label-success";
}
elseif($data->indice==2){
$indiceDisplay="Attention";
$label="label-warning";
}
elseif($data->indice==3){
$indiceDisplay="Critical";
$label="label-important";
}
else{
$indiceDisplay="Error";
$label="label-default";
}
echo "<tr class='view' >";
?>
<td>
<?php
echo CHtml::encode(User::Model()->findByPK($data->user_id)->names);echo "<br/></br>";
?>
</td>
<td>
<?php
echo "<b>";
echo CHtml::encode( date_format(new DateTime($data->date), 'g:ia \o\n l jS F Y'));?>
<?php
echo " ";
echo " ";
$linkText="<span class='label ".$label." '> ".$indiceDisplay." </span>";
echo CHtml::link($linkText,array('message/index','indice'=>$data->indice));
echo"</br>";
?>
</b>
</br>
<?php echo CHtml::encode($data->content); ?>
<br />
<?php
echo " <b>Location :</b> ".CHtml::link(Province::Model()->findByPk($data- >province_id)->name,array('message/index','province_id'=>$data->province_id))." ".Chtml::link(District::Model()->findByPk($data->district_id)- >name,array('message/index','district_id'=>$data->district_id))." ".CHtml::link(Sector::Model()->findByPk($data->sector_id)- >name,array('message/index','sector_id'=>$data->sector_id))." ".CHtml::link(Cell::Model()- >findByPk($data->cell_id)->name,array('message/index','cell_id'=>$data->cell_id))." ";
?>
<div id="results-<?echo $data->id;?>">
</div>
<?php echo "<div id='message-body-".$data->id."' style='font-size:12px;display:none;'>";?>
<div class="input-append">
<span>Add Category</span>
<?php $this->widget('CAutoComplete', array(
'model'=>$data,
'attribute'=>'category',
'url'=>array('message/suggestCategory'),
'multiple'=>true,
'htmlOptions'=>array('style'=>'height:11px;font-weight: bold;','maxlength'=>255,'value'=>$data->category,'id'=>'category-'.$data->id,))); ?>
<?php echo CHtml::ajaxSubmitButton('Save',$this- >createUrl('message/categorize',array('id'=>$data->id,'category'=>'js:function(){return $("#category-'.$data->id.'").val();}')),
array(
'type'=>'post',
'data'=>array('category'=>'js:function(){return $("#category-'.$data->id.'").val();}'),
'success'=>'function(data) {
if(data.status=="success"){
$("#results-'.$data->id.'").html(data);
$("#message-body-'.$data->id.'").style.display="none";
}
else{
$("#results-'.$data->id.'").html(data);
document.getElementById("message-body-'.$data->id.'").style.display="none";
}
}',
),array('id'=>'mybtn-'.$data->id,'class'=>'btn btn-small btn- primary','style'=>'height:21px'));
?>
</div>
</div>
</td>
<td>
<a class="btn btn-small" onclick="showInput(<?php echo $data->id;?>);"><i class="icon icon- edit"></i>
</a>
</td>
</tr>
here is the method that is called through the ajax call to update the message div in the main page posted at the begining of the code..
public function actionLoadmessages()
{ $criteria=$this->getCriteria();
if(isset($_REQUEST['indice'])){
$criteria->addCondition('indice=:ind');
$criteria->params['ind']=$_REQUEST['indice'];
}
$dataProvider=new CActiveDataProvider('Message',array('criteria'=>$criteria));
$this->layout=null;
$this->render('ajaxindex',array('dataProvider'=>$dataProvider));
}
You should apply post processing of javascript after the ajax call otherwise some javascript functions will not work ..
Your render call should be something like this
$this->renderPartial('ajaxindex',array('dataProvider'=>$dataProvider),false,true);
Refer this page for more info http://www.yiiframework.com/doc/api/1.1/CController#renderPartial-detail
You should also use renderPartial if updating a div only, render will call layout files as well.

Categories