Laravel and javascript - How do I change to users id? - javascript

I am new to laravel. How do I change to users id? I am in process of making delete users as admin. Currently it is using Auth::user(id), which means, it uses id of logged user(admin id). I got stuck, can't figure out how do I change upon clicking on button that it takes users id.
Some of the things are not being used, just standing there.
PagesController.php
public function destroy($id){
return $id;
$user = Auth::user();
$korisnik = User::findOrFail($id);
if ($korisnik->IsAdmin()){
if($korisnik->delete($id)){
return redirect()->back();
}
}else{
if ($user->delete()) {
Auth::logout();
$data = array(
'title' => 'Dobrodošli,',
'title2' => 'da biste nastavili, ulogirajte se!',
);
return view('pages.index')->with($data);
}
}
}
public function action(Request $request)
{
if($request->ajax()){
$output = '';
$query = $request->get('query');
if($query != ''){
$data = DB::table('users')
->where('surname', 'like', '%'.$query.'%')
->orWhere('name', 'like', '%'.$query.'%')
->orWhere('phone', 'like', '%'.$query.'%')
->orderBy('id')
->get();
}else {
$data = DB::table('users')
->orderBy('id')
->get();
}
$total_row = $data->count();
if($total_row > 0){
foreach($data as $row){
$output .= '
<tr>
<td>'.$row->surname.'</td>
<td>'.$row->name.'</td>
<td>'.$row->phone.'</td>
<td><button type="button" class="remove-button btn btn-danger" data-id="'.$row->id.'">
<div class="close">x</div>
</button></td>
</tr>
';
}
}else{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row,
);
echo json_encode($data);
}
}
view
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<h2>{{ $modal }}</h2>
</div>
<div class="modal-footer">
<button type="button" class="rem-mod btn btn-secondary" data-dismiss="modal">Zatvori</button>
{{ Form::open(['action'=> ['PagesController#destroy', Auth::user()->id],'method' => 'POST']) }}
{{ Form::submit('Obrišite račun', ['class' => 'bck-mod btn btn-danger']) }}
{{ Form::hidden('_method', 'DELETE') }}
{{ Form::close() }}
</div>
</div>
</div>
</div>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Pretraži korisnike</div>
<div class="panel-body">
<div class="form-group">
<input type="text" name="search" id="search" class="form-control" placeholder="Pretraži korisnike" />
</div>
<div class="table-responsive">
<h3 align="center">Broj korisnika: <span id="total_records"></span></h3>
<table id="users" class="table table-striped table-bordered">
<thead>
<tr>
<th>Prezime</th>
<th>Ime</th>
<th>Telefon</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = ''){
$.ajax({
url:"{{ route('live_search.action') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
//
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_customer_data(query);
});
$('#users').on('click', '.remove-button', function(){
var id=$(this).data('id');
$("#exampleModal").modal("show");
console.log(id);
});
$(document).on('click', '.remove-button', function(){
var id = $(this).attr('id');
{
$.ajax({
url:"{{route('live_search.destroy')}}",
method:"get",
data:{id:id},
success:function(data)
{
alert(data);
$('#users').DataTable().ajax.reload();
}
})
}
});
});

try below logic,
<td><button type="button" class="remove-button btn btn-danger" data-action="{{route('nameofroute',$row->id)}}" > </td>
Set in form Using jQuery like:
$(".remove-button ").click(function(){
$("#formId").attr('action',$(this).attr('data-action')));
})

Related

how can i refresh just the modal with ajax call without losing JavaScript tag

