I created a button to generate a popup which shows some events.And past few days I was trying to show the count of users which visted the events.
I tried some of the extensions too...Like
Counter
pcviewcounter
etc,
But I need to store the ip address ,eventid and time in my database.
Can anyone please help me with this???
View for button
<div class="modal fade" id="detailsOffeEve" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
</div>
<script>
function showdetails(id)
{ // alert(id);
$('#detailsOffeEve').load('<?php echo Yii::app()->baseUrl; ?>/offerEvents/popup/'+id);
}
</script>
And action popup
public function actionPopup($id)
{
//$this->render('/offerEvents/Details',array(
//'model'=>OfferEvents::model()->findByAttributes(array('id'=>$id)), ));
$OfferEventsList = OfferEvents::model()->findAllByAttributes(array('id' => $id));
foreach($OfferEventsList as $Listdata)
{ $titnw=$Listdata['title']; $details=$Listdata['description'];
$discountper=$Listdata['discountper']; $discountperamt=$Listdata['discountperamt'];
$strdaate=$Listdata['startdate']; $enddaate=$Listdata['enddate']; $evoftype=$Listdata['type']; }
$cmuserid=$Listdata['createdby'];
if($Listdata['createdby']==0){ $createdbyname="Admin"; } else { $createdbyname=$Listdata->company->companyname; }
$locationnw=$Listdata->location;
$offrimage=$Listdata->image;
if($offrimage!=""){ $imgUrls=$offrimage; } else { $imgUrls='image-not-available.png'; }
$infowinimgpaths='theme/images/OfferEvents/orginal/'.$imgUrls;
if (file_exists($infowinimgpaths)) { $infowinimgpathSrcs=Yii::app()->baseUrl.'/'.$infowinimgpaths; } else
{ $infowinimgpathSrcs=Yii::app()->baseUrl.'/theme/images/OfferEvents/image-not-available.png'; }
if (Yii::app()->user->id!='' && Yii::app()->user->id!=1){
$subcribeemailid=Yii::app()->user->email; $logsts=1;
$countsubscribe = Newsfeeds::model()->countByAttributes(array('emailid' => $subcribeemailid,'cuserid' => $cmuserid));
} else { $subcribeemailid=''; $countsubscribe=0; $logsts=0; }
$PopupdetailText='<div class="modal-dialog-1">
<div class="modal-content">
<div class="modal-header login_modal_header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 class="modal-title" id="myModalLabel">'.$titnw.' </h2>
</div>
<div class="container-1">
<div class="row">
<div class="col-sm-7 detail-text">
<h2 class="title"> ';
if($evoftype==0){ $PopupdetailText.='Offer Price: '.$discountperamt.'
<font style="font-size: 15px;">[ Up To '.$discountper.'% Discount ]</font>'; }
$PopupdetailText.='</h2><p>Details: </p>
<p>'.$details.'</p>
<p>Location: '.$locationnw.'</p>
<p>Expires in: '.$enddaate.'</p>';
if($countsubscribe==0){
$PopupdetailText.='<p>Shared by: '.$createdbyname.'
<button type="button" class="btn btn-success btn-xs" Onclick="subcribefeed('.$logsts.','.$cmuserid.')" >Subscribe NewsFeed</button></p>';
} else {
$PopupdetailText.='<p>Shared by: '.$createdbyname.'
<button type="button" class="btn btn-success disabled btn-xs" >Already Subscribed NewsFeed</button></p>';
}
$PopupdetailText.='<div class="form-group" id="subcribefrm" style="display:none;background-color: #eee; padding: 12px; width: 82%;">
<input type="text" id="subemailid" placeholder="Enter EmailID here" value="'.$subcribeemailid.'" style="width: 100%;" class="form-control login-field">
<br/>
Subscribe Feeds </div> ';
// if($evoftype==0){ $PopupdetailText.='<p>Offer Price:<b> $'.$discountperamt.'</b></p>'; }
$PopupdetailText.='<p>';
$PopupdetailText .= $this->renderPartial('/comments/share', array('postid' => $id),TRUE);
$PopupdetailText.='<img src="'.Yii::app()->baseUrl.'/theme/site/images/comments.png"/>Comments
<img src="'.Yii::app()->baseUrl.'/theme/site/images/share.png"/>Share</p>
<br/>';
$userComment = new Comments;
$PopupdetailText .= $this->renderPartial('//comments/_form', array('model' => $userComment,'id'=>$id),TRUE,TRUE);
// $PopupdetailText .= $this->renderPartial('//comments/view', array('model' => $userComment,'id'=>$id),TRUE);
$PopupdetailText.='</div>
<div class="col-sm-5">
<img src="'.$infowinimgpathSrcs.'" width="100%"/>
</div>
</div>
</div>
<div class="clearfix"></div>
<div class="modal-footer login_modal_footer">
</div>
</div>
</div>
<script>
function subcribefeed(staus,cid)
{
if(staus==0){
$("#subcribefrm").toggle(); }
else { subcribefeedAdd(cid); }
}
function subcribefeedAdd(cid)
{
subusremail=$("#subemailid").val();
var re = /[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if (subusremail == "" || !re.test(subusremail))
{ alert("Invalid EmailID ."); }
else {
postData ={
"email" :subusremail,
"cid" :cid
}
$.ajax({
type: "POST",
data: postData ,
url: "'.Yii::app()->baseUrl.'/newsfeeds/create",
success: function(msg){
if(msg=="Success"){ showdetails('.$id.'); alert("news feed subscribe successfully."); }
else if(msg=="available"){ alert("Already subscribe News Feed for this Commercial user."); }
else { alert("Error ."); }
}
});
}
}
</script> ';
echo $PopupdetailText;
}
I just got the answer.I dont know whether the answer is in right method.
I just added the foolwiong code after my action.
**
$view = new Viewcount;
$viewip = Yii::app()->request->getUserHostAddress();
$viewdate = date('Y-m-d');
$view->ipadd = $viewip;
$view->ofrevntid = $id;
$view->visitdate = $viewdate;
$viewlist = Viewcount::model()->findByAttributes(array('ipadd'=>$viewip,'ofrevntid'=>$id,'visitdate'=>$viewdate));
$viewcount = count($viewlist);
if ($viewcount == 0){
$view->save();
}
**
Related
I need to be able to update my sql table from open to close task.
I already wrote code for this but it is not working properly. On the modal it shows 2 'continue' buttons and right now the task table contains two tasks. Can somebody help me?
This is what the modal looks like:
and this is my code:
<?php
if (isset($_POST["closetask"])) {
$close_task_id = mysqli_real_escape_string($con, $_POST["close_task_id"]);
$sql = "UPDATE task SET task_status='closed' WHERE id_task='$close_task_id'";
$result = mysqli_query($con, $sql);
if ($result) {
$_SESSION['success'] = "Task closed";
$_SESSION['text'] = "Task has been closed successfully";
$_SESSION['icon'] = "success";
} else {
$_SESSION['success'] = "Error";
$_SESSION['text'] = "Unkown error, please try again";
$_SESSION['icon'] = "error";
}
}
?>
<?php
$query = "SELECT * FROM task ORDER BY id_task DESC";
$result = mysqli_query($con, $query);
?>
<!-- reject button -->
<form action="task-view.php" method="post" enctype="multipart/form-data">
<div id="rejectModal" class="modal fade" role="dialog" >
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Close this task?</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="d-flex align-items-center justify-content-center form-group" >
<p class="align-items-center text-center" for="company">This button means closing the task. Are you sure you want to continue?</p>
</div>
</div>
<div class="modal-footer">
<?php
while ($row = mysqli_fetch_array($result)) {
if ($row['task_status'] == 'open'){
$check_task = '
<input type="text" name="close_task_id" class="form-control" value="' . $row["id_task"] . '" hidden>
<button class="btn btn-success" type="submit" name="closetask" class="btn btn-success">Continue</button>
</button>
';
}
echo '
<br>
' . $check_task . '
';
}
?>
</div>
</div>
</div>
</div>
</div>
</form>
<!-- end of reject button-->
<?php
if (isset($_SESSION['success']) && $_SESSION['success'] != '') {
?>
<script>
swal({
title: "<?php echo $_SESSION['success']; ?>",
text: "<?php echo $_SESSION['text']; ?>",
icon: "<?php echo $_SESSION['icon']; ?>",
button: "OK",
});
</script>
<?php
unset($_SESSION['success']);
}
?>
Well, after going through your code snippet,
I could see this query
$query = "SELECT * FROM task ORDER BY id_task DESC";
$result = mysqli_query($con, $query);
meaning this fetches all records in the task table, the two continue buttons you see are coming from the while loop
while ($row = mysqli_fetch_array($result)) {
....
}
it logically implies you have two records or rows in your database task table and all the records where retrieved from the table.
When I'm searching the specific name of the image. The rest of the name of the row still showing, but I just want to view only the data from the search. See image below
Display: Select all the data from the database.
<?php$checkQuery = "SELECT `h_business_logo`,`h_business_name`,`h_business_desc` FROM user_bsns WHERE h_isActive = 1 ORDER BY h_business_name DESC";
$checkResult = mysqli_query($db->conn, "$checkQuery")
?>
Card: This card has an animation
<div class="card-body col-lg-12" >
<div class="card-body col-lg-12">
<input class="form-control" id="myInput" type="text" placeholder="Search.." style="float:left; width:25%;">
<button class="btn" style="margin-left: 5px;background-color: #e72329;color: white;"> Search </button>
</div>
<?php
if(mysqli_num_rows($checkResult) > 0):{
}
while($row = mysqli_fetch_array($checkResult)){
?>
<div class="panel" id="myDIV">
<div class="holder flipH" >
<div class="card shadow-none">
<div class="col-sm-0 column <?=$row['h_business_name'];?>" >
<div class="front"style="float:left; >
<img src="<?=$row['h_business_logo']; ?> "
style="height:150px; width:155px; border-radius: 50%; ">
</div>
</div>
<span style= "text-align:center;">
<h5><?=$row['h_business_name'];?></h5>
</span>
<span style="text-align:center;">
<p><?=$row['h_business_desc'];?></p>
</span>
</div>
</div>
</div>
<?php
}
endif;
?>
</div>
<!-- /.card-body -->
</div>
And this one is the function of the search filter.
<script>
$(document).ready(function(){
$(".btn").on("click", function() {
var value = $("#myInput").val();
lastval = "col-sm-5 column "+value;
x = document.getElementsByClassName("column");
$("#myDIV div").filter(function() {
for (i = 0; i < x.length; i++) {
element = x[i];
if (element.className.indexOf(value) == -1){
element.classList.add("nonshow");
element.classList.remove("show");
}
else {
element.classList.add("show");
element.classList.remove("nonshow");
}
}
});
});
});
</script>
Please help me to improve the codes.
Update: I solved my problem using this script(jquery)
update: I used this script in order to search automatically.
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myDiv ").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
});
});
});
I have an error and it says "DataTables warning: table id=table - Ajax error. For more information about this error, please see http://datatables.net/tn/7". After that I went to inspect element and there's 1 error and says "Failed to load resource: the server responded with a status of 404 (Not Found)"
Controller:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class section_controller extends CI_Controller{
public function __construct()
{
parent:: __construct();
$this->load->model('section_model','section');
}
public function index()
{
$this->load->helper('url');
$this->load->view('section_view');
}
public function ajax_list()
{
$list = $this->section_model->get_datatables();
$data = array();
$no = $_POST['start'];
foreach($list as $section) {
$no++;
$row = array();
$row[] = $section->sec_ID;
$row[] = $section->secname;
$row[] = $section->sec;
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)"
title="Edit" onclick="edit_section('."'".$section->sec_ID."'".')"><i
class="glyphicon glyphicon-pencil"></i> Edit</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->section->count_all(),
"recordsFiltered" => $this->section->count_filtered(),
"data" => $data,
);
echo json_encode($output);
}
public function ajax_edit($sec_ID)
{
$data = $this->section->get_by_id($sec_ID);
echo json_encode($data);
}
public function ajax_add()
{
$this->_validate();
$data = array(
'sec_ID' => $this->input->post('sec_ID'),
'secname' => $this->input->post('secname'),
'sec' => $this->input->post('sec'),
);
$insert = $this->section->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$this->_validate();
$data = array(
'sec_ID' => $this->input->post('sec_ID'),
'secname' => $this->input->post('secname'),
'sec' => $this->input->post('sec'),
);
$this->section->update(array('sec_ID' => $this->input->post('sec_ID')),
$data);
echo json_encode(array("status" => TRUE));
}
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('sec_ID') == '')
{
$data['inputerror'][] = 'sec_ID';
$data['error_string'][] = 'ID is required';
$data['status'] = FALSE;
}
if($this->input->post('secname') == '')
{
$data['inputerror'][] = 'secname';
$data['error_string'][] = 'Section name is required';
$data['status'] = FALSE;
}
if($this->input->post('sec') == '')
{
$data['inputerror'][] = 'dob';
$data['error_string'][] = 'Section is required';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
}
?>
Model:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class section_model extends CI_Model{
var $table = 'section';
var $column_order = array('sec_ID','secname','sec',null);
var $column_search = array('secname','sec');
var $order = array('sec_ID'=>'desc');
public function __construct()
{
parent::__construct();
$this->load->database();
}
private function _get_datatables_query()
{
$this->db->from($this->table);
$i = 0;
foreach ($this->column_search as $item) // loop column
{
if($_POST['search']['value']) // if datatable send POST for search
{
if($i===0) // first loop
{
$this->db->group_start(); // open bracket. query Where with
OR clause better with bracket. because maybe can combine with
other WHERE with AND.
$this->db->like($item, $_POST['search']['value']);
}
else
{
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$i++;
}
if(isset($_POST['order'])) // here order processing
{
$this->db->order_by($this->column_order[$_POST['order']['0']
['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
public function count_all()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
public function get_by_id($sec_ID)
{
$this->db->from($this->table);
$this->db->where('sec_ID',$sec_ID);
$query = $this->db->get();
return $query->row();
}
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
}
?>
And the View:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sections</title>
<link rel="stylesheet" href="<?php echo
base_url('assets/bootstrap/css/bootstrap.min.css')?>">
<link rel="stylesheet" href="<?php echo
base_url('assets/datatables/css/jquery.dataTables.min.css')?>">
</head>
<body>
<br>
<div class="container">
<h1>Sections</h1>
<br>
<button class="btn btn-success" onclick="add_section()"><i
class="glyphicon glyphicon-plus"></i> Add Section</button>
<button class="btn btn-default" onclick="reload_table()"><i
class="glyphicon glyphicon-refresh"></i> Reload</button><br><br>
<table id="table" class="table table-striped table-bordered"
cellspacing="0" width="100%">
<thead>
<tr>
<th>Section ID</th>
<th>Section Name</th>
<th>Section</th>
<th>Actions</th>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th>Section ID</th>
<th>Section Name</th>
<th>Section</th>
<th>Actions</th>
</tr>
</tfoot>
</table>
</div>
<script src="<?php echo base_url('assets/jquery/jquery-3.3.1.min.js')?>">
</script>
<script src="<?php echo base_url('assets/bootstrap/js/bootstrap.min.js')?>">
</script>
<script src="<?php echo
base_url('assets/datatables/js/jquery.dataTables.min.js')?>"></script>
<script src="<?php echo
base_url('assets/datatables/js/dataTables.bootstrap.js')?>"></script>
<script type="text/javascript">
var save_method;
var table;
$(document).ready(function(){
table = $('#table').DataTable({
"processing": true,
"serverside": true,
"order": [],
"ajax": {
"url": "<?php echo site_url('section_controller/ajax_list')?
>",
"type": "POST"
},
"columnDefs":[
{
"targets": [-1],
"orderable": false,
},
],
});
$("input").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
function add_section()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Section'); // Set Title to Bootstrap
modal title
}
function edit_section(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('section_controller/ajax_edit/')?
>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="sec_ID"]').val(data.sec_ID);
$('[name="secname"]').val(data.secname);
$('[name="sec"]').val(data.sec);
$('#modal_form').modal('show'); // show bootstrap modal
when complete loaded
$('.modal-title').text('Edit Section'); // Set title to
Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function reload_table()
{
table.ajax.reload(null,false); //reload datatable ajax
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('section_controller/ajax_add')?>";
} else {
url = "<?php echo site_url('section_controller/ajax_update')?
>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax
table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i <
data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-
error'); //select parent twice to select div form-group class and
add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
//select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / updating data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
});
</script>
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Section Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Section
ID</label>
<div class="col-md-9">
<input name="sec_ID" placeholder="Section ID"
class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Section
Name</label>
<div class="col-md-9">
<input name="secname" placeholder="Section Name"
class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Section</label>
<div class="col-md-9">
<input name="sec" placeholder="Section"
class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn
btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-
dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</body>
</html>
I'm using codeigniter with datatables,jquery and bootstrap plugin.
This is URLs' configuration problem . if your website enabled the Friendly URL or rewrite . you should see and check this configuration.
I have two tables in mysql DB, 'cars' and 'address' which they have relation with primary key and 'on delete restrict' in DB so I can't delete some address which have car and that's good. Addresss in DB have columns 'street', 'number' and 'city'. I want to delete every location which has no cars but I don't know where I'm wrong in code, it doesn't work.I checked all paths and all is ok. Any suggestion appreciate.
This is my modal delete button:
<a href="#" data-toggle="modal" data-target="#delete_loc<?php echo $value['id']?>" role="button" class="btn btn-danger btn-sm">
<i class="fa fa-trash-o"></i> Delete
</a>
<div class="modal fade" id="delete_loc<?php echo $value['id']?>" tabindex="-1" role="dialog" aria-labelledby="mydelModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" style="text-align:center;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h2 class="modal-title" id="mydelModalLabel" style="color:#a80b27;text-transform:uppercase;font-size:1.6rem;">Warning !</h2>
</div>
<div class="modal-body">
<h5>Are you shure you want delete address ID <b><?php echo $value['id']?></b>?</h5>
</div>
<div class="modal-footer">
<input type="hidden" name="loc_id" id="loc_id" value="<?php echo $value['id']?>">
<a href="" role="button" class="btn btn-danger" id="del_loc">
Yes, I'm shure!
</a>
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
This is jquery and ajax:
$(document).ready(function() {
$('#del_loc').bind('click',function(e){
e.preventDefault();
var id = $('#loc_id').val();
var data = 'loc_id='+id;
$.ajax({
type: "POST",
url: "include/locations/delete.php",
data: data,
success: function(result){
if(result == 1){
window.location.replace("address.php?id=");
}
else{
err_msg = JSON.parse(result);
if(err_msg.nAddress){
$('.panel-footer').append('<span class="help-block" style="float:right;"><strong>'+err_msg.nAddress+'</strong></span>');
}
}
}
});
});
});
This is delete.php:
<?php
require '../../config/init.php';
require '../functions/locations.php';
require '../services/xss.php';
$loc_id = _e($_POST['loc_id']);
$data = deleteLoc($loc_id);
if(is_array($data)){
print_r(1);
}
else{
echo $data;
}
?>
And this is function named locations.php:
function deleteLoc($loc_id){
global $conn;
try{
$stmt = $conn->prepare('DELETE FROM address WHERE id=:id');
$stmt->bindParam(':id',$loc_id);
$stmt->execute();
$row[] = 'deleted';
return $row;
}
catch(PDOException $e){
if(DEBUG === true){
header('Location:../../error/db_error.php?err_msg='.$e->getMessage());
}
else{
header('Location:../../error/db_error.php?err_msg');
}
}
}
If you are getting the value loc_id value properly.I think following code will help you a lot. Let's try..
JavaScript
<script type="text/javascript">
$(document).ready(function() {
$('#del_loc').bind('click',function(e){
e.preventDefault();
var id = $('#loc_id').val();
var data = 'loc_id='+id;
//try here alert(id); For checking whether you are getting value or not
$.ajax({
type: "POST",
url: "include/locations/delete.php",
dataType:'JSON',
data: data,
success: function(result){
var res=eval(result);
if(res.success){
window.location.replace("address.php?id=");
}
else
{
if(res.nAddress){
$('.panel-footer').append('<span class="help-block" style="float:right;"><strong>'+err_msg.nAddress+'</strong></span>');
}
}
}
});
});
});
</script>
PHP delete.php
<?php
require '../../config/init.php';
require '../functions/locations.php';
require '../services/xss.php';
$loc_id = _e($_POST['loc_id']);
$data = deleteLoc($loc_id);
if(is_array($data)){
echo json_encode(array('success'=>true));
}
else{
echo json_encode($data);
}
?>
I'm trying to return a multiple data from database, then I'll pass it to jquery using ajax & json but the problem is its not working. Can anyone help me to fix it? Here is my code.
Jquery
$('.highlight').click(function() {
var y = $(this).find("td").eq(0).find('input[type="hidden"]').val();
var x = $(this).find("td").eq(1).text();
var z = $(this).find("td").eq(2).text();
//$('#ClassModal').modal('show');
$("#spanclass").text(x);
$("#spanclass2").text(z);
$('#ClassModal').modal('show');
$.ajax({
type:"GET",
url: 'db_loadStud.php',
data: 'year='+x+'&subject='+z,
dataType: 'json',
success: function(data){
for(var x=0;x<data.length; x++){
$(".studname").find("span").text(data[0]+", "+data[1]);
}
}
});
return false;
});
PHP
<?php
session_start();
include("db_conf.php");
$fid = $_SESSION['fid'];
$year = $_GET['year'];
$sub = $_GET['subject'];
$sql = "SELECT si_lname, si_fname, si_mname,si_studentno FROM `student_info` a";
$sql .= " INNER JOIN (SELECT * FROM student_enrolled WHERE se_active='True') b ON a.si_studentno=b.se_id";
$sql .= " INNER JOIN tblcourses c ON b.se_level=c.c_level WHERE c_level='$year' AND c_subject='$sub' AND c_teacher = '$fid'";
$result = mysql_query($sql);
$arr;
while($array = mysql_fetch_row($result)){
echo json_encode($array);
}
?>
HTML
<div class="modal fade" id="ClassModal" style="margin-left:-400px;margin-right:auto;" tabindex="-1" role="dialog" aria-labelledby="ClassModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" style="width:1000px;">
<div class="modal-header" style="background-color:#0a4595;color:#fff">
<h4 class="modal-title" id="myModalLabel"><center>Landstand of Knowledge Learning School, Inc. [ <span id="spanclass"></span> - <span id="spanclass2"></span> ]</center></h4>
</div>
<div class="modal-body" style="height:470px;">
<div style="float:left;border:1px solid #0a4595;width:200px;height:435px;">
<div style="width:100%;height:30px;border-bottom:1px solid #0a4595;background-color:#0a4595;padding:5px;font-size:12;color:#fff">
<center>STUDENTS</center>
</div>
<div class="studname" style="width:100%;height:30px;border-bottom:1px solid #0a4595;padding:5px;font-size:12;">
<span id="studname"></span>
</div>
</div>
</div>
<div class="modal-footer" >
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
thank you in advance
In the for loop, you are always overriding the contents of the span instead of adding contents to the existing one so only the last item in the array will be visible
$(".studname").empty();
for (var x = 0; x < data.length; x++) {
$(".studname").find("span").append(data[x][0] + ", " + data[x][1]+'<br />');
}