PHP AJAX submit form with while loop - javascript

I am making a live comment function. Here the problem is that when I am commenting the comment is successful but the data gets inserted as many times the form is present in the while loop. I think I should assign a separate status id (sts_id) to each form from table status and make changes in my ajax code so that it submits data only once rather than submitting as many times as the form is created in while loop. For example, since the form is in while loop and there are 6 status posts then when I comment on a status the comment gets inserted 6 times. Also one more problem is there i.e., commenting function is currently working only on the 1st form inside the while loop. On other forms, the form submission is not working i.e., its not submitting the comments. I think adding separate ids might solved this too. Please help.
HTML part
<script>
function ajaxFunction(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
$('.commentarea').keydown(function(event) {
var id = $(this).attr('id');
var status_id = id.replace("postcomment_", "");
if($.trim($("#postcomment_"+status_id).val())) {
if(event.keyCode == 13) {
event.preventDefault();
$("form#form_id_"+status_id).on('submit', function (e) {
e.preventDefault();
var comment = $('#postcomment_'+status_id).val();
var statsid = status_id;
var myData = {"comment": comment, "statsid": statsid};
$.ajax({
url: "post-comment.php",
type: "POST",
data: myData,
success: function (data, status, xhr) {
$(".showbox").html(data); // output result
$('#postcomment').val('');
}
});
});
}
}
});
}
</script>
<div class="stats-cont">
<?php
$get_sts = "SELECT * FROM status LEFT JOIN members ON status.sts_mem = members.mem_id ORDER BY sts_time DESC";
$get_stq = $pdo->prepare($get_sts);
$get_stq->execute();
while($get_stf = $get_stq->fetch()){ extract($get_stf);
$get_cmts = "SELECT * FROM comments WHERE cmt_status = :status ORDER BY cmt_id ASC";
$get_cmtq = $pdo->prepare($get_cmts);
$get_cmtq->bindValue(':status', $sts_id);
$get_cmtq->execute();
$total_cmts = $get_cmtq->rowCount();
?>
<div class="status-note-block status-container">
<div class="member-name-container">
<div class="mem-img-thumb">
<?php if($mem_image == null){ ?>
<img src="images/user.png" height="40" width="40">
<?php }else{ ?>
<img src="users/<?php echo $mem_image; ?>" height="40" width="40">
<?php } ?>
</div>
<div class="member-name"><?php echo $mem_name; ?><br>
<small>
<?php if((date("Y-m-d", strtotime($sts_time))) == $curr_date){ echo "Today"; }else if((date("Y-m-d", strtotime($sts_time))) == $yest){ echo "Yesterday"; }else{ echo date("jS F", strtotime($sts_time)); } ?>
<?php echo date("h:i a", strtotime($sts_time)); ?> </small> </div>
</div>
<div class="status-block"><?php echo $sts_status; ?></div>
</div>
<div class="comment-block">
<div class="comment-reaction-holder"></div>
<?php while($fetch_cmts = $get_cmtq->fetch()){ extract($fetch_cmts); ?>
<div class="comment-flex-holder">
<div class="comment-img-thumb">
<?php if($mem_image == null){ ?>
<img src="images/user.png" height="30" width="30">
<?php }else{ ?>
<img src="users/<?php echo $mem_image; ?>" height="30" width="30">
<?php } ?>
</div>
<div class="showbox"><font color="#5B5899" style="font-size: 12px"><b><?php echo $mem_name; ?></b></font> <?php echo $cmt_comment; ?><br />
<font style="font-size:12px">Like · Reply · Just now</font></div>
</div>
<br />
<?php } ?>
<div id="showbox"></div>
<div class="commet-field-holder">
<div class="comment-img-thumb">
<?php if($mem_image == null){ ?>
<img src="images/user.png" height="30" width="30">
<?php }else{ ?>
<img src="users/<?php echo $mem_image; ?>" height="30" width="30">
<?php } ?>
</div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width cmtform" id="form_id_<?php echo $sts_id?>">
<input type="hidden" name="status_id" value="<?php echo $sts_id; ?>" id="statsid_<?php echo $sts_id?>" />
<textarea name="comment" placeholder="Give a comment..." class="comment-field commentarea" id="postcomment_<?php echo $sts_id?>" onclick='ajaxFunction()'></textarea>
</form>
</div>
</div>
<?php } ?>
post-comment.php part:
<?php
//error_reporting(0);
include('config/db.php');
$time = date('Y-m-d H:i:s');
$content = (!empty($_POST['comment']))?$_POST['comment']:null;
$status_id = (!empty($_POST['statsid']))?$_POST['statsid']:null;
$insert = "INSERT INTO `comments`(`cmt_comment`,`cmt_status`, `cmt_time`)VALUES(:comment, :status, :time)";
$inserq = $pdo->prepare($insert);
$inserq->bindValue(':comment', $content);
$inserq->bindValue(':status', $status_id);
$inserq->bindValue(':time', $time);
$inserq->execute();
$lastid = $pdo->lastInsertId();
$sel = "SELECT * FROM comments
LEFT JOIN status ON comments.cmt_status = status.sts_id
LEFT JOIN members ON members.mem_id = status.sts_mem
WHERE comments.cmt_id = :lastid";
$seq = $pdo->prepare($sel);
$seq->bindValue(':lastid', $lastid);
$seq->execute();
$sef = $seq->fetch();
?>
<div class="comment-flex-holder">
<div class="comment-img-thumb">
<?php if($sef['mem_image'] == null){ ?>
<img src="images/user.png" height="30" width="30">
<?php }else{ ?>
<img src="users/<?php echo $sef['mem_image']; ?>" height="30" width="30">
<?php } ?>
</div>
<div class="showbox"><font color="#5B5899" style="font-size: 12px"><b><?php echo $sef['mem_name']; ?></b></font> <?php echo $sef['cmt_comment']; ?><br />
<font style="font-size:12px">Like · Reply · Just now</font></div>
</div>
<br />

