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");
}
Related
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>
I have a code which inserts data from a modal form into two related tables, namely inventory_order table and inventory_order_product table. That code is working fine but my problem comes when I want to fetch the same data back into the modal form for editing. The code for fetch single is only retrieving data for the first line in the selectpicker while the remaining are not retrieved. Please if my question is not clear refer to the image below and please bear with me I'm a novice in php, ajax and mysql.
$(document).on('click', '.update', function(){
var inventory_order_id = $(this).attr("id");
var btn_action = 'fetch_single';
$.ajax({
url:"order_action.php",
method:"POST",
data:{inventory_order_id:inventory_order_id, btn_action:btn_action},
dataType:"json",
success:function(data)
{
$('#orderModal').modal('show');
$('#inventory_order_name').val(data.inventory_order_name);
$('#inventory_order_date').val(data.inventory_order_date);
$('#inventory_order_address').val(data.inventory_order_address);
$('#span_product_details').html(data.product_details);
$('#payment_status').val(data.payment_status);
$('.modal-title').html("<i class='fa fa-pencil-square-o'></i> Edit Order");
$('#inventory_order_id').val(inventory_order_id);
$('#action').val('Edit');
$('#btn_action').val('Edit');
}
})
});
if($_POST['btn_action'] == 'fetch_single')
{
$query = "
SELECT * FROM inventory_order WHERE inventory_order_id = :inventory_order_id
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':inventory_order_id' => $_POST["inventory_order_id"]
)
);
$result = $statement->fetchAll();
$output = array();
foreach($result as $row)
{
$output['inventory_order_name'] = $row['inventory_order_name'];
$output['inventory_order_date'] = $row['inventory_order_date'];
$output['inventory_order_address'] = $row['inventory_order_address'];
$output['payment_status'] = $row['payment_status'];
}
$sub_query = "
SELECT * FROM inventory_order_product
WHERE inventory_order_id = '".$_POST["inventory_order_id"]."'
";
$statement = $connect->prepare($sub_query);
$statement->execute();
$sub_result = $statement->fetchAll();
$product_details = '';
$count = '';
$count = $count++;
foreach($sub_result as $sub_row)
{
$product_details .= '
<script>
$(document).ready(function(){
$("#product_id'.$count.'").selectpicker("val", '.$sub_row["product_id"].');
$(".selectpicker").selectpicker();
});
</script>
<span id="row'.$count.'">
<div class="row">
<div class="col-md-8">
<select name="product_id[]" id="product_id'.$count.'" class="form-control selectpicker" data-live-search="true" required>
'.fill_product_list($connect).'
</select>
<input type="hidden" name="hidden_product_id[]" value="'.$sub_row["product_id"].'" />
</div>
<div class="col-md-3">
<input type="text" name="quantity[]" class="form-control" value="'.$sub_row["quantity"].'" required />
</div>
<div class="col-md-1">
';
if($count == '')
{
$product_details .= '<button type="button" name="add_more" id="add_more" class="btn btn-success btn-xs">+</button>';
}
else
{
$product_details .= '<button type="button" name="remove" id="'.$count.'" class="btn btn-danger btn-xs remove">-</button>';
}
$product_details .= '
</div>
</div>
</div><br />
</span>
';
}
$output['product_details'] = $product_details;
echo json_encode($output);
}
Problem in your code is with variable $count.As in your backend code this is declare outside your foreach.. loop so when first time your loop will run it will have correct value i.e : 0 but you never increment it that's why it is only giving correct value for first selectpicker. Instead you need to increment its value to set value for second value ,third and so on. i.e :
foreach($sub_result as $sub_row)
{
//you code html and jquery
$count = $count++;//add this inside for loop
}
Also, i don't why you have given $count = ''; . Instead , it should be $count = 0;
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')));
})
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.
I'm trying to generate dynamic page with ajax containing pagination, dropdown list, and search bar.
Search bar, pagination and dropdown list are managed well and adapt themselves as needs one.
Now, concerning search bar, when I try to search something, and when there is more than 5 results, if I click on page 2 for example, the next results are not displayed !
No error is indicated in logs!
Would it be possible to be pointed in the right direction please?
<?php
require('config/config.php');
if(!isset($_SESSION))
{
session_start();
}
if(isset($_SESSION['flash']))
{
foreach($_SESSION['flash'] as $type => $message)
{
echo $message;
}
unset($_SESSION['flash']);
}
$nb_per_page = !empty($_POST['nb_per_page']) ? $_POST['nb_per_page'] : 5;
$search = !empty($_POST['search']) ? $_POST['search'] : "";
$p = !empty($_POST['page']) ? $_POST['page'] : 1;
$output = "";
$result = getList($nb_per_page, $search, $p, $cnx);
showList($result['list']);
pagination($result['nb_pages'], $p);
function getList($nb_per_page, $search, $p, $cnx)
{
$nb_per_page = intval($nb_per_page);
$start = intval(($p-1) * $nb_per_page);
$where = "";
if($search != "")
{
$where .= "WHERE lastName LIKE '%".$search."%' OR firstName LIKE '%".$search."%' OR age LIKE '%".$search."%' OR scheduleRange LIKE '%".$search."%' OR phoneNumber LIKE '%".$search."%' OR email LIKE '%".$search."%' OR candidacyType LIKE '%".$search."%'";
}
$query = $cnx->prepare("SELECT * FROM candidacies ".$where." LIMIT :start, :nb_per_page");
$query->bindValue(':start', $start, PDO::PARAM_INT);
$query->bindValue(':nb_per_page', $nb_per_page, PDO::PARAM_INT);
$query->execute();
$list = $query->fetchAll(PDO::FETCH_ASSOC);
$query = $cnx->prepare('SELECT COUNT(id) AS totalResults FROM candidacies '.$where.' ');
if($search != "")
{
$where .= "WHERE lastName LIKE '%".$search."%' OR firstName LIKE '%".$search."%' OR age LIKE '%".$search."%' OR scheduleRange LIKE '%".$search."%' OR phoneNumber LIKE '%".$search."%' OR email LIKE '%".$search."%' OR candidacyType LIKE '%".$search."%'";
}
$query->execute();
$result = $query->fetch(PDO::FETCH_OBJ);
$nb = $result->totalResults;
$nb_pages = ceil($nb / $nb_per_page);
if($nb_pages < 1)
{
$nb_pages = 1;
}
return array(
"list" => $list,
"nb" => $nb,
"nb_pages" => $nb_pages
);
}
function showList($list)
{
$output = "";
$output .= '
<table class="table table-striped" id="candidaciesTable">
<thead class="thead-light">
<tr>
<th scope="col">lastName</th>
<th scope="col">firstName</th>
<th scope="col">Âge</th>
<th scope="col">Schedule Range</th>
<th scope="col">Phone Number</th>
<th scope="col">Email</th>
<th scope="col">Candidacy Type</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
';
foreach($list as $key => $value)
{
$output .= "
<tr>
<td>".htmlspecialchars($value["lastName"])."</td>
<td>".htmlspecialchars($value["firstName"])."</td>
<td>".htmlspecialchars($value["age"])."</td>
<td>".htmlspecialchars($value["scheduleRange"])."</td>
<td>".htmlspecialchars($value["phoneNumber"])."</td>
<td>".htmlspecialchars($value["email"])."</td>
<td>".htmlspecialchars($value["candidacyType"])."</td>
<td>
<div class='btn-group'>
<button class='btn btn-light btnViewCandidacy' id=".$value['id'].">
<i class='far fa-eye'></i>
</button>
<button class='btn btn-info' id='btnEditCandidacy' onclick='editCandidacy(".$value['id'].")'>
<i class='far fa-edit'></i>
</button>
<button class='btn btn-danger' id='btnDeleteCandidacy' onclick='deleteCandidacy(".$value['id'].")'>
<i class='far fa-trash-alt'></i>
</button>
</div>
</td>
</tr>
";
}
$output .= "
</tbody>
</table>";
echo $output;
}
function pagination($nb_pages, $page)
{
$output = "";
$output .= "<div class='pagination-centered'>";
/*if($page > 1)
{
$output .= '<a class="paginationLink" id="'.$i.'">Prev</a>';
}*/
for($i = 1; $i <= $nb_pages; $i++)
{
$class = "";
if($page == $i){
$class = "active";
}
$output .= '<a class="paginationLink '.$class.'" id="'.$i.'">'.$i.'</a>';
}
/*if($page > $nb_pages)
{
$output .= '<a class="paginationLink" id="'.$i.'">Next</a>';
}*/
$output .= "</div>";
echo $output;
}
$output .= '
<div class="modal" tabindex="-1" role="dialog" id="candidacyModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Candidature</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>';
echo $output;
?>
$(document).ready(function()
{
$('#searchContent').keyup(function()
{
var search = $(this).val();
var nb_per_page = $('.entriesData').val();
var page = 1;
loadContent(nb_per_page, search, page);
});
$('.entriesData').change(function ()
{
var nb_per_page = $(this).val();
var search = $('#searchContent').val();
var page = 1;
loadContent(nb_per_page, search, page);
});
$('.paginationLink').on('click', function()
{
var page = $(this).attr('id');
var nb_per_page = $('.entriesData').val();
var search = $('#searchContent').val();
//loadPagination(page);
loadContent(nb_per_page, search, page);
});
$('.btnViewCandidacy').on('click', function ()
{
var candidacyId = $(this).attr('id');
$.ajax({
url:"viewCandidacy.php",
method:"get",
data:{candidacy:candidacyId},
success:function(data)
{
$('#modal-body').html(data);
$('#candidacyModal').modal("show");
}
});
});
});
function loadContent(nb_per_page, search, page)
{
var p = {};
p['nb_per_page'] = nb_per_page;
p['search'] = search;
p['page'] = page;
$.post("search.php", p, function(data)
{
$("#result").html(data);
});
}
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<div class="input-group">
<button class="btn btn-outline-success my-2 my-sm-0">Search</button>
<input type="text" name="searchContent" id="searchContent" placeholder="searchContent" class="form-control" />
</div>
</div>
<label>Display<select name="entriesData" class="entriesData">
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5" selected>5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
résults</label>
<div id="result">
<?php include('search.php');?>
</div>
</body>
please add jquery references like
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>