I am new in codeigniter, i have been trying to display data from database as ul list in form of buttons. It was easily done using php but i want to display the same using ajax to reduce the loading time. i tried some methods but cannot able to display the data. I really need help on this, help will be appreciated. Thanks in advance.
Controller:
function user()
{
$this->data['list'] = $this->mobiles_model->get_status();
$this->_render_page('user', $this->data);
}
model:
function get_status()
{
$sql = "select * from(SELECT * FROM my_user_view ) as t group by imei ORDER BY dattim ASC ";
$query = $this->db->query($sql, array($uid,$value));
$result = $query->result();
return $result;
}
view:
<ul class="sidebar-menu" id="nav-accordion">
<?php
for ($i = 0; $i < count($deptlist); ++$i)
{
$time = $deptlist[$i]->dattim;
$sdate=date("d-m-Y H:i:s",strtotime($deptlist[$i]->dattim));
$dateFromDatabase = strtotime($time);
$dateFiveMinuteAgo = strtotime("-5 minutes");
if ($dateFromDatabase >= $dateFiveMinuteAgo)
{
?>
<li>
<button value="<?php echo $deptlist[$i]->imei ?>" class="btn-success"><?php echo $deptlist[$i]->user;?>
</button>
</li>
<?php }
else
{
?>
<li>
<button value="<?php echo $deptlist[$i]->imei ?>"class="btn-danger"><?php echo $deptlist[$i]->user; ?>
</button>
</li>
<?php }
}?>
</ul>
The data displayed using php but i want to display the same using ajax.
thanks again.
working example
to output the view part
public function index(){
if($this->session->userdata('is_logged_in')){
$this->load->view('../template/header');
$this->load->view('manufacturer');
$this->load->view('../template/footer');
} else {
redirect('main/restricted');
}
}
my controller name is manufacturer / method is manufacturer_list
public function manufacturer_list()
{
$result = array('data' => array());
$data = $this->manufacturer_model->fetchManufacturerData();
foreach ($data as $key => $value) {
//i assigned $buttons variable to hold my edit and delete btn to pass in my array.
$buttons = '
<button class="btn btn-primary" onclick="editData('.$value->id.')" data-toggle="modal" data-target="#myModal">Edit</button>
<button class="btn btn-danger" onclick="deleteData('.$value->id.')" data-toggle="modal" data-target="#deleteModal">Delete</button>
';
$result['data'][$key] = array(
$value->id,
$value->brand,
$buttons
);
}
echo json_encode($result);
}
my ajax
showRecords();
function showRecords(){
$.ajax({
url: 'manufacturer/manufacturer_list', //controller/method
type: 'POST',
dataType: 'json',
success: function(data){
var html = '';
for(i=0; i<data.length; i++){
html += '<tr align="center">'+
'<td>'+data[i].id+'</td>'+
'<td>'+data[i].brand+'</td>'+
'<td>'+'<button class="btn btn-primary edit-data" data="'+data[i].id+'">Edit</button>'+' '+
'<button class="btn btn-danger delete-data" data="'+data[i].id+'">Delete</button>'+'</td>'+
'</tr>';
}
$("#showdata").html(html); //pass the data to your tbody
},
error: function(){
alert('Could not load the data');
}
});
}
html view part is like this (manufacturer.php from index method in controller)
<table>
<thead>
<tr>
<th>ID</th>
<th>Manufacturer</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="showdata">
</tbody>
</table>
hope you get the idea
Related
I have a table that it's content is comes from database.When I click on the delete button I want to delete that row with Ajax. Actually right now it's working but with a bug and that is all of the rows get deleted when I click on the button and then if I refresh , the row that I was deleted is gone and other rows are shown.But as I said it needs a refresh.Any solution would be appreciated .
$('.dashboard-subscribe-form').submit(() => {
event.preventDefault();
const currentHiddBtn = $('.dash-subscribe-form-btn');
console.log(currentHiddBtn.closest('tr'));
const userCaution = confirm('Want to delete this quote?');
if (userCaution) { //If admin insists to delete the row
const deleteId = $('.dash-subscribe-form-btn').attr('value');
$.ajax({
type: "POST",
url: "delete-subscribe.php",
dataType: "json",
data: {
deleteId: deleteId
},
success: (data) => {
if (data.code === '200') {
console.log('It works!');
currentHiddBtn.closest('tr').css('background', 'tomato');
currentHiddBtn.closest('tr').fadeOut(1200, () => {
});
} else if (data.code === '404') {
alert('An error occurred!Please try again.');
}
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tbody>
<?php
$count = 1;
$sqlCommand = "SELECT * FROM `kq0b3_subscribe`";
$sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
$sqlCommandPrepare->execute();
while ($result = $sqlCommandPrepare->fetch()) {
?>
<tr id="row-<?php echo $result['id']; ?>">
<td class="dashboard-records">
<?php echo $count; ?>
</td>
<td class="dashboard-records">
<?php echo $result['email']; ?>
</td>
<td>
<form action="" method="post" class="dashboard-subscribe-form">
<input id="<?php echo $result['id']; ?>" type="hidden" class="dash-subscribe-form-btn" name="hidden-del" value='<?php echo $result[' id ']; ?>'/>
<button type="submit" name="sub-del-btn" class="btn btn-danger del" value='<?php echo $result[' id ']; ?>'> Delete
</button>
</form>
</td>
</tr>
<?php
$count++;
}
?>
</tbody>
delete-subscribe.php:
<?php
require_once('config.php');
$delete_row = $_POST['deleteId'];
if($delete_row){
$sqlCommand = "DELETE FROM `kq0b3_subscribe` WHERE `id` = ?";
$sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
$result = $sqlCommandPrepare->execute([
$delete_row
]);
/*The json_encode() must be after all of our calculation codes and DB query codes and...(It must be the
last line of code) */
echo json_encode(['code' => '200'], JSON_THROW_ON_ERROR, 512);
}
else {
echo json_encode(['code' => '404'], JSON_THROW_ON_ERROR, 512);
}
UPDATE2: now I'm using :
$('#row-' + deleteId).css('background', 'tomato');
$('#row-' + deleteId).fadeOut(1200, () => {
});
but the new problem is : it doesn't matter which button I click, the forst row is deleted (when any button is clicked , in the console , the id of the first row-button is printed , not the actual id that I was clicked. ).How can I fix this one?
I think the main issue, in this case, is using CSS classes as a selector and it seems to be selecting the first instance no matter which item you are clicking.
The code causing this is:
const deleteId = $('.dash-subscribe-form-btn').attr('value');
You want to be getting the target input from the event object passed from your .submit().
I have created a jsfiddle with an example that could be adapted to your code but here is a quick preview of jQuery part.
$('.dashboard-subscribe-form').submit((event) => {
event.preventDefault()
console.log(event.target.elements[0]["value"])
$('#result-from-click').html("Input Value: " + event.target.elements[0]["value"])
})
It is selecting the first element within the elements array which is the input. If you want the button you can use event.target.elements[1]
You could then also use the value returned to remove the <tr> with the same id instead of finding the nearest. This could be done in the success part of your ajax call without doing a refresh.
I am inserting data with jquery Ajax using form submit, And fetching data to dataTable after form submit, following code giving DataTables warning: table id=mainTable - Requested unknown parameter '1' for row 0, column 1. . . . .
var mainTable = $('.mainTable').DataTable();
$('#Form').submit(function(e) {
e.preventDefault();
var form = $(this).serialize();
$.ajax({
url: "result.php",
type: "post",
data: form
}).done(function (data) {
mainTable .clear().draw();
mainTable .rows.add(data).draw();
}).fail(function (jqXHR, textStatus, errorThrown) {
});
});
HTML
<div class="content">
<!-- form start -->
<form method="post" id="Form">
<input type="text" name="id">
<input type="text" name="name">
<input type="text" name="class">
<button type="submit">submit</button>
</form>
<table id="mainTable" class="mainTable table table-striped">
<thead>
<tr>
<th>Roll No</th>
<th>Name</th>
<th>class</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
PHP
$id = $_POST['group_id'];
$rollno = $_POST['roll_no'];
$name = $_POST['name'];
$class = $_POST['class'];
$insert = "insert into students (roll_no,group_id,name,class) values(:roll_no,:id,:name,:class)";
$insert = $db->prepare($insert );
$insert ->bindParam(':roll_no',$rollno);
$insert ->bindParam(':id',$id );
$insert ->bindParam(':name',$name);
$insert ->bindParam(':class',$class);
$insert ->execute();
$fetch = "SELECT roll_no,name,class FROM students where group-id=:id";
$fetch = $db->prepare($fetch );
$fetch ->bindParam(':id',$id);
$fetch ->execute();
$output = array('data' => array());
while($row = $fetch ->fetch(PDO:: FETCH_OBJ)) {
$id = $row->roll_no;
$name = $row->name;
$class = $row->class;
$output['data'][] = array( $id,$name,class);
} // /while
echo json_encode($output);
Moved from comment
The root cause is simply because jQuery ajax() doesn't parse the JSON response from result.php. The easiest solution is to parse it inside done():
data = JSON.parse(data);
mainTable.rows.add(data.data).draw();
Another solution is to properly return JSON header in result.php. Line data = JSON.parse(data) in done() should also be omitted:
header('Content-Type: application/json');
echo json_encode($output);
I want to save checkbox change using ajax.But I can't get any saved changes.
this is the view:actionacces.phtml
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$title = 'Action \'s acces by role ';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<table class="table">
<tr>
<th>Action</th>
<?php foreach ($roles as $role) : ?>
<th><?php echo $this->escapeHtml($role['name']); ?> </th>
<?php endforeach; ?>
</tr>
<tr><?php foreach ($actions as $action) : ?>
<th> <?php echo $this->escapeHtml($action['name']);
'<\br>' ?></th>
<?php
foreach ($roles as $role) :
$exist = 0;
foreach ($acls as $acl) :
if ($acl['fk_role_id'] == $role['id'] && $acl['fk_action_id'] == $action['id'] && $acl['acces'] == 1) {
$exist = 1;
}
endforeach;
?>
<th> <?php if ($exist == 1) { ?>
<label class="css-input switch switch-sm switch-primary push-10-t">
<input type='checkbox' class="checkboxAccess" id_role="<?= $role['id'] ?>" id_action="<?= $action['id'] ?>" acces="<?= $exist ?>" checked><span></span>
</label>
<?php } else { ?>
<label class="css-input switch switch-sm switch-primary push-10-t">
<input type="checkbox" class="checkboxAccess" id_role="<?= $role['id'] ?>" id_action="<?= $action['id'] ?>" acces="<?= $exist ?>" > <span></span>
</label>
</th>
<?php }
endforeach;
?>
</tr>
<?php endforeach; ?>
</table>
this is the droit.js:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function () {
$(".checkboxAccess").on('click', function () {
// console.log($(this).attr("id_role"));
// var role_id = $(this).attr("id_role");
// var action_id = $(this).attr("id_action");
// var droit = $(this).is(':checked');
console.log($(this).attr("id_role"));
var role_id = $(this).attr("id_role");
var action_id = $(this).attr("id_action");
var acces = $(this).is(':checked');
// alert(role_id);
// alert(action_id);
$.ajax({
type: "POST",
// url:'Privilege/ACL/addACL',
url: 'Detect/Acl/modifrole',
// data: {
// "id_role": role_id,
// "id_action": action_id,
// "droit": droit},
data: {
"id_role": role_id,
"id_action": action_id,
"acces": acces
},
Success: function (result) {
alert('Success');
console.log(result);
},
Error: function () {
alert('Error');
}})
});
});
this function in controller:
public function modifroleAction() {
$request = $this->getRequest();
// echo'<pre>'; print_r($this->getRequest());die;
if ($request->isPost()) {
$parametres = $this->params()->fromPost();
$acl = new Acl();
$acl->fk_role_id = $parametres['role_id'];
$acl->fk_action_id = $parametres['action_id'];
$acces = $parametres['acces'];
if ($acces == "false") {
$acl->acces = 0;
} else {
$acl->acces = 1;
}
$this->getAclTable()->saveAcl($acl);
return $this->redirect()->toRoute('acl');
}
}
Can you help me ?
You are trying to get data by $parametres['role_id'] and $parametres['action_id'] that means role_id and action_id
But you sending -
data: {
"id_role": role_id,
"id_action": action_id,
"acces": acces
},
that means id_role, and id_action.
Change your post index may work.
I need to get two data from my both dropdowns.
First dropdown gets fabricID and the second gets sizeID.
And then ajax sends the selected data to calculates.php
I used two functions to get each dropdown data inside of one $(document).ready(function(){...
$(document).ready(function(){
$('.fabric').on('change',function(){
var fabricID = $(this).val();
console.log("fabric id_price is " + fabricID); //debugging
if(fabricID){
$.ajax({
type:'POST',
url:'calculates.php',
dataType: 'json',
data: {
fabric_id: fabricID
},
success:function(html){
//closing tags
//dont need nothing here because i need
//just to get the value from both together
});
$('.size').on('change',function(){
var sizeID = $(this).val();
if(sizeID){
$.ajax({
type:'POST',
url:'calculates.php',
dataType: 'json',
data: {
size_id: sizeID
},
success:function(html){
$('.icms').html(html); // i need to get result here
based on the result from calculates.php
//closing tags
Is this right?
Did I build the jQuery script the right way?
Because its not working.
Look to my tables:
table:almofads is where is stored my fabrics names
and i will get the id_price from the dropdown fabrics and send the id_price to
table:valores_almofadas where price_id has to be equal to the first table.
So when I select fabricID and sizeID, I will get the result from here...calculates.php
<?php header('Content-Type: application/json');
include_once '../incluedes/conn_cms.php'; //session started here
if(isset($_GET["size_id"],$_GET["id_price"])){
$size_id=$_GET["size_id"] ;
$id_price=$_GET["id_price"] ;
$query3 =" SELECT * FROM valores_almofadas
WHERE size='$size_id'
AND price_id ='$id_price'";
$result = mysqli_query($conn,$query3);
while($rows = mysqli_fetch_assoc($result)){
if($_SESSION['estado'] == 'SP'){
$ICMS = $rows['icms_7'];
}else{
$ICMS = $rows['icms_12'];
}
$_SESSION['icms']=$ICMS;
} echo json_encode($_SESSION['icms']);
}
?>
so the result will be displayed here in cart.php in $_SESSION['icms']
function cart(){
global $conn;
$fabric_options = '<option>Select fabric</option>';
$query2 = "SELECT * FROM almofadas";
$result = mysqli_query($conn,$query2);
while($rows = mysqli_fetch_assoc($result)){
$tecido=$rows['tecido'];
$id_price=$rows['id_price'];
//sizes for size dropdown
$t50='50';
$t45='45';
$fabric_options .= '<option value="'.$id_price.'">'.$tecido.'</option>';
}
foreach ($_SESSION as $name => $value) {
if($value > 0){
if(substr($name, 0, 8 ) == "product_"){
$length = strlen($name) -8;
$item_id = substr($name,8 , $length);
$query = "SELECT *
FROM gallery2
WHERE gallery2.id =".escape_string($item_id). "";
$run_item = mysqli_query($conn,$query);
while($rows = mysqli_fetch_assoc($run_item)){
$vari = $rows['variante'];
$num = $rows['title'];
$id = $rows['id'];
$btn_add ='<button type="button" class="btn btn-success actions plus" data-action="plus" product_id="'.$id.'"><i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i></button>';
$btn_remove ='<button type="button" class="btn btn-warning actions less" data-action="remove" product_id="'.$id.'"><i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i></button>';
$btn_delete ='<button type="button" class="btn btn-default actions" data-action="delete" product_id="'.$id.'" onclick="deleteRow(this)"><i class="fa fa-times fa-lg" aria-hidden="true"></i></button>';
if($rows['variante'] < 1){
$vari="";
}else{
$vari = "-".$rows['variante'];
}
$product = '
<tr>
<td style="width:100px; "><img src="../'.$rows['image'].'" style="width:90%;border: 1px solid black;"></td>
<td>'.$num.''.$vari.'</td>
<td style="width:15%;">
<select name="fabric" class="fabric select form-control selectpicker" required="" >
'. $fabric_options . '
</select>
</td>
<td>
<select id="" class="select size form-control selectpicker" required style="width:80%;" >
<option value="'.$t50.'">50x'.$t50.'</option>
<option value="'.$t45.'">45x'.$t45.'</option>
</select>
</td>
<td class="product'.$id.'">'.$value.'</td>//quantity of the product
<td class="icms'.$id.'">R$:'.$_SESSION['icms'] .'</td> // cost of product
<td class="total'.$id.'">'.$value * $_SESSION['icms'] .' </td> total of product (sub.total)
<td>
'.$btn_add.' '.$btn_remove.' '.$btn_delete.'//buttons
</td>
</tr>';
echo $product;
}
}
}
}
}
and for last my buttons functions in cart_functions.php
header('Content-Type: application/json');
session_start();
if (isset($_GET['action'])) {
$action = $_GET['action'];
$prod = $_GET['prod_id'];
$prodname = 'product_'.$prod;
$result;
switch ($action) {
case 'add':
$result = add_prod($prod, $prodname);
break;
case 'plus':
$result = plus_prod($prod, $prodname);
break;
case 'remove':
$result = remove_prod($prod, $prodname);
break;
case 'delete':
$result = delete_prod($prod, $prodname);
break;
default:
$result = ['result'=>'error'];
break;
}
}
echo json_encode($result);
function add_prod($prod, $prodname){
//sua função para add
$_SESSION[$prodname] = 1;
return ['result'=>'success'];
}
function plus_prod($prod, $prodname){
$_SESSION[$prodname]++;
return ['result'=>'success', 'val'=>$_SESSION[$prodname]];
}
function remove_prod($prod, $prodname){
//sua função para remove
$_SESSION[$prodname]--;
return ['result'=>'success', 'val'=>$_SESSION[$prodname]];
}
function delete_prod($prod, $prodname){
//sua função para delete
$_SESSION[$prodname] = null;
return ['result'=>'success'];
}
Both fabricID and sizeID need to be sent like this in the ajax call:
{size_id: sizeID} & {fabric_id: fabricID}
I'm performing CRUD oprations using JQuery/Ajax and php/MySQL
i'm able to insert/select and delete data but i gotta stuck in edit/update. im pulling data into text box when i click on edit button but after editing when i click on save button unable to update in mysql db!!
Any help is Appreciated Thanks
html code
<span class="noedit name" idl='<?php echo $row->id;?>'>
<?php echo $row->url;?>
</span>
<input id="url1" name="url1" class="form-control edit name url1" value="<?php echo $row->id;?>"/>
<a ide='<?php echo $row->id;?>' id="edit" class='editOrder' href="#" style="display:block-inline;">EDIT</a>
<a idu='<?php echo $row->id;?>' id="update" class='update saveEdit' href='#' style='display:none;'>SAVE</a>
<a idc='<?php echo $row->id;?>' id="cancel" class='cancelEdit edit' href='#' style='display:none;'>CANCEL</a>
Jquery code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
alert(IdEdit);
$.ajax({
url:"pages/feeds.php",
type:"post",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
$('#id').val(show.id);
$('#url1').val(show.url);
}
});
});
$('.update').click(function(){
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
url:"pages/feeds.php",
type:"post",
async:false,
data:{
update:1,
id:id,
upurls:urls
},
success:function(up)
{
$('input[type=text]').val('');
showdata();
},
error:function(){
alert('error in updating');
}
});
});
PHP Code
if(isset($_POST['editvalue']))
{
$sql = "select * from test where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
if(isset($_POST['update']))
{
$sql = "
update test
set
url='{$_POST['upurls']}'
where id='{$_POST['id']}'
";
$result = mysql_query($sql);
if($result)
{
//alert('success');
echo 'updated successfully';
}
else
{
//alert('failed');
echo 'failed to update';
}
}
I don't see an #id input in your code. is it there? I think the problem is here.
If this input exists, use the following tips:
Check if all values (id, url) are sended to your PHP script.
You can use console.log in Javascript or print_r, var_dump functions in PHP.
Change
$('.update').click(function(){
to
$('.saveEdit').click(function(){