Since, While Loop having n numbers of form. So, each form & input values will have different IDs. In your question, same ID is declared to each and every input. So, Multiple IDs with same name are not allowed. ID can't be same.
First, you need to change each and every input ID. More simple way, Append Status ID to each ID. It will automatically get changed.
If you want to use this answer, then you need to copy my answer as it is. Rather than, modifying in your code. Because, You may leave few lines and later on outcome will come as "Not Working". So, Try this Code. If any problem, Feel free to ask.
Updated Code
<script>
function ajaxFunction(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
$('.commentarea').keydown(function(event) {
var id = $(this).attr('id');
var status_id = id.replace("postcomment_", "");
if ($.trim($("#postcomment_"+status_id).val())) {
if (event.keyCode == 13) {
event.preventDefault();
$("form#form_id_"+status_id).on('submit', function (e) {
e.preventDefault();
var comment = $('#postcomment_'+status_id).val();
var statsid = status_id;
var myData = {"comment": comment, "statsid": statsid};
$.ajax({
url: "post-comment.php",
type: "POST",
data: myData,
success: function (data, status, xhr) {
$(".showbox").html(data); // output result
$('#postcomment').val();
}
});
});
}
}
});
}
</script>
<div class="stats-cont">
<?php
$get_sts = "SELECT * FROM status LEFT JOIN members ON status.sts_mem = members.mem_id ORDER BY sts_time DESC";
$get_stq = $pdo->prepare($get_sts);
$get_stq->execute();
while($get_stf = $get_stq->fetch()){ extract($get_stf);
$get_cmts = "SELECT * FROM comments WHERE cmt_status = :status ORDER BY cmt_id ASC";
$get_cmtq = $pdo->prepare($get_cmts);
$get_cmtq->bindValue(':status', $sts_id);
$get_cmtq->execute();
$total_cmts = $get_cmtq->rowCount();
$fetch_cmts = $get_cmtq->fetch();
?>
<div class="status-note-block status-container">
<div class="member-name-container">
<div class="mem-img-thumb">
<?php if($mem_image == null){ ?>
<img src="images/user.png" height="40" width="40">
<?php }else{ ?>
<img src="users/<?php echo $mem_image; ?>" height="40" width="40">
<?php } ?>
</div>
<div class="member-name"><?php echo $mem_name; ?><br>
<small>
<?php if((date("Y-m-d", strtotime($sts_time))) == $curr_date){ echo "Today"; }else if((date("Y-m-d", strtotime($sts_time))) == $yest){ echo "Yesterday"; }else{ echo date("jS F", strtotime($sts_time)); } ?>
<?php echo date("h:i a", strtotime($sts_time)); ?> </small> </div>
</div>
<div class="status-block"><?php echo $sts_status; ?></div>
</div>
<div class="comment-block">
<div class="comment-reaction-holder"></div>
<div class="commet-field-holder">
<div class="comment-img-thumb">
<?php if($mem_image == null){ ?>
<img src="images/user.png" height="30" width="30">
<?php }else{ ?>
<img src="users/<?php echo $mem_image; ?>" height="30" width="30">
<?php } ?>
</div>
<div class="showbox"></div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width cmtform" id="form_id_<?=$sts_id?>">
<input type="hidden" name="status_id" value="<?php echo $sts_id; ?>" id="statsid_<?=$sts_id?>" />
<textarea name="comment" placeholder="Give a comment..." class="comment-field commentarea" id="postcomment_<?=$sts_id?>" onclick='ajaxFunction()'></textarea>
</form>
</div>
</div>
<?php } ?>
Edit 1
<script>
function ajaxFunction(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
$('.commentarea').keydown(function(event) {
var id = $(this).attr('id');
var status_id = id.replace("postcomment_", "");
if ($.trim($("#postcomment_"+status_id).val())) {
if (event.keyCode == 13) {
event.preventDefault();
postcomment(status_id);
}
}
});
function postcomment(status_id){
var comment = $('#postcomment_'+status_id).val();
var statsid = status_id;
var myData = {"comment": comment, "statsid": statsid};
$.ajax({
url: "post-comment.php",
type: "POST",
data: myData,
success: function (data, status, xhr) {
$(".showbox").html(data); // output result
$('#postcomment').val();
}
});
}
}
</script>

