I have a problem my delete function does not work he does not delete the organisation. When I press the button it show the text if I want to delete it I say yes but it only refreshes the site. I am not an advanced programmer and some of the code I did not write myself someone else worked on the project before me so idk why he some codes are written this way and he did not use any framework.
My code
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (isset($_FILES['croppedImage'])) logoChange();
// change organisation information is not made yet
if (isset($_POST['update'])) echo "This function is not made yet!";
if (isset($_POST['deleteOrganisation'])) DeleteOrganisations();
}
//this is the logoChange function
function logoChange() {
include '../../../include/db_conn.php';
//get organisation_id
$organisation_id = $_POST['organisation_id'];
//blob file info
$fileName = $_FILES['croppedImage']['name'];
$fileTmpName = $_FILES['croppedImage']['tmp_name'];
$fileSize = $_FILES['croppedImage']['size'];
$fileError = $_FILES['croppedImage']['error'];
//change blob to png
$fileType = 'png';
//check if image is able to upload
if ($fileError === 0) {
//check if file is not too big change number to needs!
if ($fileSize < 1000000) {
//make new random filename
$fileNameNew = uniqid('', true).".".$fileType;
$fileDesination = '../../../img/uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDesination);
//check if organisation already has a logo
$get_organisation_stmt = $conn->prepare('SELECT `organisation_logo` FROM `organisations` WHERE `organisation_id` = ?');
$get_organisation_stmt->bind_param('s', $organisation_id);
$get_organisation_stmt->execute();
$result_organisation = $get_organisation_stmt->get_result();
$row = mysqli_fetch_assoc($result_organisation);
if (is_null($row['organisation_logo'])) {
//if not inserted it
$sqlUpdateLogo = 'UPDATE `organisations` SET `organisation_logo`="'.$fileNameNew.'" WHERE `organisation_id` ="'.$organisation_id.'"';
mysqli_query($conn, $sqlUpdateLogo);
echo 'image inserted';
} else {
//else replace it
unlink('../../../img/uploads/'.$row['organisation_logo']);
$sqlUpdateLogo = 'UPDATE `organisations` SET `organisation_logo`="'.$fileNameNew.'" WHERE `organisation_id` ="'.$organisation_id.'"';
mysqli_query($conn, $sqlUpdateLogo);
echo 'image replaced';
}
}
else {
echo "File to big";
}
} else {
echo "Error in file";
}
}
// here i made the delete function
function DeleteOrganisations() {
include '../../../include/db_conn.php';
//delete the organisation
$getDeleteOrganisation = $_POST['deleteOrganisation'];
$delete_organisation_stmt = $conn->prepare('DELETE FROM `organisations` WHERE `organisation_id`= ?');
$delete_organisation_stmt->bind_param('i', $getDeleteOrganisation);
$delete_organisation_stmt->execute();
$delete_organisation_stmt->close();
}
here are the functions and here is JavaScript
//link for datatable functions
$(document).ready(function(){
$('#organisations').DataTable({
"columnDefs": [
{ "orderable": false, "targets": [0, 5] }
],
"order": [[ 1, "asc" ]]
});
});
//open edit modal for logo
$(document).on("click", ".btnopenEditLogo", function(e) {
event.preventDefault();
var organisationId = $(this).val();
var url = "functions/getOrganisationActions.php";
$.ajax({
type: 'POST',
url : url,
data: {'HiddenLogoid': organisationId},
success: function (data) {
$('#myLogoEditModal').modal('show');
$("#myLogoEditModal .modal-body").html(data);
}
});
});
//open modal with info of user for editing
$(document).on("click", ".btnopenEditOrganisation", function(e) {
event.preventDefault();
var organisationId = $(this).val();
var url = "functions/getOrganisationActions.php";
$.ajax({
type: 'POST',
url : url,
data: {'HiddenOrganisationid': organisationId},
success: function (data) {
$('#myOrganisationEditModal').modal('show');
$("#myOrganisationEditModal .modal-body").html(data);
}
});
});
//delete organisation
$(document).on("click", ".btnRemoveOrganisation", function(e) {
event.preventDefault();
var remove = $(this).val();
var url = "../cms/organisations/functions/postOrganisationActions.php";
Swal.fire({
title: 'Delete this test?',
text: "If you delete the test the questions and all statistics will be lost!",
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, cancel!',
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33'
}).then((result) => {
if (result.value) {
$.ajax({
type: 'POST',
url : url,
data: {'deleteOrganisation': remove},
success: function (data) {
Swal.fire({
title: 'Deleted!',
text: "You deleted the survey!",
type: 'success',
confirmButtonColor: '#3085d6',
confirmButtonText: 'OK'
}).then((result) => {
if (result.value) {
window.location.reload();
}
});
}
});
} else if (result.dismiss === Swal.DismissReason.cancel) {
Swal.fire (
'Cancelled',
'Your test is safe :)',
'error'
)
}
});
});
this is the index
<?php
session_start();
if (!isset($_SESSION["userId"])) {
header('Location: ../../auth/login');
die();
}
$activePage = "cms";
$activeCMSTab = "organisations";
?>
<!doctype html>
<html lang="en">
<head>
<title>Admin CMS | Organisations</title>
<!-- include header -->
<?php require '../../include/header.php'; ?>
</head>
<body class="d-flex flex-column">
<!-- include navbar -->
<?php require '../../include/navbar.php'; ?>
<!-- include organisation functions -->
<?php require 'functions/getOrganisationsActions.php'; ?>
<div id="main">
<div class="container">
<div class="row">
<div id="sidenav-border" class="col-lg-3 d-none d-md-none d-lg-block">
<?php require '../../include/cms_sidenav.php'; ?>
</div>
<div class="col-lg-9">
<div class="card-theme mt-3">
<div class="clearfix">
<h5 class="card-title-theme float-left"><i class="fas fa-building"></i> Organisation list:</h5>
<i class="fas fa-info-circle fa-fw mt-2 mr-2"></i>
</div>
<hr class="hr-theme" />
<div class="card-body">
<?php getOrganisations(); ?>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- footer -->
<?php require '../../include/footer.php'; ?>
<!-- logo modal -->
<?php require 'logo-edit-modal.php'; ?>
<!-- organisation modal -->
<?php require 'organisation-edit-modal.php'; ?>
<!-- logout modal -->
<?php require '../../auth/logout-modal.php'; ?>
<!-- include js scripts -->
<script src="js/organisationFunctions.js"></script>
</body>
</html>
you need get organisation where the button is made the button is at
<?php
function getOrganisations() {
//include DataBase connection
include '../../include/db_conn.php';
//show every organisation that is approved
$sqlCollectAllOrganisations = "SELECT * FROM `organisations` WHERE `approval_admin`='1'";
$resultAllOrganisations = mysqli_query($conn, $sqlCollectAllOrganisations);
echo '<div class="table-responsive">';
echo '<table id="organisations" class="table table-striped table-bordered table-hover">';
echo '<thead>';
echo '<tr>';
echo '<th>Logo</th>';
echo '<th>Organisation</th>';
echo '<th>Parent</th>';
echo '<th>type</th>';
echo '<th>Users</th>';
echo '<th>Tools</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
//Show organisations
if ($resultAllOrganisations->num_rows > 0) {
while ($row = $resultAllOrganisations-> fetch_assoc()) {
echo '<tr>';
//organisation logo
if ($row['organisation_logo'] == '')
echo '<td class="align-middle" align="center"><img src="../../img/stock/no-image-icon.png" class="rounded d-inline mr-1" width="30px"></img><button class="btn btn-link d-inline p-0 btnopenEditLogo" value="'. $row['organisation_id'] .'">edit</button></td>';
else
echo '<td class="align-middle" align="center"><img src="../../img/uploads/'. $row['organisation_logo'] .'" class="rounded border d-inline mr-1" width="30px"><button class="btn btn-link d-inline p-0 btnopenEditLogo" value="'. $row['organisation_id'] .'">edit</button></td>';
//organisation name
echo '<td class="align-middle">' .$row['organisation_name']. '</td>';
//organisation parent
if ($row['organisation_parent'] != null) {
$sqlCollectparent = "SELECT * FROM `organisations` WHERE `organisation_id`='".$row['organisation_parent']."'";
$resultparent = mysqli_query($conn, $sqlCollectparent);
if ($parent = $resultparent-> fetch_assoc()) echo '<td class="align-middle">'.$parent['organisation_name'].'</td>';
} else {
echo '<td class="align-middle"><i class="fas fa-times" style="font-size: 16px;"></i></td>';
}
//organisation type
echo '<td class="align-middle">' . $row['organisation_type'] . '</td>';
//count users
$sqlCountUsers = "SELECT COUNT(organisation_id) AS `count` FROM `users` WHERE `organisation_id`='".$row['organisation_id']."'";
$resultcount = mysqli_query($conn, $sqlCountUsers);
if ($count = $resultcount-> fetch_assoc()) echo '<td class="align-middle">'.$count['count'].'</td>';
//buttons
echo '<td class="align-middle text-center">';
echo '<div class="btn-group">';
echo '<button class="btn-theme btn-theme-success btn-theme-sm mr-1">Add user</button>';
echo '<button class="btn-theme btn-theme-primary btn-theme-sm mr-1 btnopenEditOrganisation" value="'. $row['organisation_id'] .'"><i class="fas fa-edit fa-fw"></i></button>';
if ($_SESSION['organisation_id'] != $row['organisation_id']) echo '<button type="button" class="btn-theme btn-theme-danger btn-theme-sm btnRemoveOrganisation" value=""><i class="fas fa-trash-alt fa-fw"></i></button>';
echo '</div>';
echo '</td>';
echo '</tr>';
}
} else {
//do nothing
}
echo '</tbody>';
echo '</table>';
echo '</div>';
}
?>
Related
I have below code to get more results on page scroll.
It works fine on localhost and on server laptop/desktop.
It does not work on mobile and does not load more results on scroll.
I cannot figure it out why this is happening or what is causing this not to work on mobile.
<?php
$getItemLID = $dba->prepare('SELECT MAX(id) as id FROM items
where status = ? AND ename like ?');
$getItemLID->bind_param('ss', $status,$param);
$getItemLID->execute();
$resultLID = $getItemLID->get_result();
$rowLID = $resultLID->fetch_assoc();
$thelastid = $rowLID['id'];
$status = 1;
$getscategory = $dba->prepare('SELECT * FROM mytable
where status = ?
order by id asc');
$getscategory->bind_param('s', $status);
$getscategory->execute();
$resultGSC = $getscategory->get_result();
while ($rowGSC = $resultGSC->fetch_assoc()) {
$scid = $rowGSC['id'];
$scename = $rowGSC['ename'];
?>
<div class="message_box" data-id="<?php echo $scid; ?>" style="padding-right: 5px;">
<div class="portfolio-item-wrap" style="border-radius: 3%;">
<span class="portfolio-description">
<h3><?php echo $scename; ?></h3>
</span>
</div>
</div>
<?php } ?>
<div id="msg_loaderw" style="display: none;">
<div class="card">
<div class="card-body">
<div class="d-flex align-items-center">
<strong>Loading...</strong>
<div class="spinner-border ml-auto" role="status" aria-hidden="true">
</div>
</div>
</div>
</div>
</div>
<div id="msg_loader">
</div>
<script>
$(document).ready(function () {
$(window).scroll(function () {
var thislastid = "<?php echo $thelastid; ?>";
if($(window).scrollTop() == ($(document).height() - $(window).height())) {
$("#msg_loaderw").show();
var msg_id = $(".message_box:last").data("id");
$.ajax({
type: "POST",
url: "inc/items/search_items_get.php",
data: {msg_id: msg_id},
cache: false,
success: function (data) {
//Insert data after the message_box
$(".message_boxx").append(data);
if (msg_id == thislastid) {
$("#msg_loaderw").hide();
$("#msg_loader").html('<hr><div class="card"><div class="card-body"><div class="align-items-center"><strong><center>That is all what we have for now.</center></strong></div></div></div>');
}
}
});
}
});
});
</script>
Below is : inc/items/search_items_get.php
<?php
include ('../default/db.php');
if (isset($_POST['msg_id']) && isset($_POST['msg_id']) !== NULL) {
$msg_id = $_POST['msg_id'];
$status = 1;
$limit = 12;
$getItem = $dba->prepare('SELECT * FROM mytable
where id > ? AND status = ?
order by id asc');
$getItem->bind_param('ss', $msg_id,$status);
$getItem->execute();
$resultItem = $getItem->get_result();
while ($rowItem = $resultItem->fetch_assoc()) {
$itemID = $rowItem['id'];
$itemName = $rowItem['ename'];
?>
<div class="message_box" data-id="<?php echo $itemID; ?>" style="padding-right: 5px;">
<div class="portfolio-item-wrap" style="border-radius: 3%;">
<span class="portfolio-description">
<h5><?php echo $itemName; ?></h5>
</span>
</div>
</div>
<?php
}
} else {
echo "Message ID is empty";
}
?>*emphasized text*
It seems it's a script issue just try changing the code a bit , hopefully it will work:
<script>
$(document).ready(function () {
$(window).scroll(function () {
var scrollHeight = $(document).height();
var scrollPosition = $(window).height() + $(window).scrollTop();
if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
$("#msg_loaderw").show();
var msg_id = $(".message_box:last").data("id");
$.ajax({
type: "POST",
url: "inc/items/search_items_get.php",
data: {msg_id: msg_id},
cache: false,
success: function (data) {
//Insert data after the message_box
$(".message_boxx").append(data);
if (msg_id == thislastid) {
$("#msg_loaderw").hide();
$("#msg_loader").html('<hr><div class="card"><div class="card-body"><div class="align-items-center"><strong><center>That is all what we have for now.</center></strong></div></div></div>');
}
}
});
}
});
});
</script>
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.
Im using bootstrap template. In table I have delete button, clicking on it, Im able to display a confirmation message with swal. But after clicking yes,delete it.... it has perform action by deleting from database. Please guide me how to write a query in swal so that it takes that particular row id and delete that row into database.
deleting action should be like
if(isset($_POST['delete'])) {
$update=$_POST['v_id'];
mysqli_query($conn, "UPDATE vendor_pricing SET status = 'deleted' where Vendor_pricing_id=$update");
}
<?php
session_start();
if(empty($_SESSION))
{
header("Location: ../login.php");
}
$mpage = "printer";
$page = "list_printer.php";
include '../header.php';
$email1 = $_SESSION['email'];
$Vendor_id="SELECT Vendor_id FROM vendors where email = '$email1' ";
$result=mysqli_query($conn,$Vendor_id);
$row = mysqli_fetch_row($result);
$sql = "SELECT Vendor_pricing_id, status, printer_name,process,material,color,strength,surface_finish,per_gram_charge,per_hour_charge FROM vendor_pricing where Vendors_Vendor_id= $row[0] and status='active' or status='inactive' ";
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<!DOCTYPE html>
<html>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Printer Lists
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-dashboard"></i> Home</li>
<li>Printer</li>
<li class="active">List Printers</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box table-responsive no-padding">
<div class="box-header">
<h3 class="box-title">List of all Printers</h3>
</div>
<!-- /.box-header -->
<div id="response" class="box-body">
<table id="example1" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th width="8%">Printer Name</th>
<th>Process</th>
<th>Material</th>
<th>Color</th>
<th>Strength</th>
<th>Surface Finish</th>
<th padding>per Gram</th>
<th>per Hour</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_array($query))
{
$vid=$row['Vendor_pricing_id'];
$p_name=$row['printer_name'];
$pro=$row['process'];
$mat=$row['material'];
$color=$row['color'];
$type=$row['strength'];
$sur=$row['surface_finish'];
$p_gram=$row['per_gram_charge'];
$p_hour=$row['per_hour_charge'];
$st=$row['status']; if ($st=="active"){ $link='inactive'; $color1='success'; $style='white'; $cursor='allowed'; $tip="inactive ur printer";}
else { $link='active';$color1='warning'; $style='#EEE'; $cursor='not-allowed'; $tip="activate ur printer";}
?>
<tr style="background-Color:<?php echo $style;?>; cursor: <?php echo $cursor;?>;">
<form method="post">
<td><?php echo $vid;?>
<input type="hidden" value="<?php echo $vid;?>" name="v_id">
</td>
<td><?php echo $p_name;?></td>
<td><?php echo $pro;?></td>
<td><?php echo $mat;?></td>
<td><?php echo $color;?></td>
<td><?php echo $type;?></td>
<td><?php echo $sur;?></td>
<button type="delete" name="delete" value="<?php echo $vid;?>" id="<?php echo $vid ?>" type="submit" class="btn-warning" onclick="archiveFunction(this.id)">Delete</button>
</td>
</tr>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
$('#reloadpage').click(function() {
location.reload(true);
});
function archiveFunction(id) {
event.preventDefault(); // prevent form submit
var form = event.target.form; // storing the form
swal({
title: "Are you sure?",
text: "But you will still be able to retrieve this file.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, Delete it!",
cancelButtonText: "No, cancel please!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
window.location.href="delete.php?delete_id="+id;
swal("Updated!", "Your imaginary file has been Deleted.", "success");
} else {
swal("Cancelled", "Your file is safe :)", "error");
}
});
}
</script>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
</div>
</html>
You are getting the v_id from post variables in php, but you are actually requesting the server with get method. This is the reason why it is not working. The proper way is to request the server with post method to perform delete action.
You should change this snippet from:
if (isConfirm) {
// this is `get` request to the server
// so you can only get the data from $_GET variable, says $_GET['delete_id']
window.location.href = "delete.php?delete_id=" + id;
swal("Updated!", "Your imaginary file has been Deleted.", "success");
} else {
swal("Cancelled", "Your file is safe :)", "error");
}
TO
if (isConfirm) {
// this is `post` request to the server
// so you can get the data from $_POST variables, says $_POST['delete'] $_POST['v_id']
$.ajax({
method: 'POST',
data: {'delete': true, 'v_id' : id },
url: 'delete.php',
success: function(data) {
}
});
swal("Updated!", "Your imaginary file has been Deleted.", "success");
} else {
swal("Cancelled", "Your file is safe :)", "error");
}
You can create AJAX request like this:
$.ajax({
method: 'GET',
data: {'id' : this.id },
url: 'delete.php',
success: function(data) {
// Request is successful you have the response in data
}
})
$(document).on('click', '.delete', function () {
var id = $(this).data('id');
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
}).then((result) => {
if (result.value) {
$.ajax({
url: 'delete.php?action=delete',
type: 'POST',
data: 'id=' + id,
dataType: 'json'
})
.done(function (response) {
swal('Deleted!', response.message, response.status);
fetch();
})
.fail(function () {
swal('Oops...', 'Something went wrong with ajax !', 'error');
});
}
})
});
I am loading the latest news article to my home page, I would like to load the next one on click of a button. However I get this error on click: home.php:353 Uncaught ReferenceError: nextNews is not defined. The code I have written will load another article but will not hide the previous one. Any suggestions for this are also welcome.
<script>
$( document ).ready(function() {
var newsCount = 1;
function nextNews(item){
newsCount = newsCount + 1;
$("#newsHome2").load("load-news.php", {
newsNewCount: newsCount
});
}
});
</script>
<?php
$query = $handler->query('SELECT * FROM articles LIMIT 1');
$results = $query->fetchAll(PDO::FETCH_ASSOC);
if ($_GET['sort'] == 'dateTime')
{
$sql = " ORDER BY dateTime";}
for ($i=0; $i < count($results); $i++) {
echo '<div class="col-lg-6 col-xs-12 col-sm-12 height-news82" id="newsHome2">';
echo '<h2 class="ashu">Lastest News</h2><br>';
echo '<p class="news-title78">'.$results[$i]['headline'].' <br>'.'</p>';
echo '<img class="news-img33" src="data:image/png;base64,' .base64_encode( $results[$i]['logo'] ).'"/>';
echo '<p class="news-time">'.$results[$i]['dateTime'].'< br>'.'</p>';
echo '<p class="news-body56">'.$results[$i]['text'].'</p>' ;
echo '</p><br><button id="solo-buttons67">Read More</button>';
echo '<i id="arrow20" class="fa fa-chevron-left fa-1x"></ i><i id="arrow21" onclick="nextNews(this)" class="fa fa-chevron-right fa-1x"></i></div>';
}
?>
Your function 'nextNews' is defined in the anonymous function passed to .ready(). So it can't be called in your html.
Alternative:
Use jquery click event
Define the function outside of the anonymous function
Try this workout Its working fine :)
view file view.php
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<div id="newsHome2"></div>
<script type="text/javascript">
var newsCount = 1;
$( document ).ready(function() {
nextNews(newsCount)
});
function nextNews(newsCount){
newsCount = newsCount + 1;
$.post("load-news.php", { newsNewCount: newsCount }, function(data, status){
$("#newsHome2").html(data);
});
}
</script>
php file load-news.php
<?php
if(isset($_POST['newsNewCount'])) { $newsCount=$_POST['newsNewCount']; } else { $newsCount=1; }
echo '<div class="col-lg-6 col-xs-12 col-sm-12 height-news82" id="newsHome2">';
echo '<h2 class="ashu">Lastest News</h2><br>';
echo '<p class="news-title78">headline '.$newsCount.' <br>'.'</p>';
echo '<img class="news-img33" src="data:image/png;base64,"/>';
echo '<p class="news-time">dateTime '.$newsCount.'< br>'.'</p>';
echo '<p class="news-body56">text '.$newsCount.'</p>' ;
echo '</p><br><button id="solo-buttons67">Read More '.$newsCount.'</button>';
echo '<i id="arrow20" class="fa fa-chevron-left fa-1x"></ i><i id="arrow21" onclick="nextNews('.$newsCount.')" class="fa fa-chevron-right fa-1x"> click here for next </i></div>';
?>
I have drag and drop jquery. Accordion that allows user to drag and drop names into a droppable area. So what i want to do is to display dropped names on a new page after user click submit. But I cant get how to do it. I thought maybe its can be done using ajax but not sure how. Thanks in advance. Here is my code:
<link href="jquery-ui/jquery-ui.css" rel="stylesheet" />
<script src="jquery-ui/jquery.js"></script>
<script src="jquery-ui/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$("#myAccordion"). accordion({heightStyle:"content", active: false, collapsible:true});
$(".source li").draggable({helper:"clone"});
$("#project ol").droppable({
activeClass: "ui-state-default",
hoverClass: "ui-state-hover",
accept: ":not(.ui-sortable-helper)",
drop: function(event, ui)
{
$(this).find(".placeholder").remove();
$("<li></li>").text(ui.draggable.text())
.addClass("project-item")
.addClass('dropClass')
.appendTo(this);
}
}).sortable({
items: "li:not(.placeholder)",
sort: function() {
$(this).removeClass("ui-state-default");
}
});
$("#myAccordion ul").droppable({
drop: function(event, ui) {
$(ui.draggable).remove();
},
hoverClass: "ui-state-hover",
accept: '.project-item'
});
$('#box').keyup(function(){
var valThis = $(this).val().toLowerCase();
if(valThis == ""){
$('.source > li').show();
} else {
$('.source > li').each(function(){
var text = $(this).text().toLowerCase();
(text.indexOf(valThis) >= 0) ? $(this).show() : $(this).hide();
});
};
});
});
</script>
<div id="myAccordion" style="width:20%; float:left; margin-right:30px;">
<?php for($i=321; $i<347; $i++)
{
echo "<h3>".chr($i)."</h3>";
echo '<ul class="source">';
$sql = "SELECT username FROM user WHERE username LIKE '".chr($i+32)."%' ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$name= $row["username"];
echo"<li class='ui-state-highlight'>". $name ."</li>";
}
} else
{
echo "0 results";
}
echo '</ul>';
}
?>
</div>
<form class="formcss" method="POST" action="create3.php">
<fieldset style="background-color:white;">
<div id="project" style="margin-left:10%;">
<label>Leader:</label>
<ol>
<li class="placeholder" name="leader[]" <?php if (isset($leader[$i])) echo 'value="'.$leader[$i].'"' ?>>Add leaders and checkers here</li>
</ol>
<br><br>
<div class="row">
<input type = "submit" name ="submit" class="button" value = "Create Project" onclick="userSubmitted = true;"/>
</div>
</div>
</fieldset>
</form>