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>
Related
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 using ajax,javascript, php and still new with this.
Here the scenario, I have a button with onclick function in my index.html page when I click that button I want it to redirect me to another my getdata.php page while posting and id. So when I've been redirected to my getdata.php page I just need to query using that id.
The button that trigger redirection are located at index.html <button class="btn btn-default print" name="print" data-username="{{"'.$row['msid'].'"}}" onclick="generatepdf()"><span class="icon-printer"></button>
The following codes I've been using right now. I hope I've got a lot of help right here.
index.html
<?php
session_start();
$conn = mysqli_connect("localhost","root","1234","a0");
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Cache-control" content="no-cache"> <!--The No-Cache-->
<!--Bootstrap 3.3.7 CSS-->
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!--Data Tables-->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css">
<!--Date Timepicker-->
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!--Linear Icons-->
<link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">
<!--Date Timepicker-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.min.css">
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">MENU</button>
<a class="navbar-brand" href="#"><span class="icon-bag"></span> SUPPLIER</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div class="container-fluid">
<h2 >List of Machine</h2>
<div class="table-responsive">
<div align="right">
<button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-success">New File <span class="fa fa-code-fork"></span></button>
</div>
<br>
<table id="user_data" class="table table table-bordered table-hover dt-responsive " width="100%">
<thead>
<tr>
<th width="5%">Image</th>
<th width="15%">Name</th>
<th width="10%">Date Added</th>
<th width="10%">Created By</th>
<th width="6%">Action</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add New Business Type </h4>
</div>
<div class="modal-body">
<label>Business Name</label>
<input type="text" name="businessname" id="businessname" class="form-control" />
<br />
<label>Select Business Image</label>
<input type="file" name="businessimage" id="businessimage" />
<span id="user_uploaded_image"></span>
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<input type="hidden" name="operation" id="operation" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST"
},
});
$(document).on('click', '.update', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"fetch_single.php",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#businessname').val(data.businessname);
$('.modal-title').text("Update Business Type");
$('#user_id').val(user_id);
$('#user_uploaded_image').html(data.businessimage);
$('#action').val("Save Changes");
$('#operation').val("Edit");
}
})
});
$(document).on('click', '.delete', function(){
var user_id = $(this).attr("id");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{user_id:user_id},
success:function(data)
{
alert(data);
dataTable.ajax.reload();
}
});
}
else
{
return false;
}
});
function generatepdf() {
var name = $(this).data('msid');
if (name != undefined && name != null) {
window.location = 'reports/getdata.php';
$.ajax({
url:"reports/getdata.php",
method:"POST"
});
}
};
});
</script>
<!--Data Table JS-->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/dataTables.responsive.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/responsive.bootstrap.min.js"></script>
</body>
fetch.php
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM machine_supplier ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE machine_description LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY msid DESC ';
}
if($_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$image = '';
if($row["image1"] != '')
{
$image = '<img src="machine_images/'.$row["image1"].'" class="img-thumbnail" width="50" height="35" />';
}
else
{
$image = '';
}
$sub_array = array();
$sub_array[] = $image;
$sub_array[] = $row["machine_description"];
$sub_array[] = $row["model_number"];
$sub_array[] = $row["supplier"];
$sub_array[] = '<select class="form-control">
<option selected disabled>YOUR ACTIONS</option>
<option name="update" id="'.$row["msid"].'" class="update">UPDATE</option>
<option name="delete" id="'.$row["msid"].'" class="delete">DELETE</option>
</select>
<button class="btn btn-default print" name="print" data-username="{{"'.$row['msid'].'"}}" onclick="generatepdf()"><span class="icon-printer"></button>
';
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
function.php
<?php
function upload_image()
{
if(isset($_FILES["image1"]))
{
$extension = explode('.', $_FILES['image1']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = 'machine_images/' . $new_name;
move_uploaded_file($_FILES['image1']['tmp_name'], $destination);
return $new_name;
}
}
function get_image_name($user_id)
{
include('db.php');
$statement = $connection->prepare("SELECT image1 FROM machine_supplier WHERE msid = '$user_id'");
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
return $row["image1"];
}
}
function get_total_all_records()
{
include('db.php');
$statement = $connection->prepare("SELECT * FROM machine_supplier");
$statement->execute();
$result = $statement->fetchAll();
return $statement->rowCount();
}
?>
getdata.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "databasename";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['print'])) {
$sql = "SELECT msid FROM machine_supplier WHERE";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//data
}
} else {
echo "0 results";
}
} else{
//redirect back
}
?>
</body>
</html>
Easy way is not using JS or Jquery for your requirement. Just use HTML form and PHP only like following in your index.php.
<?php
//In you index.php
//.....................
//..........................
//your other codes
//......................
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form method="post" action="getdata.php">
<input type="hidden" name="my_id" value="<?php echo $row['msid']; ?>" />
<input type="submit" value="REDIRECT AND POST MY ID" />
</form>
<?php
}
} else {
echo "0 results";
}
//.................
//.................
You just need to replace the button code with this form code and your ID will be posted and redirected to getdata.php page because of the form attribute action="getdata.php".
See the form method is post this means your form will be submitted using POST method. Now in your getdata.php file do following
<?php
$posted_id = $_POST['my_id'];
echo $posted_id;
//now get data from DB using this id
//get data from db where id = $posted_id
This is not full code for getdata.php but you will see at least your posted id(from index.php to getdata.php) using this code. There are lots to do like checking http method, error handling etc etc.
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");
}
i am facing some kind of issue here in my javascript i think, it was working to open a small windows, but i don't know how it's not working now. here's below my javascript code ad my php and html codes
<?php
require_once '../core/init.php';
$id = $_POST['id'];
if(is_numeric($id) && $id > 0 && $id == round($id, 0)){
$id = $_POST['id'];
} else {
exit;
}
$id = (int)$id;
$sql = "SELECT * FROM products WHERE id = '$id'";
$result = $db->query($sql);
$product = mysqli_fetch_assoc($result);
$brand_id = $product['brand'];
$sql = "SELECT brand FROM brand WHERE id = '$brand_id'";
$brand_query = $db->query($sql);
$brand = mysqli_fetch_assoc($brand_query);
$sizestring = $product['sizes'];
$size_array = explode(',', $sizestring);
?>
<!-- Details Modal -->
<?php ob_start(); ?>
<div class="modal fade details-1" id="details-modal" tabindex="-1" role="dialog" aria-labelledby="details-1" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button class="close" type="button" onclick="closemodal()" aria-label="close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title text-center"><?php echo $product['title']; ?></h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="col-sm-6">
<div class="center-block">
<img src="<?php echo $product['image']; ?>" alt="<?php echo $product['title']; ?>" class="details img-responsive">
</div>
</div>
<div class="col-sm-6">
<h4>Details</h4>
<p><?php echo $product['description']; ?></p>
<hr>
<p>Price: $<?php echo $product['price']; ?></p>
<p>Brand: <?php echo $brand['brand']; ?></p>
<form action="add_cart.php" method="post">
<div class="form-group">
<div clss="col-xs-3">
<label for="quantity">Quantity:</label>
<input type="text" class="form-control" id="quantity" name="quantity">
</div>
</div>
<div class="form-group">
<label for="size">Size:</label>
<select name="size" id="size" class="form-control">
<option value=""></option>
<?php foreach($size_array as $string) {
$string_array = explode(':', $string);
$size = $string_array[0];
$quantity = $string_array[1];
echo '<option value="'.$size.'">'.$size.' ('.$quantity.' Available)</option>';
} ?>
</select>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" onclick="closemodal()">Close</button>
<button class="btn btn-warning" type="submit"><span class="glyphicon glyphicon-shopping-cart"></span>Add To Cart</button>
</div>
</div>
</div>
</div>
<script>
function closemodal(){
jQuery ('#details-modal').modal('hide');
setTimeout(function(){
jQuery('#details-modal').remove();
jQuery('.modal-backdrop').remove();
},500);
}
</script>
<?php echo ob_get_clean(); ?>
After looking at your var_dump($product); result:
array(10) {
["id"]=> string(1) "1"
["title"]=> string(12) "Levi's Jeans"
["price"]=> string(5) "29.99"
["list_price"]=> string(5) "39.99"
["band"]=> string(1) "1"
["categories"]=> string(1) "6"
["image"]=> string(24) "images/products/men4.png"
["description"]=> string(16) "Description here"
["featured"]=> string(1) "1"
["sizes"]=> string(14) "28:3,32:2,36:5"
}
It's obvious that you do not have a field named 'brandin yourproducts` table.
The nearest field name to brand is band which I think is a typo. So if you change this line of your code:
`$brand_id = $product['brand'];`
To this
`$brand_id = $product['band'];`
Then you will solve the error
Notice: Undefined index: brand
And in this query $sql = "SELECT * FROM products WHERE id = '$id'"; since $id is integer, there is no need to enclose it in single quotes and you can have your query like this:
$sql = "SELECT * FROM products WHERE id = $id";
Also looking at your queries, you have two queries which you can combine them to a single query using a simple join
You have `"SELECT * FROM products WHERE id = '$id'" and "SELECT brand FROM brand WHERE id = '$brand_id'"
In table products, the field band is foreign key to table brand field id So you can simply write this query:
$sql = "SELECT products.*, brand.brand FROM products left join brand on products.band = brand.id WHERE products.id = $id";
So your php section at the top of your detailsmodal.php file will become like this:
<?php
require_once '../core/init.php';
$id = $_POST['id'];
if(is_numeric($id) && $id > 0 && $id == round($id, 0)){
$id = $_POST['id'];
} else {
exit;
}
$id = (int)$id;
$sql = "SELECT products.*, brand.brand FROM products left join brand on products.band = brand.id WHERE products.id = $id";
$result = $db->query($sql);
$product = mysqli_fetch_assoc($result);
$sizestring = $product['sizes'];
$size_array = explode(',', $sizestring);
?>
and then only at this line of your html:
<p>Brand: <?php echo $brand['brand']; ?></p>
You have to change it to
<p>Brand: <?php echo $product['brand']; ?></p>
Note: Since you are using mysqli, It's highly advised to use prepared statements instead of just putting your variable directly in your query
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>