to maintain uniqueness in comment box you should use counter. that will create dynamic name and id. same you need to fetch in ajax call $(this).attr('data-counter')
you can check below code and set according to your need.
<script>
function ajaxFunction(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
$('.postcomment').keydown(function(event) {
if($.trim($(".postcomment").val())) {
if(event.keyCode == 13) {
event.preventDefault();
$("form.cmtform").submit();
}
}
});
$("form.cmtform").on('submit', function(e) {
e.preventDefault();
var counter_val = $(this).attr('data-counter');
var comment = $('#postcomment_' + counter_val).val();
var statsid = $('#statsid_' + counter_val).val();
var myData={"comment":comment, "statsid":statsid};
$.ajax({
url : "post-comment.php",
type: "POST",
data : myData,
success: function(data,status,xhr){
$(".showbox").html(data); // output result
$('#postcomment_' + counter_val).val();
}
});
});
}
</script>
<div class="stats-cont">
<?php
$get_sts = "SELECT * FROM status LEFT JOIN members ON status.sts_mem = members.mem_id ORDER BY sts_time DESC";
$get_stq = $pdo->prepare($get_sts);
$get_stq->execute();
$counter = 1;
while($get_stf = $get_stq->fetch()){ extract($get_stf);
$get_cmts = "SELECT * FROM comments WHERE cmt_status = :status ORDER BY cmt_id ASC";
$get_cmtq = $pdo->prepare($get_cmts);
$get_cmtq->bindValue(':status', $sts_id);
$get_cmtq->execute();
$total_cmts = $get_cmtq->rowCount();
$fetch_cmts = $get_cmtq->fetch();
?>
<div class="status-note-block status-container">
<div class="member-name-container">
<div class="mem-img-thumb">
<?php if($mem_image == null){ ?>
<img src="images/user.png" height="40" width="40">
<?php }else{ ?>
<img src="users/<?php echo $mem_image; ?>" height="40" width="40">
<?php } ?>
</div>
<div class="member-name"><?php echo $mem_name; ?><br>
<small>
<?php if((date("Y-m-d", strtotime($sts_time))) == $curr_date){ echo "Today"; }else if((date("Y-m-d", strtotime($sts_time))) == $yest){ echo "Yesterday"; }else{ echo date("jS F", strtotime($sts_time)); } ?>
<?php echo date("h:i a", strtotime($sts_time)); ?> </small> </div>
</div>
<div class="status-block"><?php echo $sts_status; ?></div>
</div>
<div class="comment-block">
<div class="comment-reaction-holder"></div>
<div class="commet-field-holder">
<div class="comment-img-thumb">
<?php if($mem_image == null){ ?>
<img src="images/user.png" height="30" width="30">
<?php }else{ ?>
<img src="users/<?php echo $mem_image; ?>" height="30" width="30">
<?php } ?>
</div>
<div class="showbox"></div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width cmtform" data-counter="<?php echo $counter;?>">
<input type="hidden" name="status_id_<?php echo $counter;?>" value="<?php echo $sts_id; ?>" id="statsid_<?php echo $counter;?>" />
<textarea name="comment_<?php echo $counter;?>" placeholder="Give a comment..." class="postcomment comment-field commentarea" id="postcomment_<?php echo $counter;?>" onclick='ajaxFunction()'></textarea>
</form>
</div>
</div>
<?php
$counter++;
}
?>
Cheers !!

Related

Filter date from data base with ajax and jquery with the help of form?