so im working on this library project where students can order books and admin has to confirm those requests from his side.
here is a pic of the project to have a small idea:
those are students requests
when u click on the blue button you can see more details of the student order:order details
as you can see there is the book that the student has ordered.
now what i wanted is to refresh just the modal after the admin click accept and i did achieve that by using the .load() function here is the piece of code that responsible that :code that load the modal
since we have multiple students and they can order multiple books so i had to use 2 loops that why you see those dynamic id on the modal id and button id, $tmp is for the students loop and $tmp2 is for the books loop. so far so good, the problem is when the modal refresh i lose my script tag which is bad why because all my buttons have click events so no script means buttons will not work here is before and after modal refresh before refresh you can see the script tag that responsible for the buttons and the ajax call here is after as you can see the modal refresh successfully but i lost my script so the buttons will not work so i have to reload the whole page so i can retrieve my script then the buttons will work again.
some of the solutions i tried is to put the script outside of the modal because i assumed .load() can only fetch html no script but i can't because i need the script to be inside that loop in the modal for the books button
here is the modal code if you want more details :
<!-- user books details modal -->
<div class="modal fade" id="userBooksDetails<?= $tmp ?>" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg ">
<div id="modalContent<?= $tmp ?>" class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close"></button>
</div>
<div id="modalBody<?= $tmp ?>" class="modal-body">
<table class="table">
<thead>
<tr>
<th scope="col">Picture</th>
<th scope="col">Name</th>
<th scope="col">Status</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<?php
//dont mind this its just to fetch information of the book to display it in the modal
$livre = new Livre();
$exemplaire = $livre->myBooks($user->id);
if ($exemplaire) {
//here is the second loop because student can order multiple books and each book request need to have an unique id for it button
foreach ($exemplaire as $exem) {
$tmp2--;
$copy = Exemplaire::find($exem['Num_Exemp']);
$book = Livre::find($copy->ISBN);
?>
<script>
$(document).ready(function() {
//request for accepting the order of the user
$("#acceptBook<?= $tmp2 ?>").click(function() {
let copyId = $(this).attr("data-idCopy");
$.ajax({
url: "<?= PROOT ?>emprunts/acceptOrder/" + copyId,
type: "POST",
success: function(data) {
$("#modalContent<?= $tmp ?>").load(window.location.href + " #modalContent<?= $tmp ?>" );
console.log(data)
}
});
});
//request for rejecting the order of the user
$("#rejectBook<?= $tmp2 ?>").click(function() {
let copyId = $(this).attr("data-idCopy");
$.ajax({
url: "<?= PROOT ?>emprunts/rejectOrder/" + copyId,
type: "POST",
success: function(data) {
//$("#userBooksDetails<?= $tmp ?>").load(" #userBooksDetails<?= $tmp ?>");
console.log(data);
$("#modalBody<?= $tmp ?>").load(window.location.href + " #modalBody<?= $tmp ?>" );
}
});
});
//request for returning the book (is not working after reloading on accept fix it )
$("#return<?= $tmp2 ?>").click(function() {
let copyId = $(this).attr("data-idCopy");
$.ajax({
url: "<?= PROOT ?>emprunts/returnBook/" + copyId,
type: "POST",
success: function(data) {
console.log(data);
$("#modalBody<?= $tmp ?>").load(window.location.href + " #modalBody<?= $tmp ?>" );
}
});
})
})
</script>
<tr>
<th> <img src="<?= PROOT . "/public/img/books/" . $book->img ?>" class="w-50 rounded-t-5 rounded-tr-md-0 rounded-bl-md-5" aria-controls="#picker-editor">
</th>
<td class="display-6 text-align-center">
<div class="my-5">
<?= $book->Titre_livre ?>
</div>
</td>
<td>
<div class="form-group mt-4">
<button id="stat<?= $tmp2 ?>" disabled class="btn mt-5"><?php if($exem['isConfirm']==0)
echo "Not Confirmed";
else echo "Confirmed"; ?></button>
</div>
</td>
<td id="test<?= $tmp2 ?>">
<!-- here im checking if the book is confirmed if yes im showing some specific buttons if not hiding some buttons -->
<div class="form-group mt-5">
<a <?php if($exem['isConfirm']==1)
echo "hidden";
else
echo "" ?>
id="acceptBook<?= $tmp2 ?>" class="btn m-2" data-idCopy="<?= $exem['Num_Exemp'] ?>" role="button">Accept</a>
<a <?php if($exem['isConfirm']==1)
echo "hidden";
else
echo "" ?> id="rejectBook<?= $tmp2 ?>" class="btn btn-dark m-2" data-idCopy="<?= $exem['Num_Exemp'] ?>" role="button">Reject</a>
<a <?php if($exem['isConfirm']==0)
echo "hidden";
else
echo "" ?> id="return<?= $tmp2?>" data-idCopy="<?= $exem['Num_Exemp'] ?>" class="btn btn-secondary mt-4"> Return </a>
</div>
</td>
</tr>
<?php }
}
?>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-mdb-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

How to show modal and get the Data for Update

