#php #html #jquery #json #ajax
#php #HTML #jquery #json #ajax
Вопрос:
Я создаю панель мониторинга для своего веб-сайта портфолио, который строится с использованием php, ООП, ajax и Jquery datatable. Для сбора данных я использую datatable. Я могу отобразить данные в таблице. Но я не могу понять, как захватить отдельные данные из таблицы данных в загрузочный режим, когда я нажимаю на кнопку редактирования? Я перепробовал много руководств с YouTube и Google. данные json отображаются в devtool. Но не в модальном. вот снимок экрана проблемы вместе с моим классом панели мониторинга и table.js данные файла отображаются в формате json, но не отображаются в модальном
Это мой модальный html-код :
<div id="recordModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-
dismiss="modal">amp;times;</button>
</div>
<div class="modal-body">
<form method="POST" id="recordForm" enctype="multipart/form-
data">
<div class="table-responsive-sm">
<table class=" table table-borderless table-sm">
<tr>
<td><label for="Image">Image:</label></td>
<td>
<input type="file" name="image" class="form-control-file
form-control-sm" id="user_img">
</td>
</tr>
<tr>
<td> <label for="Name">Name:</label></td>
<td>
<input type="text" class="form-control-sm
form-control" id="user_name" name="Name" placeholder="Enter your Name">
</td>
</tr>
<tr>
<td> <label for="Title">Title:</label> </td>
<td>
<input type="text" class="form-control-sm
form-control" id="user_title" name="Title" placeholder="Enter a Title">
</td>
</tr>
<tr>
<td> <label for="Aim amp; Mission">Mission:</label>
</td>
<td>
<textarea name="Vision" id="vision" cols="10"
rows="5" class="form-control form-control-sm" placeholder="Enter a
Description about you!!">
</textarea>
</td>
</tr>
<tr>
<td> <label for="Expertise">Expertise in:</label>
</td>
<td>
<input type="text" class="form-control-sm
form-control" id="expt" name="Expertise" placeholder="Enter what you
expert
in!!">
</td>
</tr>
<tr>
<td><label for="Experience">Experience:</label>
</td>
<td>
<input type="text" class="form-control-sm
form-control" id="exper" name="Experience" placeholder="Enter your
current
position!!">
</td>
</tr>
<tr>
<td> <label for="Current Position:">Position:</label>
</td>
<td>
<input type="text" class="form-control-sm form-
control" id="cPos" name="cPosition" placeholder="Enter your Name">
</td>
</tr>
<tr>
<td> <label for="Link">Link Fiverr:</label></td>
<td>
<input type="text" class="form-control-sm
form-control" id="fiver" name="Fiverr" placeholder="link of your
fiverr
profile">
</td>
</tr>
<tr>
<td colspan="1"> <label for="Link">Link LinkedIn:
</label> </td>
<td>
<input type="text" class="form-control-sm
form-control" id="linked" name="linkedIn" placeholder="link of your
fiverr
profile">
</td>
</tr>
<tr>
<td> <label for="Link">Link Upwork:</label></td>
<td>
<input type="text" class="form-control-sm
form-control" id="upwo" name="upWork" placeholder="link of your
fiverr
profile">
</td>
</tr>
</table>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="id" id="id">
<input type="hidden" name="action" id="action" value="">
<input type="submit" name="save" id="save" class="btn
btn-info" value="Save">
<button type="button" class="btn btn-default" data-
dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
</div>
Вот мой код класса DashBoard :
<?php
namespace PortFolioAppDashboard;
use PortFolioApphelpersFormat;
use PDO;
use PortFolioAppModelDatabase;
class DashBoard extends Database
{
public $id;
public $name;
public $title;
public $vision;
public $expertise;
public $experience;
public $cPosition;
public $fiVer;
public $upWork;
public $linkedIn;
public $image;
public function setData($array)
{
if (array_key_exists("id", $array)) {
$this->id = $array['id'];
}
if (array_key_exists("Name", $array)) {
$this->name = $array['Name'];
}
if (array_key_exists("Title", $array)) {
$this->title = $array['Title'];
}
if (array_key_exists("Vision", $array)) {
$this->vision = $array['Vision'];
}
if (array_key_exists("Expertise", $array)) {
$this->expertise = $array['Expertise'];
}
if (array_key_exists("Experience", $array)) {
$this->experience = $array['Experience'];
}
if (array_key_exists("cPosition", $array)) {
$this->cPosition = $array['cPosition'];
}
if (array_key_exists("Fiverr", $array)) {
$this->fiVer = $array['Fiverr'];
}
if (array_key_exists("upWork", $array)) {
$this->upWork = $array['upWork'];
}
if (array_key_exists("linkedIn", $array)) {
$this->linkedIn = $array['linkedIn'];
}
if (array_key_exists("profilePicture", $array)) {
$this->image = $array['profilePicture'];
} }//end of setData;
//starting data store function;
public function store()
{
$name = $this->name;
$title = $this->title;
$vision = $this->vision;
$cPosition = $this->cPosition;
$expertise = $this->expertise;
$experience = $this->experience;
$fiVer = $this->fiVer;
$upWork = $this->upWork;
$linkedIn = $this->linkedIn;
$image = $this->image;
$array = array();
$sqlQuery = "INSERT INTO
summary (name,
title,
vision,
cposition,
expertise,
experience,
fiverr,
upwork,
linkedin,
profile)
VALUES (:name,
:title,
:vision,
:cPosition,
:expertise,
:experience,
:fiVer,
:upWork,
:linkedIn,
:image)";
$dataArray = array(
':name' =>$name,
':title' =>$title,
':vision'=>$vision,
':cPosition'=>$cPosition,
':expertise'=>$expertise,
':experience'=>$experience,
':fiVer'=>$fiVer,
':upWork'=>$upWork,
':linkedIn'=>$linkedIn,
':image'=>$image
);
$STH = $this->DBH->prepare($sqlQuery);
foreach($dataArray as $dt=>$key){
$STH->bindValue(':'.$dt, $key,PDO::PARAM_STR);
}
$result = $STH->execute($dataArray);
// return $STH->rowCount();
if (isset($result)) {
// $ok = false;
if (empty($dataArray[':name'])){
// $ok = true;
$array[] = "empty form not submitted";
} else {
// $ok = false;
$array[] ="<p class='alert alert-success'>form submitted</p>";
} }
foreach($array as $ar)
{
echo json_encode($ar);
} }
//view all the data in front-end
public function index()
{
$sqlQuery = "select * from summary WHERE is_trashed='NO'";
$STH = $this->DBH->query($sqlQuery);
$STH->setFetchMode(PDO::FETCH_OBJ);
$allData = $STH->fetchAll();
return $allData;
}
//fetch data from database in a datatable
public function fetch()
{
// $srQuery = '';
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = $_POST['search']['value']; // Search value
$searchArray = array();
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = "AND ( `name` LIKE :name or
`title` LIKE :title OR
`vision` LIKE :vision OR
`expertise` LIKE :expertise OR
`experience` LIKE :experience OR
`cposition` LIKE :cposition OR
`fiverr` LIKE :fiverr OR
`upwork` LIKE :upwork OR
`linkedin` LIKE :linkedin OR
`profile` LIKE :profile
) ";
$searchArray = array(
'name'=>"% $searchValue %",
'title'=>"% $searchValue %",
'vision'=>"% $searchValue %",
'expertise'=>"% $searchValue %",
'experience'=>"% $searchValue %",
'cposition'=>"% $searchValue %",
'fiverr'=>"% $searchValue %",
'upwork'=>"% $searchValue %",
'linkedin'=>"% $searchValue %",
'profile'=> "% $searchValue %"
);
}
$query = " SELECT COUNT(*) AS `allcount` FROM `summary` ";
$STH =$this->DBH->prepare($query);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_OBJ);
$records = $STH->fetch();
$totalRecords = $records->allcount;
$srQuery = " SELECT COUNT(*) AS `allcount` FROM `summary` WHERE 1 ".$searchQuery;
$STH =$this->DBH->prepare($srQuery);
$STH->execute($searchArray);
$STH->setFetchMode(PDO::FETCH_OBJ);
$records = $STH->fetch();
$filter = $records->allcount;
$orderQuery = " SELECT * FROM `summary` WHERE 1".$searchQuery." ORDER BY ".$columnName." ".$columnSortOrder." LIMIT :limit , :offset " ;
$STH =$this->DBH->prepare($orderQuery );
foreach($searchArray as $key=>$search){
$STH->bindValue(':'.$key, $search,PDO::PARAM_STR);
}
$STH->bindValue(':limit',(int)$row, PDO::PARAM_INT);
$STH->bindValue(':offset',(int)$rowperpage, PDO::PARAM_INT);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_OBJ);
$empRecords = $STH->fetchAll();
$data = array();
foreach($empRecords as $row){
$btn = '<div class="btn-group btn-group-sm ">
<button type="button" name="update" id="'.$row->id.'" class="btn btn-info btn-xs btn-outline-info update" ><i class="fas fa-2x"></i></button>
<button type="button" name="delete" id ="'.$row->id.'" class="btn btn-secondary btn-xs btn-outline-secondary delete" ><i class="fas fa-2x"></i></button>
<button type="button" name="view" id="'.$row->id.'" class="btn btn-primary btn-xs btn-outline-primary view" ><i class="far fa-2x"></i></button>
<button type="button" name="recover" id="'.$row->id.'" class="btn btn-success btn-xs btn-outline-success recover" ><i class="fas fa-2x"></i></button>
</div>';
$img = '';
$profileImage = $row->profile;
if( $profileImage!== ''){
$img = '<img src="images/'.$profileImage.'" class="img-fluid" alt="img"/> ';
}else{
$img = '';
}
$expertise = $row->expertise;
$exp = explode(",", $expertise);
$des = new Format();
$vision = $row->vision;
$shortText = $des->textShorten($vision , 20);
$data[] = array(
"name"=> $row->name,
"title"=> $row->title,
"vision"=>$shortText,
"expertise"=>'<a href="#" class="badge badge-pill badge-primary">'.implode(" ",$exp).'</a>',
"experience"=> $row->experience,
"cposition"=> $row->cposition,
"fiverr"=> $row->fiverr,
"upwork"=> $row->upwork,
"linkedin"=> $row->linkedin,
"profile"=> $img,
"#"=> $btn
);
}
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $filter ,
"aaData" => $data
);
echo json_encode($response);
}
//get records for editing in the modal
public function getRecords(){
if($this->id){
$query = "SELECT * FROM `summary` WHERE `id`=:id";
$STH = $this->DBH->prepare($query);
$STH->bindParam(":",$this->id);
$STH->execute(array(
":id" =>$this->id)
);
$STH->setFetchMode(PDO::FETCH_OBJ);
$row = $STH->fetchAll();
echo json_encode($row);
}
}
// view single data in front-end
public function view()
{
$sqlQuery = "SELECT * FROM summary WHERE `id`= '.$this->id.'";
$STH = $this->DBH->query($sqlQuery);
$STH->setFetchMode(PDO::FETCH_OBJ);
$singleData = $STH->fetch();
return $singleData;
}
//update records in a modal
public function update()
{
$name = $this->name;
$title = $this->title;
$vision = $this->vision;
$cPosition = $this->cPosition;
$expertise = $this->expertise;
$experience = $this->experience;
$fiVer = $this->fiVer;
$upWork = $this->upWork;
$linkedIn = $this->linkedIn;
$image = $this->image;
if($THIS->id){
$sqlQuery = "UPDATE summary SET
name=?,
title=?,
vision=?,
cposition=?,
expertise=?,
experience=?,
fiverr=?,
upwork=?,
linkedin=?,
profile=?
WHERE id='.$this->id.'";
$dataArray = array(
$name,
$title,
$vision,
$cPosition,
$expertise,
$experience,
$fiVer,
$upWork,
$linkedIn,
$image
);
$STH = $this->DBH->prepare($sqlQuery);
$result = $STH->execute($dataArray);
if (!isset($name,
$title,
$vision,
$cPosition,
$expertise,
$experience,
$fiVer,
$upWork,
$linkedIn,
$image)) {
echo "<p class='alert alert-warning text-center'>Filed Must not be empty</p>";
} else {
if ($result) {
echo '<p class="alert alert-success text-center">profile Updated Successfully!!</p>';
} else {
echo '<p class="alert alert-info text-center">There was an error while Updating your Profile please try later!</p>';
}
}
}
}
}
Это мой table.js код:
// Data table processing
$(document).ready(function(){
var dataRecords = $('#example').DataTable({
bProcessing: true,
serverSide:true,
responsive:true,
serverMethod: "post",
pagingType : "full_numbers",
//scrollX :true,
iDisplayLength: 8,
alengthMenu: [ [10, 25, 50, -1], [10, 25, 50, "All"] ],
ajax: {
url: "fetch.php",
type: "POST",
dataType:"json"
},
columns:[
{data: "name"},
{data: "title"},
{data: "vision"},
{data: "expertise"},
{data: "experience"},
{data: "cposition"},
{data: "fiverr"},
{data: "upwork"},
{data: "linkedin"},
{data: "profile"},
{data: "#"}
],
columnDefs:[
{targets: 10,
orderable: false,
searchable : false
}
]
});
// page load on click
$('.navbar').on('click','.nav-link',function(e) {
e.preventDefault();
var page = $(this).attr('href');
if(page !=='#') {
$.ajax({
url: page,
type: 'GET',
dataType: 'html',
success: function(data){
$('#content').html(data);
$('.navbar').height('auto');
dataRecords.ajax.reload();
}
});
} else{
$(document.body).load('index.php');
}
});
//submitting form with ajax request
$("#summary").on('submit',function(e){
e.preventDefault();
var form = new FormData(this);
$.ajax({
url: 'sunForm.php',
type: 'POST',
data: form,
async:false,
dataType: 'json',
success: function(response) {
$('#message').fadeIn(800).html( response );
$('#message').fadeOut(800).html( response );
dataRecords.ajax.reload()
},
contentType: false,
processData: false,
cache: false
});
$('#summary')[0].reset();
;
return false;
});
//this is code for showing single data from data table in a modal for
editing
$("#example").on('click', '.update', function(){
var id = $(this).attr("id");
var action = 'getRecords';
$.ajax({
url:'action.php',
method:"POST",
data:{id:id, action:action},
dataType:"json",
success:function(data){
$('#recordModal').modal('show');
$('#id').val(JSON.stringify(data.id));
//$("#user_img").val(data.image);
$('#user_name').val(JSON.stringify(data.Name));
$('#user_title').val(data.Title);
$('#vision').val(data.Vision);
$('#expt').val(data.Expertise);
$('#exper').val(data.Experience);
$('#cPos').val(data.cPosition);
$('#fiver').val(data.Fiverr);
$('#linked').val(data.linkedIn);
$('#upwo').val(data.upWork);
$('#action').val('update');
// $('#save').val('Save');
}
})
});
});