I have four file in php first one is feedback that contain data table where I try to display my data feedback.php are below
<?php
error_reporting(E_ALL);
ini_set('display_error',1);
include_once('header.php');
//include_once('sidemenu.php');
require_once('Class_Library/class_Feedback.php');
?>
<?php
$obj = new Feedback();
//$clientid = $_SESSION['clientId'];
$feedbackdata = $obj->GetAllFeedback();
if($feedbackdata['success']==1)
{
$data=$feedbackdata['data'];
//print_r($data);
}
else {
$data=[];
}
//print_r($fedbackdata);
//die;
?>
<style>
.dataTables_filter {
float: right;
}
.pagination{
float: right;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="js/home_page.js"></script>
<script>
$(document).ready(function () {
var startdate = document.getElementById("feedbackstartdate").value;
var enddate = document.getElementById("feedbackenddate").value;
var site = document.getElementById("site").value;
// alert("end "+enddate);
// alert("start "+startdate);
$feedbackdata=showfeedbacklist(startdate, enddate,site);
});
</script>
<script>
function feedbackindex()
{
//alert("hello, your code is here");
var startdate= document.getElementById("fromDate").value;
var enddate= document.getElementById("toDate").value;
var site= document.getElementById("site").value;
//alert('start '+startdate);
//alert('enddate '+enddate);
if (startdate == "")
{
window.alert("Please select From date.");
document.getElementById("fromDate").focus();
return false;
}
if (enddate == "")
{
window.alert("Please select To date.");
document.getElementById("toDate").focus();
return false;
}
if (startdate > enddate )
{
window.alert("From date can't be greater then To date.");
document.getElementById("toDate").focus();
return false;
}
$feedbackdata = showfeedbacklist(startdate, enddate,site);
/**************************************************************************/
}
</script>
<!--page content -->
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default" style="margin-top: 25px;">
<div class="panel-heading">
<h4>Feedback</h4>
</div>
<form id="formdata" method="post">
<div class="col-md-4">
<div class="form-group">
<label for="pwd">From: </label>
<input type="date" id="fromDate" name="FSDate" size="20" class="form-control input" placeholder="mm/dd/yyyy"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="pwd">To: </label>
<input type="date" id="toDate" class="form-control" name="FSDate" size="20" placeholder="mm/dd/yyyy"/>
</div>
</div>
<div class="col-md-4" style="margin-top:20px;">
<div class="form-group">
<input type="hidden" name="feedbackstartdate" id="feedbackstartdate" value="<?php echo date('Y-m-d', strtotime("-7 days")); ?>">
<input type="hidden" id="feedbackenddate" name="feedbackenddate" value="<?php echo date('Y-m-d', strtotime("-1 days")); ?>">
<input type="" id="site" name="site" value="<?php echo SITE; ?>"
<center><button type="button" class="btn btn-info" onclick="return feedbackindex();">Submit</button></center>
</div>
</div>
</form>
<div class="panel-body">
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example"> <thead>
<tr>
<th>Cutomer Name</th>
<th>Location</th>
<th>Visit Type</th>
<th>Visit By</th>
<th>Visit Dtae</th>
<th>Feedback</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
for ($i = 0; $i < count($data); $i++) {
?>
<tr>
<td><?php echo $data[$i]['CustomerName'];?></td>
<td><?php echo $data[$i]['clientCity']; ?></td>
<td><?php echo $data[$i]['TaskType']; ?></td>
<td><?php echo $data[$i]['visitByName']; ?></td>
<td><?php echo $data[$i]['visitDate'];?></td>
<td><?php
$datafeedback = $data[$i]['feedbackValue'];
if($datafeedback==null)
{
echo 'pending';
}
else{
if($datafeedback==5)
{
echo '<img src="images/feedback/greenSmile.png" alt="send feedback by data"style="width:50px;height:50px;" />';
}
elseif ($datafeedback==4) {
echo '<img src="images/feedback/smile.png" alt="send feedback by data"style="width:50px;height:50px;" />';
}
elseif ($datafeedback==3) {
echo '<img src="images/feedback/redsmile.png" alt="send feedback by data"style="width:50px;height:50px;" />';
}
}
?></td>
<td>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!--/page content -->
<?php include 'footer.php'; ?>
My code is proper work when we try to display to data but when we try to filter I don't know how to work that and my link file of js are
function showfeedbacklist(startdate, enddate, site)
{
var postData =
{
"startdate":startdate ,
"enddate": enddate,
"site" :site
};
var dataString = JSON.stringify(postData);
// alert(dataString);
$.ajax({
type: "post",
// dataType: "json",
//contentType: "application/json; charset=utf-8",
url:site+"Link_Library/link_getfeedbacklist.php",
data: {"mydata": dataString},
success: function (response) {
var respdata = response;
// alert(respdata);
console.log(respdata);
},
error: function (e) {
alert(e);
console.log(e.message);
}
});
}
and my ajax page where i am send to data are
<?php
require_once('../Class_Library/class_Feedback.php');
$obj = new Feedback();
if (!empty($_POST["mydata"])) {
$jsonArr = $_POST["mydata"];
// echo $jsonArr;
$data = json_decode($jsonArr, true);
//print_r($data);
//die;
if (!empty($data)) {
$fromdt1 = $data['startdate'];
$fromdt = date("Y-m-d H:i:s", strtotime($fromdt1));
// echo "statrt date-".$fromdt;
$enddte1 = $data['enddate'];
$enddte2 = date("Y-m-d", strtotime($enddte1));
$date123 = date_create($enddte2 ." 23:59:59", timezone_open("Asia/Kolkata"));
$enddate = date_format($date123, "Y-m-d H:i:s");
// echo "endd date-".$enddt;
$result = $obj->graphGetFeedbacklist($enddate, $fromdt);
// echo "<pre>";
// print_r($res);
}
}
?>
And my sql class file are last one that is
<?php
if (!class_exists('Connection_Communication')) {
include_once('class_connect_db_Communication.php');
}
class Feedback {
public $DB;
public function __construct() {
$db = new Connection_Communication();
$this->DB = $db->getConnection_Communication();
}
function GetAllFeedback() {
try {
$query = "select site.*,list.Service_Type,list.Id,(select Task_Type from tbl_task_type where Auto_Id = list.Service_Type) as TaskType,DATE_FORMAT(start_date,'%d-%b-%Y') as visitDate,CONCAT(usr.First_Name,' ',usr.Last_Name) as visitByName,(select SUM(parameter_value)/(select count(parameterId) from tbl_visit_feedback_parameter where parameterId < (select MAX(parameterId) from tbl_visit_feedback_parameter)) from tbl_visit_feedback_data where parameter_id < (select MAX(parameterId) from tbl_visit_feedback_parameter) and task_id = site.task_id) as feedbackValue from tbl_site_visit_detail as site JOIN tbl_master_user as usr ON site.employee_id = usr.ID JOIN tbl_tasks_list as list ON site.task_id = list.Task_Id where visit_status = '1'";
$stmt = $this->DB->prepare($query);
// $stmt->bindParam(':sd', $startdate, PDO::PARAM_STR);
// $stmt->bindParam(':ed', $enddate, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($row) {
require_once 'class_master.php';
$masObj = new Master();
$farray = array();
for ($i = 0; $i < count($row); $i++) {
$refid = $row[$i]['Id'];
$Service_Type = $row[$i]['Service_Type'];
$result = $masObj->getTaskDetail($refid, $Service_Type);
if ($result['success'] == 1) {
$data = $result['data'];
$temp = $data + $row[$i];
array_push($farray, $temp);
}
}
if (!empty($farray)) {
$response['success'] = 1;
$response['data'] = $farray;
} else {
$response['success'] = 0;
$response['message'] = 'No data found.';
}
} else {
$response['success'] = 0;
$response['data'] = 'error while fetching data ';
}
} catch (Exception $ex) {
$response['success'] = 0;
$response['data'] = $ex->getMessage();
}
return $response;
}
}
?>
I am new in codding area so i don't know how to handle that type problem and I sow so many references but I have no idea what happen there.

Post request not changing value in DB

I can't seem to figure out why my status doesn't change. I am trying to get my chat activation button to work on click, and send a post request to a specified url via jQuery. Can I even do that without using an actual form or sth??
jQuery:
$(".model_chat_button").css('cursor', 'pointer').click(function() {
var model_id = $(this).parent().attr('id').split('model_')[1];
var active = 1;
if ($(this).attr('rel') == '1')
{
active = 0;
$(this).attr('rel', '0');
$(this).find("img").attr('src', $(this).find("img").attr('src').replace('chat_active', 'chat_inactive'));
}
else
{
$(this).attr('rel', '1');
$(this).find("img").attr('src', $(this).find("img").attr('src').replace('chat_inactive', 'chat_active'));
}
$.post(base_url + lang + '/chats/activateModel',{model_id: model_id, active: active});
});
In my controller chats.php:
public function activateModel()
{
if ($this->session->userdata('is_admin') && $this->input->post('model_id'))
{
$model = new Model($this->input->post('model_id'));
$model->chat_active = $this->input->post('active')? 1 : 0;
$model->save();
}
}
And my view:
<div id="<?php echo $model->id; ?>">
<div class="model_chat_button" rel="<?php echo $model->chat_active? 1 : 0;?>">
<?php if ($model->chat_active): ?>
<?php if (! $this->session->userdata('is_admin')): ?>
<a href="<?php echo site_url(); ?>/chat/<?php echo $model->id; ?>" title="<?php echo $this->lang->line('chat_with'); ?> <?php echo $model->name; ?>">
<?php endif; ?>
<img src="<?php echo base_url(); ?>assets/images/design/button_chat_active.png" alt="Chat" />
<?php if (! $this->session->userdata('is_admin')): ?>
</a>
<?php endif; ?>
<?php else: ?>
<img src="<?php echo base_url(); ?>assets/images/design/button_chat_inactive.png" alt="Chat" />
<?php endif; ?>
</div>
</div>
So from what I can tell from the network tab, it does send a post request to the chats/activateModel URL, but the model ID is not added. What am I missing here?

noty jQuery - notification apearence

I want to show notification on delete all button. I use noty jquery while I click on delete all button only button of notification show not full and page redirected I am using codeigniter what I do the code below like as
// view of my file
<?php $page_url = $this->uri->segment(2);?>
<div id="contents" style="width:1024px;">
<div class="buttons">
<div><button class="button-choose-2 pure-button" id="delete">Delete</button></div>
<div>
<input type="button" class="button-choose-2 pure-button" name="CheckAll" value="Check All" onClick="checkAll(document.myform.list)"></div>
<div>
<input type="button" class="button-choose-2 pure-button" name="UnCheckAll" value="Uncheck All" onClick="uncheckAll(document.myform.list)"></div>
<div><button class="button-choose-2 pure-button">Add</button></div>
</div>
<br style="clear:both;">
<?php $this->load->view("includes/left_menu") ?>
<form name="myform" id="myform">
<div class="right-contents">
<table width="98%" cellpadding="5">
<tr class="right-top">
<td width="8%"> </td>
<td width="21%">Name</td>
<td width="18%">Image</td>
<td width="38%">Designation</td>
<td colspan="3" align="center">Actions</td>
</tr>
<?php if(is_array($items)): ?>
<?php foreach($items as $row){?>
<tr>
<td width="8%"><input type="checkbox" id="list" name="del[]" value="<?php echo $row->team_id;?>" class="del"></td>
<td width="21%"><?php echo $row->name?></td>
<td width="18%"><img src="assets/icons/<?php echo $row->photo?>" width="100" height="70"></td>
<td width="38%"><?php echo $row->designation?></td>
<td width="5%"><img src="assets/img/edit.png"></td>
<td width="5%"><img src="assets/img/27935.png"></td>
<td width="5%"><a href="parexons_con/delete/<?php echo
$row->team_id;?>/<?php echo $page_url ?>/<?php echo 'team'; ?>/<?php echo 'team_id'; ?>"><img src="assets/img/Delete-icon.png"></a></td>
</tr>
<?php } endif; ?>
</table>
</div>
</form>
<script>
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}
function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
</script>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#delete").on('click', function(e) {
var r = confirm("are you sure you want to delete this");
if (r==true) {
e.preventDefault();
var ids = $('.del:checked').map(function () {
return this.value;
}).get();
console.log(ids);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>parexons_con/delete_all",
data: 'id=' + ids,
type: "POST",
success: function (result) {
noty({text: 'thank you for providing information', type: 'success',settimeout:5000});
setTimeout(window.location.reload(), 1200000);
}
});
}
});
});
</script>
and controller are
function delete_all($del_id = NULL, $view = NULL, $table = NULL, $field_name = NULL)
{
$error = 'error';
$msg = 'deleted';
$ids = $this->input->post('id');
$explode = explode(",", $ids);
foreach ($explode as $id) {
$query = $this->parexons_model->delete_row('team', array('team_id' => $id));
}
if ($query) {
http_response_code(redirect("my_controller/team"), 5000);
} else {
redirect("my_controller/team");
}
}
Wrong syntax of jquery ajax data it would be
data: {id: ids},
Second do not redirect of controller function you need to pass some value to ajax success like
function delete_all($del_id = NULL, $view = NULL, $table = NULL, $field_name = NULL) {
$error = 'error';
$msg = 'deleted';
$ids = $this->input->post('id');
$explode = explode(",", $ids);
foreach ($explode as $id) {
$query = $this->parexons_model->delete_row('team', array('team_id' => $id));
}
if ($query) {
echo "success";
} else {
echo "false";
}
}