Hi i want to ask about my problem, so in my case i want to show a modal from "Edit" button and then the modal get data from database based on id. This is my code and still didn't work. Can you tell me where i missing it?
tokoCrud.php
<?php
include ('crudAction.php');
function insertData($db, $tableName) {
$data = [
'id_ot' => ' ',
'nama_ot' => $_POST['namaToko'],
'alamat_ot' => $_POST['alamatToko'],
'status_ot' => '1'
];
if(!isDataTokoExist($db, $namaToko)) {
session_start();
include ('logger.php');
$query = buildInsertQuery($tableName, $data);
$idTarget = 'Master Barang';
$data = ['username_pstr' => $_SESSION['username'], 'Create' => 'DataToko'];
writeLogToko($db, $_SESSION['idpengguna'], $idTarget, 'Toko', 'Insert Data Toko', $data);
return runQuery($db, $query, 'insert');
}
else {
header('location: ' . $_REQUEST['pageReferrer'] . '&error=false&message=' . $result['message']);
}
}
function updateData($db, $tableName) {
$data = [
'id_ot' => ' ',
'nama_ot' => $_POST['namaToko'],
'alamat_ot' => $_POST['alamatToko']
];
if(isset($_GET['idToko'])) {
$tokoId = $_GET['idToko'];
}
$query = buildUpdateQuery($tableName, $data);
$query .= " WHERE id_ot = '$tokoId' ";
return runQuery($db, $query, 'update');
}
function isDataTokoExist($db, $namaToko) {
$namaToko = $_POST['namaToko'];
$query = "SELECT * FROM master_toko WHERE nama_ot = '$namaToko'";
$result = mysqli_query($db, $query);
return $result -> num_rows > 0;
}
function getDataToko() {
$db = getDBConnection();
$query = "SELECT * FROM master_toko ORDER BY id_ot DESC";
$result= mysqli_query($db, $query);
return $result;
}
function getDetailToko($db, $tableName) {
$tokoId = $_GET['idToko'];
$query = "SELECT * FROM $tableName WHERE id_ot = $tokoId";
$result = runQuery($db, $query, 'select');
return mysqli_fetch_array($result['data'], MYSQLI_ASSOC);
}
?>
This is endpoint.php
<?php
$action = $_GET['action'];
$objectType = $_GET['objectType'];
$db = getDBConnection();
$tableName = getTableName($objectType);
$return = [];
if ($objectType === 'toko') {
include 'tokoCrud.php';
if ($action === 'get') {
$return = getDetailToko($db, $tableName);
}
}
return json_encode($return);
die();
?>
This is formAction.php
<?php
$actionObject = $_REQUEST['actionObject'] ?? '';
$actionType = $_REQUEST['actionType'] ?? '';
include $actionObject .'Crud.php';
include 'config.php';
function getTableName($actionObject)
{
$tableMapping = [
'toko' => 'master_toko'
// 'barang' => 'table_barang',
// 'jenis' => 'table_jenis',
];
return $tableMapping[$actionObject];
}
$db = getDBConnection();
$tableName = getTableName($actionObject);
switch($actionType):
case 'insert' : $result = insertData($db, $tableName);
break;
case 'delete' : $result = deleteData($db, $tableName);
break;
case 'update' : $result = updateData($db, $tableName);
break;
endswitch;
if (!$result['error']) {
header('location: ' . $_REQUEST['pageReferrer'] . '&error=false&message=' . $result['message']);
} else {
header('location: ' . $_REQUEST['pageReferrer'] . '&error=true&message=' . $result['message']);
}
?>
This is crudAction.php
<?php
function runQuery($db, $query, $queryType) {
$result = mysqli_query($db, $query);
if(!empty(mysqli_error($db))) {
return [
'error' => true,
'message' => mysqli_error($db)
];
}
return [
'error' => false,
'message' => getMessage($queryType),
'data' => $result
];
}
function buildInsertQuery($tableName, $data) {
$tableColumns = [];
$insertValues = [];
foreach ($data as $key => $value) {
array_push($tableColumns, $key);
array_push($insertValues, $value);
}
$columns = "(`" . implode("`,`", $tableColumns) . "`)";
$values = "('" . implode("','", $insertValues) . "')";
$query = "INSERT INTO `$tableName` ". $columns . " VALUES " . $values ." ";
return $query ?? false;
}
function buildUpdateQuery($tableName, $data) {
$tableColumns = [];
$insertValues = [];
foreach ($data as $key => $value) {
array_push($tableColumns, $key);
array_push($insertValues, $value);
}
$columns = "(`" . implode("`,`", $tableColumns) . "`)";
$values = "('" . implode("','", $insertValues) . "')";
$query = "UPDATE `$tableName` SET ". $columns ." = " .$values ." ";
return $query ?? false;
}
function getMessage($queryType) {
$messages = [
'insert' => 'Data has been succesfuly added',
'update' => 'Data has been succesfuly updated',
'delete' => 'Data has been succesfuly deleted',
'select' => 'Data has been selected',
'dataDouble' => 'Data Ada yang Dobel'
];
return $messages[$queryType];
}
function getLastID() {
return mysqli_insert_id();
}
?>
This is master_toko.php
<?php
require "partial/header.php";
require "partial/sidebar.php";
include ('library/services/tokoCrud.php');
// include 'messageBox.php';
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1>Master Toko</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item active">Master Toko</li>
</ol>
</div>
</div>
</div><!-- /.container-fluid -->
</section>
<!-- Main content -->
<section class="content">
<?php include 'library/services/messageBox.php';
?>
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Data Toko</h3>
<button type="button" class="btn btn-success float-right" data-toggle="modal" data-target=".modalBesar">Tambah Data</button>
</div>
<!-- Bagian Form Modal -->
<div class="modal fade modalBesar" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="exampleModalLabel">Tambah Toko</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method = "post" action = "library/services/formAction.php">
<input type="hidden" name="pageReferrer" value="http://localhost/city/?page=store" >
<input type="hidden" name="actionObject" value="toko" >
<input type="hidden" name="actionType" value="insert" >
<div class="form-group">
<label for="recipient-name" class="col-form-label">Nama Toko</label>
<input type="text" class="form-control" id="namaToko" placeholder="Masukkan Nama Toko" name="namaToko" required>
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Alamat Toko</label>
<input type="text" class="form-control" id="alamatToko" placeholder="Masukkan Nama Toko" name="alamatToko" required>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" name="submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Akhir Bagian Modal -->
<!-- Bagian Edit Form Modal -->
<div class="modal fade modalBesar" tabindex="-1" role="dialog" aria-hidden="true" id = "modalUpdate">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="exampleModalLabel">Edit Data Toko</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method = "post" action = "library/services/formAction.php">
<input type="hidden" name="pageReferrer" value="http://localhost/city/?page=store" >
<input type="hidden" name="actionObject" value="toko" >
<input type="hidden" name="actionType" value="update" >
<input type="hidden" name="action" value="get" >
<input type="hidden" name="idToko" value="<? $idToko; ?>" >
<div class="form-group">
<label for="recipient-name" class="col-form-label">Nama Toko</label>
<input type="text" class="form-control" id="namaToko" placeholder="Masukkan Nama Toko" name="namaToko" required>
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Alamat Toko</label>
<input type="text" class="form-control" id="alamatToko" placeholder="Masukkan Nama Toko" name="alamatToko" required>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" name="submit">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Akhir Edit Bagian Modal -->
<!-- /.card-header -->
<div class="card-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>No</th>
<th>Toko</th>
<th>Alamat</th>
<th>Status</th>
<th>Opsi</th>
</tr>
</thead>
<tbody>
<?php
$n=1;
$toko = getDataToko();
while ($dataToko = mysqli_fetch_array($toko)) {
if($dataToko['status_ot']==1)
{
$status = "Aktif";
$idStatus = "1";
}
if($dataToko['status_ot']==2)
{
$status = "Tidak Aktif";
$idStatus = "2";
}
?>
<tr>
<td>
<?php echo $n++; ?>
</td>
<td>
<?php echo $dataToko['nama_ot'] ?>
</td>
<td>
<?php echo $dataToko['alamat_ot'] ?>
</td>
<td>
<?php echo $status ?>
</td>
<td>
<button type = "button" class = "view-detail btn btn-success"> Edit </button>
<button type = "button" class = "btn btn-danger deletebtn"> Delete </button>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<!-- /.content-wrapper -->
<?php require "partial/footer.php"; ?>
<script>
let buttonDetail = document.querySelectorAll('.view-detail');
buttonDetail.forEach((function(_el)) {
_el.addEventlistener('click', function(e) {
var modal = _el.getAttribute("modalBesar");
let idToko = e.target.dataset.id;
$.ajax ({
url: 'http://localhost/city/library/services/endpoint.php',
method: 'POST',
data: {action: 'get', objectType: 'toko', idToko: 'idToko'},
dataType: 'json',
success : function(response) {
let namaToko = response.namaToko;
let alamatToko = response.alamatToko;
}
});
});
});
</script>

Modal to display data using AJAX in codeigniter

These few days I'm stuck with this modal thing.
I have a long list of data.. and in order to reduce too much data display on screen. I plan to use modal so when user wants to see details.. they just click on the particular data and system display all. However, in order to display all data, need to have another function to call. I look around and found that there's no way to call function to populate data and at the same time to open modal. So I try out AJAX & JS.
My problem .. the function didn't work to open modal and display data. APpreciate if you guys out there can help me.. Thanks in advance. Here's are my codes:
Modal: modal-finance.php
defined('BASEPATH') or exit('No direct script access allowed');
class Model_finance extends CI_Model {
public function __construct() {
$this->load->database();
}
// To list HMS data
public function get_hms_data() {
$query = $this->db->select(array(
'c.*',
), false)
->where(
'c.pan is NOT NULL',NULL,FALSE
)
->get('coll_tbl c');
if ($query->num_rows() > 0) {
return $query->result();
}
else {
return false;
}
}
// To list HMS data match with PBB data by PAN No
public function matched_by_pan($pan_no){
$query = $this->db->select(array(
'c.*',
'p.approval_code',
'p.card_no'
), false)
->join('pbb_cc_tbl p', 'p.approval_code = c.approval_code','left')
->like(array(
'c.pan' => $pan_no
))
->get('coll_tbl c');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Controller: Finance.php
class Finance extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('model_finance');
}
/* Function to call the view of finance */
public function index() {
$this->load->view('pages/finance');
}
public function get_matchBYpan()
{
$this->load->model('model_finance');
$cardData = $this->input->post('cardData');
$last4pan = substr($cardData,12);
echo $last4pan;
if(isset($last4pan) and !empty($last4pan))
{
$records = $this->model_finance->matched_by_pan($last4pan);
$i=1;
$output = '';
foreach($records as $row)
{
$output .= '
<h4 class="text-center">'.$cardData.'</h4><br>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>No</th>
<th>Booking ID</th>
<th>PAN No</th>
<th>Approval Code</th>
<th>Method</th>
<th>Source</th>
<th>OTA</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>'.$i.'</td>
<td>'.$row->booking_id.'</td>
<td>'.$row->pan.'</td>
<td>'.$row->approval_code.'</td>
<td>'.$row->method.'</td>
<td>'.$row->source.'</td>
<td>'.$row->ota.'</td>
<td>'.$row->total.'</td>
</tr>
</tbody>
</table>';
$i++;
}
echo $output;
}
}
Views: fin_match.php
<!-- modal-tableHMS starts -->
<div id="modal_tableHMS" class="modal fade" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header no-padding">
<div class="table-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<span class="white">×</span>
</button>
HMS data matched by last 4 digit PBB Card number (PAN)
</div>
</div>
<div class="modal-body no-padding">
<div id="hms_result"></div>
</div>
<div class="modal-footer no-margin-top">
<button class="btn btn-sm btn-danger pull-left" data-dismiss="modal">
<i class="ace-icon fa fa-times"></i>
Close
</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal-table -->
</div> <!-- /.main-content-inner -->
<script type="text/javascript">
$(document).ready(function(){
$('.view_data').click(function(){
var cardData = $(this).attr('id');
$.ajax({
url: "<?php echo base_url() ?>Finance/get_matchBYpan",
method: "POST",
data: {cardData:cardData},
success: function(data){
$('#hms_result').html(data);
$('#modal_tableHMS').modal('show');
}
});
});
});
<!-- other codes -->
<div class="row">
<div class="col-xs-6">
<div class="col-xs-12">
<center><h3 class="row header smaller lighter blue">
<span class="col-xs-12"><b> PBB Data </b></span>
</h3></center>
<table id="dataTablePBB" class="table table-bordered table-hover">
<thead>
<tr>
<th>No</th>
<th>Transaction Date</th>
<th>PBB Card Number</th>
<th>Card Type</th>
<th>Approval Code</th>
<th>Currency</th>
<th>Gross Amount</th>
<th>Trace No</th>
</tr>
</thead>
<tbody>
<?php
if(!empty($PBBdata)):
$i=1;
foreach($PBBdata as $row)
{
echo '<tr>';
echo '<td>'.$i.'</td>';
echo '<td>'.$row->trans_date.'</td>';
echo '<td>';
?>
<input type="button" name="view" value="<?php echo $row->card_no; ?>" id="<?php echo $row->card_no; ?>" class="btn btn-info btn-sm view_data"">
<?php
echo '</td>';
echo '<td>'.$row->card_type.'</td>';
echo '<td>'.$row->approval_code.'</td>';
echo '<td>'.$row->gross_cur.'</td>';
echo '<td>'.$row->gross_amt.'</td>';
echo '<td>'.$row->trace_no.'</td>';
echo '</tr>';
$i++;
}
endif;
?>
</tbody>
</table>
</div> <!--col-xs-12-->
</div>
It seems that on your JS script has returning failure. If you are using Chrome you can check it on Console or Network -> XHR there are more detailed information regarding on that error.
And that $output variable must be array because the view needs a storage since it is inside foreach loop and return it like this * echo json_encode($output)* Please see more here.

can't show the modal in codeigniter using ajax

I'm working with codeigniter, and i want to show the detail data in modal, the detail data is from another table.
I have a button like this:
<button class="btn btn-info" onclick="detail_barang("<?php echo $tbrang->id_barang;?>")">Detail</button>
And this is my detail_barang function:
function detail_barang(id)
{
$('#form')[0].reset(); // reset form on modals
$.ajax({
url : "<?php echo site_url('admin/Barang/barang/ajax_detail_barang/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('#modal_detail').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Detail Barang'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Kesalahan!');
}
});
}
Modal Script:
<div class="modal fade" id="modal_detail">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title">Detail Barang</h3>
</div>
<div class="modal-body">
<table class="table table-striped" id="tblGrid">
<thead id="tblHead">
<tr>
<th>ID Barang</th>
<th>No Inv</th>
<th class="text-right">Kondisi</th>
</tr>
</thead>
<tbody>
<?php
foreach($detail_barang as $detil)
{?>
<tr>
<td><?php echo $detil->id_barang ?></td>
<td><?php echo $detil->no_inv ?></td>
<td><?php echo $detil->kondisi ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default " data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
ajax_detail_barang function:
public function ajax_detail_barang($id)
{
$where = array
(
'id_barang' => $id,
'kondisi' => 'Ada'
);
$data['detail_barang'] = $this->modelku->get_by_id('detail_barang', $where)->result();
echo json_encode($data);
}
get_by_id function:
public function get_by_id($table, $where)
{
$this->db->from($table);
$this->db->where($where);
$query = $this->db->get();
return $query->row();
}
But when i click the button, the error appears "Kesalahan!" whats wrong my code?
The problem i see is in how u are using the returned data from ur model
public function get_by_id($table, $where)
{
$this->db->from($table);
$this->db->where($where);
$query = $this->db->get();
return $query->row();
//at this point it already contains the data u need
}
but here u are using result();
$data['detail_barang'] = $this->modelku->get_by_id('detail_barang', $where)->result();
//i tried and u cant use result method if u already executed row method.
In short, remove result()
Hope my answer helps u.

data is not parsing inside the json

I am trying to fetch data through js function using pdo and bootstrap modal but my problem is data is not coming properly inside json through php function. details.php is not getting data properly and i am getting uncaught syntax error in getEventDetails function in json parsing.
here is my code
here I'am fetching data and performing update function
<html>
<table class="table table-bordered table-striped">
<form method="POST">
<tr>
<th>Event Name</th>
<th>Event Date</th>
<th>Update</th>
<th>Delete</th>
</tr>
<?php
include '../class.php';
$object = new crud();
$users = $object->readEvent();
if (count($users) > 0)
{
$number = 1;
foreach ($users as $user)
{
echo '<tr>
<td>'.$user['Event_Name'].'</td>
<td>'.$user['Event_Date'].'</td>
<td>
<button type="button" class="btn btn-warning" onClick="GetEventDetails('.$user['Event_ID'].')" class="btn btn-warning">Update</button>
</td>
<td>
<button type="button" onClick="DeleteEvent('.$user['Event_ID'].')" class="btn btn-danger">Delete</button>
</td>
</tr>';
}
}
?>
</form>
</table>
<!-- Modal-Update Event List-->
<div class="modal fade" id="update_event_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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>
<h4 class="modal-title" id="myModalLabel">Update</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="update_event_name">Event Name</label>
<input type="text" id="update_event_name" class="form-control"/>
</div>
<div class="form-group">
<label for="update_event_date" class="col-xs-2 col-form-label">Date and time</label>
<input type="text" id="update_event_date" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="updateEvent()" >Save Changes</button>
<input type="hidden" id="hidden_event_id">
</div>
</div>
</div>
</div>
GetEventDetail function
function GetEventDetails(id)
{
// Add User ID to the hidden field for furture usage
$("#hidden_event_id").val(id);
$.post("ajax/details.php",
{
id: id
},
function (data, status)
{
// PARSE json data
var user = JSON.parse(data);
// Assing existing values to the modal popup fields
$("#update_event_name").val(user.event_name);
$("#update_event_date").val(user.event_date);
}
);
// Open modal popup
$("#update_event_modal").modal("show");
}
after this it goes to details.php, code for details.php
<?php
include '../class.php';
if(isset($_POST['id']) && isset($_POST['id']) != "")
{
$user_id = $_POST['id'];
//echo $id;
$object = new crud();
$object->EventDetails($user_id);
}
else
{
echo 0;
}
?>
and it goes to php function.
public function EventDetails($user_id)
{
$query = $this->DB_conn->prepare("SELECT Event_Name, Event_Date FROM My_Event WHERE Event_ID = :id");
$query->bindParam("id", $user_id, PDO::PARAM_STR);
$query->execute();
return json_encode($query->fetch(PDO::FETCH_ASSOC));
}
Update event fucntion
function updateEvent()
{
// get values
var update_event_name = $("#update_event_name").val();
var update_event_date = $("#update_event_date").val();
//update_category_name = update_category_name.trim();
// get hidden field value
var id = $("#hidden_event_id").val();
// Update the details by requesting to the server using ajax
$.post("ajax/updatedata.php",
{
id: id,
update_event_name: update_event_name,
update_event_date: update_event_date
},
function (data, status)
{
alert("Data: " + data + "\nStatus: " + status);
$("#update_event_modal").modal("hide");
// read records again
readEvent();
// clear fields from the popup
$("#update_event_name").val("");
$("#update_event_date").val("");
}
);
}
updatedata.php
<?php
include("../class.php");
if (isset($_POST['update_event_name']) && isset($_POST['update_event_date']) && isset($_POST['id']))
{
$id = $_POST['id'];
$update_event_name = $_POST['update_event_name'];
$update_wedding_date = $_POST['update_event_date'];
$object = new crud();
$object->UpdateEvent($update_event_name, $update_wedding_date, $id);
}
else
{
echo 0;
}
?>
public function UpdateEvent($update_event_name, $update_wedding_date,$id)
{
$query = $this->DB_conn->prepare("UPDATE My_event SET Event_Name = :update_event_name, Event_Date = :update_wedding_date WHERE Event_ID = :id");
$query->bindParam("update_event_name", $update_event_name, PDO::PARAM_STR);
$query->bindParam("update_wedding_date", $update_wedding_date, PDO::PARAM_STR);
$query->bindParam("id", $id, PDO::PARAM_STR);
$query->execute();
}
You don't receive the data, because you have never actually outputted that to the client. So, in your details.php:
echo $object->EventDetails($user_id);
and similarly, in the updatedata.php:
echo $object->UpdateEvent($update_event_name, $update_wedding_date, $id);
I found the solution, problem was with json parse so i added litillt code and now it's working fine.
function GetEventDetails(id)
{
// Add User ID to the hidden field for furture usage
$("#hidden_event_id").val(id);
$.post("ajax/details.php",
{
id: id
},
function (data, status)
{
var data_name = 0;
var data_date = 0;
// PARSE json data
var user = JSON.parse(data);
$(user).each(function(i,val)
{
$.each(val,function(k,v)
{
console.log(k+" : "+ v);
if(k == "Event_Name")
{
data_name = v;
}
else if(k == "Event_Date")
{
data_value = v;
}
});
});
$("#update_event_name").val(data_name);
$("#update_event_date").val(data_value);
}
);
// Open modal popup
$("#update_event_modal").modal("show");
}

Categories

Resources