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');
});
}
})
});
Related
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>';
}
?>
I have the following ajax script
$(document).ready(function(){
$(".ver").click(function(event){
var pulsado = $(this).data("dnipass");
alert(pulsado);
event.preventDefault();
var prueba ;
$.ajax({
type: 'POST',
url: 'adminVerLineas.php',
data: {
dni:$(this).data("dnipass"),
},
success: (data) => {
alert(data);
$(this).closest('.form-group').next('.userInfo').append(data);
}
});
});
})
Its posting data in this html code
<?php if($usuarios[$i]["IdRol"] == '2'){ ?>
<tr>
<td colspan="2">
<!-- -->
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="ver"></label>
<div class="col-md-4">
<button data-dnipass="<?= $dni?>" class="ver" name="ver" class="btn btn-primary">Ver líneas</button>
</div>
</div>
<table id ="<?= $i?>" class="table userInfo" data-formpost="<?= $dni?>"></table>
</td>
</tr>
<?php } ?>
How do I make that on second click it deletes the data? , and then on third it posts it again, on fourth deletes.... and so..
EDIT: Progress using ramraider code
$(document).ready(function(){
$(".ver").click(function(event){
var pulsado = $(this).data("dnipass");
state = $(this).closest('.form-group').next('.userInfo').data("state"); //always picking 0, instead of the new generated 1
console.log(state);
state = 1-parseInt(state);
alert(pulsado);
event.preventDefault();
var prueba ;
$.ajax({
type: 'POST',
url: 'adminVerLineas.php',
data: {
dni:$(this).data("dnipass"),
},
success: (data) => {
switch( state ){
case 1:
$(this).closest('.form-group').next('.userInfo').append( data );
$(this).closest('.form-group').next('.userInfo').attr("data-state","1");
break;
case 0:
$(this).closest('.form-group').next('.userInfo').remove();
$(this).closest('.form-group').next('.userInfo').attr("data-state","0");
break;
}
}
});
This is how my data-state tag looks on no click
<table id="0" class="table userInfo" data-formpost="12345678B" data-state="0"></table>
And this is how it looks on first click
<table id="0" class="table userInfo" data-formpost="12345678B" data-state="1"></table>
And this is how it looks from second click and all of the next ones
<table id="0" class="table userInfo" data-formpost="12345678B" data-state="1"></table>
It basically stops changing, but im not sure why, seems that state = $(this).closest('.form-group').next('.userInfo').data("state"); start to always pick 0, instead the new generated 1
EDIT 2:
Ramraiders suggested answer works properly, I was missing that the data-state was moved to button
You can set a dataset attribute ( on the button ) that you toggle between 1 and 0 - the value can then be used to fork the logic in your ajax function. For example, set data-state=0 and then toggle it's value in the click handler and test that value in the callback
<button data-dnipass='<?php echo $dni;?>' data-state=0 class="ver" name="ver" class="btn btn-primary">Ver líneas</button>
<!-- note the data-state attribute that will be toggled! -->
$(document).ready(function(){
$( ".ver" ).click( function(event){
event.preventDefault();
event.target.dataset.state = 1 - event.target.dataset.state;
var pulsado = $(this).data("dnipass");
$.ajax({
type: 'POST',
url: 'adminVerLineas.php',
data: {
dni:pulsado
},
success: (data) => {
switch( parseInt( event.target.dataset.state ) ){
case 1:
$(this).closest('.form-group').next('.userInfo').append( data );
break;
case 0:
/* delete */
break;
}
}
});
});
})
I don't use jQuery so I am not familiar at all with its syntax or intricacies but this appears to do what you want. I have put it together into a working demo - obviously some of the code you see is mickey mouse but should give the idea.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
echo "gigantic mouse strangles elephant";
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>jQuery-toggle append/delete</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
<script>
$(document).ready(function(){
$( ".ver" ).click( function(event){
event.preventDefault();
event.target.dataset.state = 1 - event.target.dataset.state;
var pulsado = $(this).data("dnipass");
$.ajax({
type: 'POST',
url: location.href, //'adminVerLineas.php',
data: {
dni:pulsado
},
success: (data) => {
switch( parseInt( event.target.dataset.state ) ){
case 1:
$(this).closest('.form-group').next('.userInfo').append( data );
break;
case 0:
/* delete */
$(this).closest('.form-group').next('.userInfo').text('');
/* or, slightly better IMO */
// $(this).closest('.form-group').next('.userInfo').html('<tr><td></td></tr>');
break;
}
}
});
});
})
</script>
</head>
<body>
<table>
<tr>
<td colspan="2">
<div class="form-group">
<label class="col-md-4 control-label" for="ver"></label>
<div class="col-md-4">
<button data-state=0 data-dnipass="BANANA APPLE ORANGE STRAWBERRY" class="ver" name="ver" class="btn btn-primary">Ver líneas</button>
</div>
</div>
<table id ="XYZABC123" class="table userInfo" data-formpost="BANANA APPLE ORANGE STRAWBERRY"></table>
</td>
</tr>
</table>
</body>
</html>
Create two click handler such as:
$(".ver-post").click(function(event) {...}
and
$(".ver-delete").click(function(event) {...}
in the success of each replace the class.
success: (data) => {
...
$(this).addClass('ver-delete').removeClass('ver-post');
}
Haven't tested it yet but something like this should work.
Like #urfusion mention it, counter is probably the easiest solution:
$(document).ready(function(){
count_click = 0; // new row counter
$(".ver").click(function(event){
count_click += 1; // new row update counter
var pulsado = $(this).data("dnipass");
alert(pulsado);
event.preventDefault();
var prueba ;
$.ajax({
type: 'POST',
url: 'adminVerLineas.php',
data: {
dni:$(this).data("dnipass"),
},
success: (data) => {
alert(data);
if (count_click % 2 == 0) { // second, fourth, sixth...
// TO DO - delete data
} else { // first, third...
// TO DO - add data
}
$(this).closest('.form-group').next('.userInfo').append(data);
}
});
});
})
I am new on codeigniter I tried to fetch data which is filter by date from database and display it in my view page through ajax without refreshing my page.
I tried lot but didn't get the solution .
Here is my controller:
public function sohan_by_date(){
/* Check the validation of search by date function*/
$this->form_validation->set_rules('start_date', 'Start Date', 'trim|required');
$this->form_validation->set_rules('end_date', 'End Date', 'trim|required');
if($this->form_validation->run()){
/* display data from database from comparing the date in database*/
$date1=$this->input->post('start_date');
$date2=$this->input->post('end_date');
$start_date=date('Y-m-d', strtotime($date1));
$end_date=date('Y-m-d', strtotime($date2));
$check=$this->task->get_by_date_sohan($start_date,$end_date);
if($check){
$data['result']=$this->task->get_by_date_sohan($start_date,$end_date);
$this->load->view('admin/sohan_task_by_date', $data);
return json_encode($data);
}
else{
redirect('task/sohan_task');
}
}
else{
redirect('task/sohan_task');
}
}
Here is my model:
public function get_by_date_sohan($start_date,$end_date){
/* This display all task of sohan from database by date*/
$this->db->select('*');
$this->db->from('task_form');
$this->db->where('name','sohan');
$this->db->where('date >= ',$start_date);
$this->db->where('date <= ',$end_date);
$query=$this->db->get();
return $result=$query->result();
}
Here is my ajax:
<script type='text/javascript' language='javascript'>
$('#getdata').click(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url();?>task/sohan_by_date",
dataType: "json",
success: function(data){
debugger;
$('#result_table').html(data);
},
error: function() { alert("oops..."); }
});
});
</script>
here is my view:
<div class="form-body">
<div data-example-id="simple-form-inline">
<?php
$attributes = array('class' => 'form-inline');
echo form_open('', $attributes);
?>
<div class="form-group">
<input type="text" class="form-control" name="start_date" id="start_date" placeholder="Start Date" >
</div>
<div class="form-group">
<input type="text" class="form-control" name="end_date" id="end_date" placeholder="End Date">
</div>
<button type="submit" class="btn btn-default" id="getdata">Check</button>
<?php
echo form_close();
?>
</div>
</div>
<div id='result_table'>
<?php include('date.php');?>
</div>
My date.php file is:
<table class="table table-striped table-hover table-responsive">
<thead>
<tr class="success">
<th>Name</th>
<th>Date</th>
<th>Work</th>
<th>Partner</th>
<th>Director</th>
<th>Time</th>
<th>Task</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php foreach($result as $row) { ?>
<tr>
<td><?php echo $row->name;?></td>
<td><?php echo $row->date;?></td>
<td><?php echo $row->work;?></td>
<td><?php echo $row->partner;?></td>
<td><?php echo $row->director;?></td>
<td><?php echo $row->time;?></td>
<td><?php echo $row->task;?></td>
<td><?php echo $row->status;?></td>
</tr>
<?php } ?>
</tbody>
</table>
When I am fetching data normally without any using ajax and display in view then it working properly but page is refreshing.It means my controller and my model is working properly.But when I used ajax to display data without refreshing page then its not working ..please help me to find the solution .I dont have much more knowledge in ajax.
I got the Answer now its working perfectly. here i am going to share my answer.
Here is Jquery:
$('#myform').submit(function (event) {
dataString = $("#myform").serialize();
$.ajax({
type:"POST",
url:"<?php echo base_url(); ?>task/sohan_by_date",
data:dataString,
success:function (data) {
$('#task').html(data);
}
});
event.preventDefault();
});
Here is my controller:
public function sohan_by_date(){
/* Check the validation of search by date function*/
$this->form_validation->set_rules('start_date', 'Start Date', 'trim|required');
$this->form_validation->set_rules('end_date', 'End Date', 'trim|required');
if($this->form_validation->run()){
/* display data from database from comparing the date in database*/
$date1=$this->input->post('start_date');
$date2=$this->input->post('end_date');
$start_date=date('Y-m-d', strtotime($date1));
$end_date=date('Y-m-d', strtotime($date2));
$check=$this->task->get_by_date_sohan($start_date,$end_date);
if($check){
$data['result']=$this->task->get_by_date_sohan($start_date,$end_date);
$this->load->view('admin/date', $data);
return json_encode($data);
}
else{
redirect('task/sohan_task');
}
}
else{
redirect('task/sohan_task');
}
}
Here is a form in view:
<?php
$attributes = array('class' => 'form-inline','id'=>'myform');
echo form_open('', $attributes);
?>
My all code in details I already explain in my question if any one got stuck like this problem please compare my above question and my this answer.
Thank you
First give an id attribute to ua form.It is not necessary, you can get data by class also.But it might be a good practice.
<?php
$attributes = array('class' => 'form-inline','id'=>'myform');
echo form_open('', $attributes);
?>
Now in ua clicks,get the form variables by form.serialize method in ajax.
var str =$('#myform').serialize();
$.ajax({
url: '<?php echo site_url('task/sohan_by_date'); ?>',
async: false,
type: 'POST',
data:str,
dataType: 'html',
success: function(data)
{
alert(data);
},
error:function(error)
{
alert(error)
}
});
Now change ua controller code as:
if($check)
{
$this->task->get_by_date_sohan($start_date,$end_date);
}
if ua getting the data in alert as array,use json.stringify() to alert the data.. Good luck.
I'm trying to add and delete data to the database using ajax and php.
Everything works nice. But the problem is if I delete the last item and then try to add a new one, only the first one can be added, the second one, third one... are also added to the databse, but they are not shown on the page. I can see those only when I refresh the page.
My code for delete and add :
Add :
<!--Dodavanje texta-->
<script type="text/javascript">
//Dodavanje texta
$(document).ready(function () {
$(document).on("click", "#btnAddText", function(e){
var title = $("#txtTitle").val();
var text = $("#txtText").val();
$.ajax({
url : "add-text.php",
type : "POST",
dataType:"json",
data : {title:title, text:text},
beforeSend: function(){
$("#btnAddText").text("Saving...");
},
success: function(msg){
if(msg.br_rez == 1){
$(".sadrzaj").append(msg.result);
$("#natpisPrazno").fadeOut(300);
$("#txtTitle").val("");
$("#txtText").val("");
$("#btnAddText").text("Save");
$("#brRez").text(msg.br_rez);
}else{
$("#example1").append(msg.result);
$("#txtTitle").val("");
$("#txtText").val("");
$("#btnAddText").text("Save");
$("#brRez").text(msg.br_rez);
}
},
error: function(){
$("#error").text("Error! Something is wrong, the text is not saved!").fadeIn(300);
}
});
e.preventDefault();
});
});
</script>
Delete :
<!-- Brisanje texta -->
<script type="text/javascript">
$(document).ready(function() {
//Brisanje texta
$(document).on("click", ".btnDelText", function(){
var cijeliID = this.id.split("-");
var id = cijeliID[1];
$.ajax({
url : "text-delete.php",
type: "POST",
data : {id : id},
beforeSend: function(){
$("#delText-"+id).text("Deleting...");
},
success: function(msg){
if(msg){
if(msg == 0){
$(".divSadrzaj").fadeOut(300);
$("#natpisPrazno").addClass("alert-warning");
$("#natpisPrazno").fadeIn().html("Er zijn nog geen texten!");
}else{
$("#textItem-"+id).fadeOut(800);
$("#brRez").text(msg);
}
}else{
$("#errorDel").addClass("btn-danger");
$("#errorDel").text("Something was wrong!");
}
},
error: function(){
$("#errorDel").addClass("btn-danger");
$("#errorDel").text("Something was wrong!");
}
});
});
});
</script>
And the table where the databse data is shown is :
<div class="content">
<!-- Main row -->
<div class="row">
<div class="col-md-12 sadrzaj">
<?php
$rez = mysqli_query($kon, "SELECT * FROM texts");
$brRez = mysqli_num_rows($rez);
if($brRez < 1){
echo "<div class=\"alert alert-warning\" role=\"alert\" style=\"text-align:center;\">
Er zijn nog geen texts!
</div>";
}else{
echo "<div id=\"natpisPrazno\" class=\"alert\" role=\"alert\" style=\"text-align:center;\">
</div>";
?>
<div class="box divSadrzaj">
<div class="box-title">
<h3>Totaal texts - <span id="brRez"><b><u><?php echo $brRez; ?></u></b></span></h3>
</div><!-- /.box-title -->
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Text</th>
<th>Acties</th>
</tr>
</thead>
<tbody>
<?php
while($red = mysqli_fetch_assoc($rez)){
echo "<tr id=\"textItem-". $red["id"] ."\">
<td style=\"text-align:center;\">". $red["id"] ."</td>
<td style=\"text-align:center;\">". $red["title"] ."</td>
<td style=\"text-align:center;\">". $red["text"] ."</td>
<td style=\"text-align:center;\">
<a class=\"btn btn-danger btn-sm btnDelText\" title=\"". $red["title"] . "-wissen\" id=\"delText-". $red["id"] ."\">
<i class=\"fa fa-trash-o \"></i>
</a>
<a class=\"btn btn-success btn-sm\" title=\"". $red["title"] . "-veranderen\" >
<i class=\"fa fa-pencil-square-o\"></i>
</a><br/><br/>
<div id=\"errorDel\"></div>
</td>
</tr>";
}
?>
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Title</th>
<th>Text</th>
<th>Acties</th>
</tr>
</tfoot>
</table>
</div>
</div><!-- /.box -->
<?php
}
?>
</div><!-- /.col -->
</div><!-- /.row -->
</div>
Thus everything works great if there is no data in the database and I try to add a new one, it is added to the database and shown on the page. The first one, second one..every record is added and shown. Then when I try to delete it, it works also very nice.
Only when I delete the last record, then I can add only one new record that is shown on the page. The second one is also added to the database but it is not shown on the page until I refresh the page.
Any ideas? Thanks.
UPDATE
When I add $(".sadrzaj") to the console I get :
When I add $(".sadrzaj").append('test'); to the cosole I get (it is shown):
When I try to add a new record, I get next response (exactly what I need to get, table row to append to the table, but it is not shown)
And then when I refresh the page I get it right :
This is the HTML part:
div id="messages">
<div class="messages">
<?php if(isset ($unread)) { ?>
<p>You have <?php echo $unread?> unread messages.</p>
<?php } ?>
<?php if(isset ($messages)) { ?>
<?php foreach ($messages as $msg){ ?>
<div class="col_3">
<?php
if($msg['read'] == 0){ echo 'Status of message: Unreaded';}
elseif($msg['read'] == 1){echo 'Status of message: Readed';}
echo "<p>Message from: $msg[name]</p>";
echo "<p>Sender email: $msg[email]</p>";
echo "<p>Message: <br />$msg[message]</p>"; ?>
Delete message
</div>
<?php } ?>
<?php } ?><!-------- end of if $message-------->
</div><!------ end of div .messages--------->
</div><!------ end of div #messages--------->
and JQ:
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>");
});
});
}
});
return false;
});
Code is working, but when it comes to the load nothing is being shown. I did
load("<?php echo site_url('messages/show') ?>", function() {
alert('Load was performed.');
});
and there was an alert, and when I look page source I can see that the content has been changed, but it is not displayed.
When you view the source of a page that has been loaded via AJAX, it will never update. You will need to inspect the DOM in order to see what has changed.
The reason is because the content is not actually on the page and is being dynamically added to the page.