How Do i Loop Js with mysql while loop

Hey Guys i need to ask is that how can i loop the javascript with the while loop
As My code is this
$i=0;
while($row = mysqli_fetch_array($result)) {
echo '<div class="grid_1_of_4 images_1_of_4" >
<form method="post" action="......">
<a class = "popup-link" href = "'.$row['shade_enlarged_img'].'" alt = "" title = "'.$row['shade_desc'].'">
<img src="'.$row['shade_img'].'" alt="" title = "click to enlarge"/> </a>
<h2>'.$row['shade_desc'].'</h2>
<p style="font-size:0.95em"><b>Code: '.$row['shade_code'].'</b></p>
<p>Category: '.$row['categories'].'</p>';
$code=$row['shade_code'];
$result_quantity = mysqli_query($con,"SELECT ...........);
$num_of_rows=mysqli_num_rows($result_quantity);
$count=0;?>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint<?php echo $i; ?>").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "getprice.php?brand=<?php echo $row['brand_name']; ?>&category=<?php echo $row['categories'];?>&q="+str;
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint<?php echo $i; ?>").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script> <?php
echo '<p style="font-size:0.71em">Available Packaging: <select name="product_qty" onchange="showUser(this.value)" style="margin-left:4px; font-size:1.02em;">
<option value=""></option>';
while($row_quantity = mysqli_fetch_array($result_quantity)) {
echo '<option value="'.$row_quantity['quantity'].'">'.$row_quantity['quantity'].' '.$row_quantity['quantity_unit'].'</option>';
}
echo '</select></p>';
echo '<div id="txtHint'.$i.'"><b>Person info will be listed here.</b></div>';
echo '</p>';
echo '<p style="font-size:0.71em">Quantity: <input type="number" style="display:inline; width:50px;" name="number_of_units" min="1"></p>';
echo '<button class="button"><span class="cart-button"><img src="images/cart.jpg" alt="" />Add to Cart</span> </button>
<input type="hidden" name="product_code" value="'.$row['shade_code'].'" />
</form>
</div>'; $i++;
the Code Works Well but as i'm calling all the items by while loop from mysqldatabase so when i run this code this only works on the 1st item and rest does'nt work..
Watch This Images For A Quick Veiw http://imgur.com/2qM0FzX
I think you will have a problem with #products because you can't have the same id="products" over and over again otherwise the jQuery doesn't know which to switch. Actually, same with #priceInput. Try adding the auto-incrementing $i as demonstrated below.
<?php
$i = 0;
while($row = mysqli_fetch_array($result)) { ?>
<div class="grid_1_of_4 images_1_of_4" >
<form method="post" action="page.php">
<a class = "popup-link" href = "<?php echo $row['shade_enlarged_img']; ?>" alt = "" title = "<?php echo $row['shade_desc']; ?>">
<img src="<?php echo $row['shade_img']; ?>" alt="" title = "click to enlarge"/> </a>
<h2><?php echo $row['shade_desc']; ?></h2>
<p style="font-size:0.95em"><b>Code: <?php echo $row['shade_code']; ?></b></p>
<p>Category: <?php echo $row['categories']; ?></p>
<script>
$(function () {
$('#products<?php echo $i; ?>').change(function () {
$('#priceInput<?php echo $i; ?>').val($('#products<?php echo $i; ?> option:selected').attr('data-price'));
});
});
</script>
<p style="font-size:0.71em">Available Packaging: <select id="products<?php echo $i; ?>" name="product_qty" style="margin-left:4px; font-size:1.02em;" onChange="ShowInfo('<?php echo $i; ?>','<?php echo $row['brand_name']; ?>','<?php echo $row['categories']; ?>')">
<?php
$code = $row['shade_code'];
$result_quantity = mysqli_query($con,"SELECT ............");
$num_of_rows = mysqli_num_rows($result_quantity);
$count = 0;
while($row_quantity = mysqli_fetch_array($result_quantity)) { ?>
<option value="<?php echo $row_quantity['quantity']; ?>" data-price="<?php echo $row_quantity['price']; ?>"><?php echo $row_quantity['quantity'].' '.$row_quantity['quantity_unit']; ?></option><?php
} ?>
</select></p>
<div id="txtHint<?php echo $i; ?>"><b>Person info will be listed here.</b></div>
Price :<input type="text" name="price" value="" id="priceInput<?php echo $i; ?>" disabled="disabled"/>
<p style="font-size:0.71em">Quantity: <input type="number" style="display:inline; width:50px;" name="number_of_units" min="1"></p>
<button class="button"><span class="cart-button"><img src="images/cart.jpg" alt="" />Add to Cart</span> </button>
</form>
</div><?php
$i++;
} ?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script>
function ShowInfo(IdNum,RowBrand,RowCat) {
// Get the value of the selected dropdown
var SelVal = $('#products'+IdNum).val();
$.ajax({
type : 'GET',
url:"getprice.php?brand="+RowBrand+"&category="+RowCat+"&q="+SelVal;
success: function(result){
$('#txtHint'+IdNum).html(result);
}
});
}
</script>
Try the .= which will continue to add the latest results from you mysqli_fetch_array query.
Then just echo that summed up value you assigned to $just_a_variable out to the page or back to ajax etc.
<?php
$just_a_variable = '';
$just_a_variable .= '<p style="font-size:0.71em">Available Packaging: <select id="products" name="product_qty" style="margin-left:4px; font-size:1.02em;">';
while($row_quantity = mysqli_fetch_array($result_quantity)) {
$just_a_variable .= '<option value="'.$row_quantity['quantity'].'" data-price="'.$row_quantity['price'].'">'.$row_quantity['quantity'].' '.$row_quantity['quantity_unit'].'</option>';
}
$just_a_variable .= '</select></p>';
$just_a_variable .= ' Price :<input type="text" name="price" value="'.$row_quantity['price'].'" id="priceInput" disabled="disabled"/>';
echo $just_a_variable;
?>
that is because the mysql_fetch_array function returns one row at a time. If you want all the rows you should iterate over the results
$row = mysqli_fetch_array($result_quantity);
$total = mysql_num_rows($variable_resultfrom_sql_query);
while($row = mysql_fetch_array($variable_resultfrom_sql_query))

Jquery, ajax won't alert some message

So I am doing a shopping cart site, using CodeIgniter on backend
Here is the catch, I loop the product list, with 'add to cart' button, inside a form tag.
So let's say, I have 5 products to display, there will be 5 form tag as:
<?php foreach ($products as $vid):?>
<form id='cart' method='post' action='<?php echo base_url();?>cart/add'>
<input type='hidden' id='vid' name='vid' value='<?php echo $vid['id'];?>'/>
<div class="video_box">
<div class="video">
<a href="#<?php echo $vid['id'];?>" name='modal'>
<img src="<?php echo base_url(); ?>assets/images/<?php echo $vid['video_thumbnail'];?>" alt="<?php echo $vid['title'];?>" border="0" height='150' width='100' />
</a>
</div>
<div class="video_checkbox">
<?php if($this->session->userdata('nric')===FALSE ) {
echo "Please Login to Rent/Purchase"; } else { ?>
<input type='image' id='btn-add' src="<?php echo base_url(); ?>assets/images/rent_btn.png" alt="Rent" border="0" />
<?php } ?>
</div>
</form>
<?php endforeach;?>
And my javascript/jquery script:
<script type="text/javascript">
$(document).ready(function() {
$("#btn-add").click(function() {
var action = $("#cart").attr('action');
var form_data = {
vid : $("#vid").val(),
is_ajax : 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response)
{
if(response == 'exists')
{ alert("This item is in your cart already! You can only add 1 same item once");
}
if(response == 'newses')
{ alert("This item has been added succesfully!");
document.location.reload(true);
}
if(response == 'new_added')
{
alert("This item has been added succesfully1!");
document.location.reload(true);
}
}
});
return false;
});
});
</script>
As my controller (in form action) localhost/site/cart/add:
public function add() {
$vid=$_POST['vid'];
if($this->session->userdata('shoppingCart')===FALSE)
{
$shoppingCart = array (
$vid => 1
);
$this->session->set_userdata('shoppingCart',$shoppingCart);
echo 'newses';
} else {
$tmp = $this->session->userdata('shoppingCart');
if(array_key_exists($vid, $tmp)) {
//only allow user to add qty:1 to the same product
echo 'exists';
} else {
$tmp[$vid]= 1;
$this->session->set_userdata('shoppingCart',$tmp);
echo 'new_added';
}
}
}
So the problem now, I can add the product to my shopping cart with no problem, all the stuff inside cart/add controller runs fine, the output is as expected.
But I need to alert the customer whether the product has been added or failed (as shown in my jquery code).
Problem is, the script will run fine only for the 1st created.
Means, if there is 5 products, it will loop and create 5 form-tag right, only the 1st form-tag will run the script successfully (after the button is clicked). The 2nd-5th form will redirect to other blank page, echoing the result (e.g "newses", "new_added", "exists"), not alerting the user as stated in the script (but the shopping cart function works properly).
What did I do wrong?
Try this
<?php foreach ($products as $vid):?>
<form id='cart' method='post' action='<?php echo base_url();?>cart/add'>
<input type='hidden' class='vid' name='vid' value='<?php echo $vid['id'];?>'/>
<div class="video_box">
<div class="video">
<a href="#<?php echo $vid['id'];?>" name='modal'>
<img src="<?php echo base_url(); ?>assets/images/<?php echo $vid['video_thumbnail'];?>" alt="<?php echo $vid['title'];?>" border="0" height='150' width='100' />
</a>
</div>
<div class="video_checkbox">
<?php if($this->session->userdata('nric')===FALSE ) {
echo "Please Login to Rent/Purchase"; } else { ?>
<input type='image' class='btn-add' src="<?php echo base_url(); ?>assets/images/rent_btn.png" alt="Rent" border="0" />
<?php } ?>
</div>
</form>
<?php endforeach;?>
Jquery
$(document).ready(function() {
$(".btn-add").click(function() {
var $this = $(this);
var $form = $this.parents('form');
var action = $form.attr('action');
var vid = $form.find('input.vid').val();
var form_data = {
vid : vid,
is_ajax : 1
};
$.ajax({
type : "POST",
url : action,
data : form_data,
success : function(response) {
if (response == 'exists') {
alert("This item is in your cart already! You can only add 1 same item once");
}
if (response == 'newses') {
alert("This item has been added succesfully!");
document.location.reload(true);
}
if (response == 'new_added') {
alert("This item has been added succesfully1!");
document.location.reload(true);
}
}
});
return false;
});
});

Categories

Resources