Save ajax post data on div to localStorage - javascript

I created a datatable in which there is a button which has an action to post data into a div, below is the code I have:
html :
<div class="card-body">
<div class="overlay" id="kt_datatable_nodata">
<div class="overlay-wrapper rounded bg-light text-center pt-lg-30 pb-lg-30"
style="border: 2px dashed #c6c6c6;">
<p class="font-weight-bold text-center">Pilih data untuk dibandingkan.</p>
<a href='#left-modal' class='btn font-weight-bolder btn-jcm btn-md'
data-toggle='modal'>Pilih Data</a>
</div>
</div>
<div id="kt_datatable_fetch_display"></div>
</div>
This my datatable :
"use strict";
var LeftTable = function() {
var options = {
data: {
type: 'remote',
source: {
read: {
url: 'src/khu-pusat/json/compare.php',
},
},
},
columns: [{
field: 'name',
title: 'Name',
template: function(row) {
return row.nama_karyawan;
},
},{
field: 'proyek',
title: 'Proyek',
template: function(row) {
return row.proyek;
},
},{
field: 'action',
title: 'Action',
template: function(row) {
return '<button data-id="'+ row.id +'" class="btn btn-sm btn-jcm" type="button" data-dismiss="modal">Pilih</button>';
},
},]
};
var displayLeftData = function() {
$('#kt_datatable').on('click','tr button', function() {
var leftId = $(this).data('id');
$.ajax({
type: 'post',
url: 'src/khu-pusat/compare/left-side/left-value.php',
data: {
'rowid': leftId
},
success: function(data) {
$('#kt_datatable_nodata').addClass('hidden');
$("#kt_datatable_fetch_display").html(data);
}
});
}).click(function() {
$('#kt_datatable_fetch_display').empty();
});
};
return {
// public functions
init: function() {
displayLeftData();
},
};
}();
jQuery(document).ready(function() {
LeftTable.init();
});
left-value.php
<?php
include 'db_connect.php';
if (isset($_POST['rowid'])) {
$id = $_POST['rowid'];
$query = mysqli_query($config, "SELECT* FROM data_penilaian where id = '$id'");
$no = 1;
while ($row = mysqli_fetch_array($query)) {
?>
<div class="text-right">
<button type="submit" id="approve" class="btn btn-success btn-sm font-weight-bold"><i
class="flaticon2-paperplane"></i>Approve</button>
<a href='#left-modal' class='btn btn-light-success btn-sm font-weight-bold' data-toggle='modal'>Change more data</a>
</div>
<form class="leftForms" method="POST">
<h3 class="card-label">
<input type="hidden" name="id" class="form-control" value="<?= $row['id']; ?>">
<span class="d-block text-dark font-weight-bolder mb-5">
<i class="fa fa-genderless text-jcm mr-2"></i>
<?= $row['name']; ?>
</span>
<span class="d-block text-muted mt-1 font-size-sm ml-6">Proyek : <?= $row['proyek']; ?></span>
</h3>
</form>
<?php
}
}
?>
from the above case how can I save the data in kt_datatable_fetch_display into localStorage, in short, make kt_datatable_fetch_display into localStorage so that the div doesn't disappear when the page is reloaded.

You can use this code.
var displayLeftData = function() {
const content = localStorage.getItem('content');
if(content) {
$("#kt_datatable_fetch_display").html(content);
}
$('#kt_datatable').on('click','tr button', function() {
var leftId = $(this).data('id');
$.ajax({
type: 'post',
url: 'src/khu-pusat/compare/left-side/left-value.php',
data: {
'rowid': leftId
},
success: function(data) {
$('#kt_datatable_nodata').addClass('hidden');
$("#kt_datatable_fetch_display").html(data);
localStorage.setItem('content', data);
}
});
}).click(function() {
$('#kt_datatable_fetch_display').empty();
localStorage.removeItem('content');
});
};

Related

Javascript DataTables warning, Requested unknown parameter 'Id' for row 0

I'm getting the following error when I'm trying to fill a Datatable using ajax :
Also, I can get all datas in controller and i am returning Json from there. There is no any problem in controller. Just I can't fill datatable.
My javascript code in below :
This is my function
function createDatatable(setting) {
var actionsColumn = {
sortable: false,
searchable: false,
class: 'text-center',
render: function (data, type, row, meta) {
return '<a class="btn btn-outline-primary btn-sm" href="/' + setting.controller + '/Edit/' + row[setting.primaryKey] + '" title="Düzenle"><i class="icon-pencil"></i></a> <a class="btn btn-outline-danger btn-sm" href="/' + setting.controller + '/Delete/' + row[setting.primaryKey] + '" title="Sil"><i class="icon-trash"></i></a>';
}
};
if (setting.hasCostumActionsColumn === undefined || setting.hasCostumActionsColumn == false) {
setting.columns.push(actionsColumn);
}
if (setting.defaultSortingColumn === undefined) {
setting.defaultSortingColumn = 0;
}
if (setting.defaultSorting === undefined) {
setting.defaultSorting = "desc";
}
if (setting.queryString === undefined) {
setting.queryString = "";
}
var url = '/' + setting.controller + '/' + setting.action;
if (setting.queryString != undefined && setting.queryString != "") {
url += '?' + setting.queryString;
}
var table = $('#' + setting.tableId).DataTable({
info: false,
dom: '<"toolbar">frtip',
deferRender: true,
fnInitComplete: function () {
$("#table1_paginate").remove();
handlePaging();
$('#next-btn').on('click', function () {
table.page('next').draw('page');
updateCurrentPageInput();
});
$('#previous-btn').on('click', function () {
table.page('previous').draw('page');
updateCurrentPageInput();
});
$("#goto-page").on('click', function () {
var page = parseInt($("#pagination-current-page").val());
if (page < 1) {
page = 1;
} else if (page > table.page.info().pages) {
page = table.page.info().pages;
}
var index = page - 1;
table.page(index).draw('page');
updateCurrentPageInput();
});
$("#pagination-row-count").change(function () {
table.page.len($("#pagination-row-count").val()).draw();
updateCurrentPageInput();
});
},
"drawCallback": function (settings) {
updateCurrentPageInput();
},
responsive: true,
processing: true,
serverSide: true,
orderCellsTop: true,
autoWidth: true,
deferRender: true,
lengthMenu: [[10, 20, 50, 100, -1], [10, 20, 50, 100, "Tümü"]],
ajax: {
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
async: true,
headers: {
"RequestVerificationToken": document.querySelector('[name="__RequestVerificationToken"]').value
},
data: function (data) {
let additionalValues = [];
data.AdditionalValues = additionalValues;
return JSON.stringify(data);
}
},
columns: setting.columns,
columnDefs: setting.columnDefs,
order: [setting.defaultSortingColumn, setting.defaultSorting]
});
$("#filter-table").on('click', function () {
$(".table-filter").each(function (k, item) {
var index = $(item).data('index');
var val = $(item).val();
if (val != "") {
table.column(index + ':visible').search(val);
} else {
table.column(index + ':visible').search('DisableSearch');
}
});
table.draw();
});
$("#clear-filter-table").on('click', function () {
document.getElementById("filter-form").reset();
$(".table-filter").each(function (k, item) {
var index = $(item).data('index');
table.column(index + ':visible').search('');
});
table.draw();
});
$(".table-title").prependTo($("#table1_wrapper"));
function updateCurrentPageInput() {
console.log('table pager');
var currentPage = table.page() + 1;
$("#pagination-current-page").val(currentPage);
if (table.page() === 0) {
$('#previous-btn').attr("disabled", true);
} else {
$('#previous-btn').prop("disabled", false);
}
if (table.page.info().pages === currentPage) {
$('#next-btn').attr("disabled", true);
} else {
$('#next-btn').prop("disabled", false);
}
$("#pagination-current-page").prop('max', table.page.info().pages);
$("#table-info-div").html(`Toplam ${table.page.info().pages} sayfanın ${table.page() + 1}. sayfasındasınız. Toplam ${table.page.info().recordsTotal} kayıt bulunmaktadır.`);
}
function handlePaging() {
$('div.toolbar').html(`
<span id="table-info-div">Toplam2 ${table.page.info().pages} sayfanın ${table.page() + 1}. sayfasındasınız. Toplam ${table.page.info().recordsTotal} kayıt bulunmaktadır.</span>
<div class="input-group">
<button id="previous-btn" class="btn btn-success btn-sm paginate_button previous" style="margin-right:5px">< Önceki</button>
<input type="number" id="pagination-current-page" class="form-control" value="1" min="1" step="1" style="padding:5px; width:50px;margin-right:5px;" />
<button id="goto-page" class="btn btn-info btn-sm" style="margin-right:5px">Git</button>
<button id="next-btn" class="btn btn-success btn-sm paginate_button next" style="margin-right:5px">Sonraki ></button>
<div class="kayitSayisi">
<select id="pagination-row-count" class="form-control">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</div>
</div>`);
$("#pagination-current-page").prop('max', table.page.info().pages);
if (table.page() === 0) {
$('#previous-btn').attr("disabled", true);
} else {
$('#previous-btn').prop("disabled", false);
}
if (table.page.info().pages === 1) {
$('#next-btn').attr("disabled", true);
} else {
$('#next-btn').prop("disabled", false);
}
}
return table;
}
Here, I am calling the function :
createDatatable({
tableId: 'table1',
controller: 'User',
action: 'LoadTable',
columns: [
{
data: "Id",
name: "eq",
visible: true,
searchable: true
},
{
data: "FirstName",
name: "co",
searchable: true
},
{
data: "LastName",
name: "co",
searchable: true
},
{
data: "UserName",
name: "co",
searchable: true
},
{
data: "Email",
name: "co",
searchable: true
},
{
sortable: false,
class: 'text-center',
searchable: false,
render: function (data, type, row, meta) {
return '<a class="btn btn-outline-success btn-sm" href="/User/ChangePassword/' + row["Id"] + '" title="Şifre Değiştir"><i class="icon-lock"></i></a> <a class="btn btn-outline-primary btn-sm" href="/User/Edit/' + row["Id"] + '" title="Düzenle"><i class="icon-pencil"></i></a> <a class="btn btn-outline-danger btn-sm" href="/User/Delete/' + row["Id"] + '" title="Sil"><i class="icon-trash"></i></a>';
}
}
],
primaryKey: "Id",
hasCostumActionsColumn: true
});
Update :
I added html code :
<div class="content">
<div class="card-group-control card-group-control-right">
<div class="card">
<div class="card-header">
<h6 class="card-title">
<a data-toggle="collapse" class="collapsed text-default" href="#filter-collapse" style="display:block">Filtrele</a>
</h6>
</div>
<div id="filter-collapse" class="collapse">
<div class="card-body">
<form id="filter-form">
<div class="form-group row">
<div class="col-md-3">
<label class="col-form-label col-lg-12">Id</label>
<div class="col-lg-12">
<input type="text" class="form-control table-filter" data-index="0" />
</div>
</div>
<div class="col-md-3">
<label class="col-form-label col-lg-12">Adı</label>
<div class="col-lg-12">
<input type="text" class="form-control table-filter" data-index="1" />
</div>
</div>
<div class="col-md-3">
<label class="col-form-label col-lg-12">Soyadı</label>
<div class="col-lg-12">
<input type="text" class="form-control table-filter" data-index="2" />
</div>
</div>
<div class="col-md-3">
<label class="col-form-label col-lg-12">Kullanıcı Adı</label>
<div class="col-lg-12">
<input type="text" class="form-control table-filter" data-index="3" />
</div>
</div>
<div class="col-md-3">
<label class="col-form-label col-lg-12">E-Posta</label>
<div class="col-lg-12">
<input type="text" class="form-control table-filter" data-index="4" />
</div>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<div class="col-lg-12">
Listele
Temizle
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-body">
<div class="table-title">Kullanıcılar</div>
<table id="table1" class="table table-bordered table-hover datatable-ajax datatable-responsive">
<thead>
<tr>
<th >Id</th>
<th data-priority="1">Adı</th>
<th data-priority="2">Soyadı</th>
<th>Kullanıcı Adı</th>
<th>E-posta</th>
<th style="width: 210px;"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>

Image upload with PHP and AJAX not working

In my current project i want to update the users profile image with a AJAX post. In the past i update the image with an normal PHP function. So I used my working function and implement this in my new AJAX post.
If the form is triggered the function will be called, but the new image will not be uploaded or recognized.
So the second if in the function will not be called although there is an image.
In the response of the POST I ever get the 5 and 0.
What am I doing wrong here?
update_user_informations();
function update_user_informations() {
include "../../../includes/db.php";
if(isset($_POST['update_user_informations'])) {
$targetDir = "../../../assets/img/users/";
$allowed_image_extensions = array(
"png","jpg","jpeg"
);
$user_id = $_POST['user_id'];
$user_logo_old = $_POST['user_logo_old'];
if(isset($_FILES['user_logo']) && !empty($_FILES['user_logo']['name'])) {
$fileinfo = #getimagesize($_FILES['user_logo']['tmp_name']);
$width = $fileinfo[0];
$height = $fileinfo[1];
$user_image = $pathinfo($_FILES['user_logo']['name'], PATHINFO_EXTENSION);
if(!in_array($user_image, $allowed_image_extensions)) {
echo 1;
exit;
} else if(($_FILES['user_logo']['size'] > 1048576)) {
echo 2;
exit;
} else if($width > "500" || $height > "500") {
echo 3;
exit;
} else {
unlink("../../../assets/img/users/$user_logo_old");
$user_logo_new = $user_id.$user_username;
echo 4;
}
move_uploaded_file($_FILES['user_logo']['tmp_name'], $targetDir.$user_logo_new.".".$user_image);
$user_logo_path = $user_logo_new.".".$user_image;
} else {
$get_user_logo = $connection->prepare("SELECT user_logo FROM user WHERE user_id = ?");
$get_user_logo->bind_param("s", $user_id);
$get_user_logo->execute();
$result = $get_user_logo->get_result();
$row = $result->fetch_assoc();
$user_logo_path = $row['user_logo'];
$get_user_logo->close();
echo 5;
}
$update_user_informations = $connection->prepare("UPDATE user SET user_logo = ? WHERE user_id = ?");
$update_user_informations->bind_param("ss", $user_logo_path, $user_id);
$update_user_informations->execute();
$update_user_informations->close();
echo 0;
exit;
}
}
"use strict";
var KTAccountSettingsBasicInfo = (function () {
const e = document.getElementById("kt_account_basic_info_form");
return {
init: function () {
(() => {
const o = e.querySelector("#kt_account_basic_info_submit");
o.addEventListener("click", function (t) {
t.preventDefault(),
o.setAttribute("data-kt-indicator", "on"),
(o.disabled = !0),
setTimeout(function () {
o.removeAttribute("data-kt-indicator"),
(o.disabled = !1),
Swal.fire({
text: "Form has been successfully submitted!",
icon: "success",
buttonsStyling: !1,
confirmButtonText: "Ok, got it!",
customClass: { confirmButton: "btn btn-primary" },
}).then(function (t) {
t.isConfirmed;
$.ajax({
url: "../profile/includes/settings/profile-settings-functions.php",
method: "POST",
data: $('#kt_account_basic_info_form').serialize(),
success: function(response) {
if(response == 1) {
Swal.fire({
text: "Wrong image extension!",
icon: "error",
buttonsStyling: !1,
confirmButtonText: "Ok, got it!",
customClass: { confirmButton: "btn btn-primary" },
})
} else if(response == 2) {
Swal.fire({
text: "The image must not be larger than 1MB!",
icon: "error",
buttonsStyling: !1,
confirmButtonText: "Ok, got it!",
customClass: { confirmButton: "btn btn-primary" },
})
} else if(response == 3) {
Swal.fire({
text: "The image must not be larger than 500px x 500px!",
icon: "error",
buttonsStyling: !1,
confirmButtonText: "Ok, got it!",
customClass: { confirmButton: "btn btn-primary" },
})
} else {
location.reload();
}
}
});
});
}, 2e3);
})
})();
},
};
})();
KTUtil.onDOMContentLoaded(function () {
KTAccountSettingsBasicInfo.init();
});
<div class="card mb-5 mb-xl-10" id="kt_account_settings_info" data-kt-scroll-offset="{default: 100, md: 125}">
<div class="card-header border-0 cursor-pointer" role="button" data-bs-toggle="collapse" data-bs-target="#kt_account_basic_info" aria-expanded="true" aria-controls="kt_account_basic_info">
<div class="card-title m-0">
<h3 class="fw-boldest m-0">Basic Info</h3>
</div>
</div>
<div id="kt_account_basic_info" class="collapse show">
<form id="kt_account_basic_info_form" class="form">
<div class="card-body border-top p-9">
<input class='d-none' name='update_user_informations' value='1'>
<input class='d-none' name='user_id' value='<?php echo $user_id ?>'>
<input class='d-none' name='user_logo_old' value='<?php echo $user_logo ?>'>
<div class="row mb-6">
<label class="col-lg-4 col-form-label fw-bold fs-6">Avatar</label>
<div class="col-lg-8">
<div class="image-input image-input-outline" data-kt-image-input="true" style="background-image: url(../assets/img/users/blank.png)">
<div class="image-input-wrapper w-125px h-125px" style="background-image: url(../assets/img/users/<?php echo $user_logo ?>)"></div>
<label class="btn btn-icon btn-circle btn-active-color-primary w-25px h-25px bg-white shadow" data-kt-image-input-action="change" data-bs-toggle="tooltip" title="Change avatar">
<i class="bi bi-pencil-fill fs-7"></i>
<input type="file" name="user_logo" accept=".png, .jpg, .jpeg">
</label>
</div>
<div class="form-text">Allowed file types: png, jpg, jpeg.</div>
</div>
</div>
</div>
<div class="card-footer d-flex justify-content-end py-6 px-9">
<button type="submit" class="btn btn-primary" id="kt_account_basic_info_submit">Save Changes</button>
</div>
</form>
</div>
</div>

how to fix POST http://localhost:8000/cour 500 (Internal Server Error) laravel,ajax and Yajra pakage

How can I solve this problem, I'm working with package yajra but I don't know where I have the problem.
I'm getting a 500 (Internal Server Error)
<?php
namespace App\Http\Controllers;
use App\Cour;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
//use Validator;
class CourController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
if(request()->ajax())
{
return datatables()->of(Cour::latest()->get())
->addColumn('action', function($data){
$button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Edit</button>';
$button .= ' ';
$button .= '<button type="button" name="delete" id="'.$data->id.'" class="delete btn btn-danger btn-sm">Delete</button>';
return $button;
})
->rawColumns(['action'])
->make(true);
}
return view('cour');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$rules = array(
'prof' => 'required',
'module' => 'required',
'chapitre' => 'required',
'titre' => 'required',
'description' => 'required',
'file' => 'required|file|max:5000|mimes:pdf,docx,doc',
);
$error = Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json(['errors' => $error->errors()->all()]);
}
$file = $request->file('file');
$new_name = rand() . '.' . $file->getClientOriginalExtension();
$file->move(public_path('images'), $new_name);
$form_data = array(
'prof' => $request->prof,
'module' => $request->module,
'chapitre' => $request->chapitre,
'titre' => $request->titre,
'description' => $request->description,
'file' => $new_name
);
Cour::create($form_data);
return response()->json(['success' => 'Data Added successfully.']);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
if(request()->ajax())
{
$data = Cour::findOrFail($id);
return response()->json(['data' => $data]);
}
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request)
{
$file_name = $request->hidden_file;
$file = $request->file('file');
if($file != '')
{
$rules = array(
'prof' => 'required',
'module' => 'required',
'chapitre' => 'required',
'titre' => 'required',
'description' => 'required',
'file' => 'required|file|mimes:pdf,docx,doc|max:5000',
);
$error = Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json(['errors' => $error->errors()->all()]);
}
$file_name = rand() . '.' . $file->getClientOriginalExtension();
$file->move(public_path('images'), $file_name);
}
else
{
$rules = array(
'prof' => 'required',
'module' => 'required',
'chapitre' => 'required',
'titre' => 'required',
'description' => 'required',
);
$error = Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json(['errors' => $error->errors()->all()]);
}
}
$form_data = array(
'prof' => $request->prof,
'module' => $request->module,
'chapitre' => $request->chapitre,
'titre' => $request->titre,
'description' => $request->description,
'file' => $file_name
);
Cour::whereId($request->hidden_id)->update($form_data);
return response()->json(['success' => 'Data is successfully updated']);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$data = Cour::findOrFail($id);
$data->delete();
}
public function download($file)
{
return response()->download('storage/images'.$file);
}
}
cour view
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel 5.8 - DataTables Server Side Processing using Ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h3 align="center">Laravel 5.8 Ajax Crud Tutorial - Delete or Remove Data</h3>
<br />
<div align="right">
<button type="button" name="create_record" id="create_record" class="btn btn-success btn-sm">Create Record</button>
</div>
<br />
<div class="table-responsive">
<table class="table table-bordered table-striped" id="user_table">
<thead>
<tr>
<th width="">Id</th>
<th width=""><i class="icon_profile"></i>professeur</th>
<th width="">module</th>
<th width="">chapitre</th>
<th width="">titre</th>
<th width="">description</th>
<th width="30%">Action</th>
</tr>
</thead>
</table>
</div>
<br />
<br />
</div>
</body>
</html>
<div id="formModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add cour</h4>
</div>
<div class="modal-body">
<span id="form_result"></span>
<form method="post" id="sample_form" class="form-horizontal" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label class="col-md-4 text-right">Enseignant:</label>
<div class="col-md-8">
<input type="text" name="prof" class="form-control input-lg" placeholder="le nom du prof" />
</div>
</div>
<div class="form-group">
<label class="col-md-4 text-right">Module:</label>
<div class="col-md-8">
<input type="text" name="module" class="form-control input-lg" placeholder="module"/>
</div>
</div>
<div class="form-group">
<label class="col-md-4 text-right">Chapitre:</label>
<div class="col-md-8">
<input type="text" name="chapitre" class="form-control input-lg" placeholder="chapitre"/>
</div>
</div>
<div class="form-group">
<label class="col-md-4 text-right">Titre:</label>
<div class="col-md-8">
<input type="text" name="titre" class="form-control input-lg" placeholder="titre"/>
</div>
</div>
<div class="form-group">
<label class="col-md-4 text-right">Description:</label>
<div class="col-md-8">
<input type="text" name="description" class="form-control input-lg" placeholder="description"/>
</div>
</div>
<div class="form-group">
<label class="col-md-4 text-right">choisir le fichier</label>
<div class="col-md-8">
<input type="file" name="file" id="file" />
<span id="store_image"></span>
</div>
</div>
<div class="form-group" align="center">
<input type="hidden" name="action" id="action" />
<input type="hidden" name="hidden_id" id="hidden_id" />
<input type="submit" name="action_button" id="action_button" class="btn btn-warning" value="Add" />
</div>
</form>
</div>
</div>
</div>
</div>
<div id="confirmModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Confirmation</h2>
</div>
<div class="modal-body">
<h4 align="center" style="margin:0;">Are you sure you want to remove this data?</h4>
</div>
<div class="modal-footer">
<button type="button" name="ok_button" id="ok_button" class="btn btn-danger">OK</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('#user_table').DataTable({
processing: true,
serverSide: true,
ajax:{
url: "{{ route('cour.index') }}",
},
columns:[
{
data: 'file',
name: 'file',
render: function(data, type, full, meta){
return "<img src={{ URL::to('/') }}/images/" + data + " width='70' class='img-thumbnail' />";
},
orderable: false
},
{
data: 'prof',
name: 'prof'
},
{
data: 'module',
name: 'module'
},
{
data: 'chapitre',
name: 'chapitre'
},
{
data: 'titre',
name: 'titre'
},
{
data: 'description',
name: 'description'
},
{
data: 'action',
name: 'action',
orderable: false
}
]
});
$('#create_record').click(function(){
$('.modal-title').text("Ajouter un coure");
$('#action_button').val("Add");
$('#action').val("Add");
$('#formModal').modal('show');
});
$('#sample_form').on('submit', function(event){
event.preventDefault();
if($('#action').val() == 'Add')
{
$.ajax({
url:"{{ route('cour.store') }}",
method:"POST",
data: new FormData(this),
contentType: false,
cache:false,
processData: false,
dataType:"json",
success:function(data)
{
var html = '';
if(data.errors)
{
html = '<div class="alert alert-danger">';
for(var count = 0; count < data.errors.length; count++)
{
html += '<p>' + data.errors[count] + '</p>';
}
html += '</div>';
}
if(data.success)
{
html = '<div class="alert alert-success">' + data.success + '</div>';
$('#sample_form')[0].reset();
$('#user_table').DataTable().ajax.reload();
}
$('#form_result').html(html);
}
})
}
if($('#action').val() == "Edit")
{
$.ajax({
url:"{{ route('cour.update') }}",
method:"POST",
data:new FormData(this),
contentType: false,
cache: false,
processData: false,
dataType:"json",
success:function(data)
{
var html = '';
if(data.errors)
{
html = '<div class="alert alert-danger">';
for(var count = 0; count < data.errors.length; count++)
{
html += '<p>' + data.errors[count] + '</p>';
}
html += '</div>';
}
if(data.success)
{
html = '<div class="alert alert-success">' + data.success + '</div>';
$('#sample_form')[0].reset();
$('#store_image').html('');
$('#user_table').DataTable().ajax.reload();
}
$('#form_result').html(html);
}
});
}
});
$(document).on('click', '.edit', function(){
var id = $(this).attr('id');
$('#form_result').html('');
$.ajax({
url:"/cour/"+id+"/edit",
dataType:"json",
success:function(html){
$('#prof').val(html.data.prof);
$('#module').val(html.data.module);
$('#chapitre').val(html.data.chapitre);
$('#titre').val(html.data.titre);
$('#description').val(html.data.description);
$('#store_file').html("<iframe src={{ URL::to('/') }}/images/" + html.data.file + " width='70' class='img-thumbnail' ></iframe>");
$('#store_file').append("<input type='hidden' name='hidden_file' value='"+html.data.file+"' />");
$('#hidden_id').val(html.data.id);
$('.modal-title').text("Edit New Record");
$('#action_button').val("Edit");
$('#action').val("Edit");
$('#formModal').modal('show');
}
})
});
var user_id;
$(document).on('click', '.delete', function(){
user_id = $(this).attr('id');
$('#confirmModal').modal('show');
});
$('#ok_button').click(function(){
$.ajax({
url:"cour/destroy/"+user_id,
beforeSend:function(){
$('#ok_button').text('Deleting...');
},
success:function(data)
{
setTimeout(function(){
$('#confirmModal').modal('hide');
$('#user_table').DataTable().ajax.reload();
}, 2000);
}
})
});
});
</script>
routes :
Route::resource('cour', 'CourController');
Route::post('cour/update', 'CourController#update')->name('cour.update');
Route::get('cour/destroy/{id}', 'CourController#destroy');
When you got 500 error?
If you get when your datatables send ajax, you can try to add CSRF to header request of datatable before send.
Additional, you can change your .env APP_DEBUG=true to see more info about your error.
A example when you want to send ajax from this
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
You can see how to add csrf to header datatable request here
"ajax":{
url: url,
type: "GET",
headers: { 'Apitoken': apiToken },
});
You should set your csrf in meta tag in header
<meta name="csrf-token" content="{{ csrf_token() }}">

Show Multiple Value With Ajax

I have 2 db 'srtptr' and 'deskripsisrt' and I want to show them with modal bootstrap
I successfully show from 'srtptr' but I don't know how to show from 'deskripsisrt',..
this my db 'deskripsisrt'
+--------------+------------------+-----------+
| id_des | deskripsi | id_srt |
+--------------+------------------+-----------+
| 1 | Test 4 | 4 |
| 2 | Test 2 | 4 |
+--------------+------------------+-----------+
I want to show multiple values on my modal.
Modal script:
<div class="modal fade" id="myModals" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<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">Add User</h4>
</div>
<div class="modal-body" style="max-height: 600; overflow-y: scroll;">
<div class="alert alert-danger" role="alert" id="removeWarning">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class="sr-only">Error:</span>
Anda yakin ingin menghapus user ini
</div>
<br>
<form class="form-horizontal" id="formUser" method="post" target="blank">
<input type="hidden" class="form-control" id="type" name="type">
<input type="hidden" class="form-control" id="id_srt" name="id_srt">
<input id="desc" value="1" type="hidden" >
<span style="font-weight: bold">Kepada PT</span>
<div class="input-group">
<input type="text" class="form-control" name="tujuan_srt" id="tujuan_srt" value="" title="Tujuan Surat" placeholder="Tujuan Surat" maxlength="25" size="100">
</div>
</br>
<span style="font-weight: bold">Kepada Nama</span>
<div class="input-group">
<input type="text" class="form-control" name="kepada_srt" id="kepada_srt" value="" title="Tujuan Surat" placeholder="Tujuan Surat" maxlength="25" size="100">
</div>
</br>
<span style="font-weight: bold">Tanggal</span>
<div class="input-group">
<input type="text" name="tanggal" class="form-control" id="tanggal" value="<?php echo $fungsi->Tanggal('tgl').' '.$fungsi->Tanggal('blnL').' '.$fungsi->Tanggal('THN'); ?>" title="Tanggal Pembayaran" readonly="readonly" size="100">
</div>
</br>
<div class="col-md-6 konten "></br>
<span style="font-weight: bold">Deskripsi</span>
</div>
<div class="col-md-6 konten " style="Text-align: Right;"></br>
<button type="button" onclick="tambahDesc(); return false;" style="cursor:pointer; font-size:8pt; border-radius:2px; min-width:10px; border:0px; background:#4D4D4D; color:#FFFFFF; font-weight:bold;">Tambah Deskripsi</button>
</div>
<table border="1" style="width:30%" id="test">
<tr><td>deskripsi</td></tr>
**I WANT TO SHOW VALUE FROM DB 'deskripsisrt' HERE!!**
</table>
<div id="divDesc"> </div>
</br></br></br></br>
</form>
</div>
<div class="modal-footer">
<button type="submit" id="btn1" class="btn btn-default" style="align:left">Cetak</button>
<button type="button" onClick="submitUser()" class="btn btn-default" data-dismiss="modal">Submit</button>
<button type="button" onClick="clearModals()" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
AJAX Code:
//Show Modal
function showModals( id_srt )
{
waitingDialog.show();
clearModals();
// For Execute Data (EDIT & DELETE)
if( id_srt )
{
$.ajax({
type: "POST",
url: "crud.php",
dataType: 'json',
data: {id_srt:id_srt,type:"get"},
success: function(res) {
waitingDialog.hide();
setModalData( res );
}
});
}
// FOR ADD Data
else
{
$("#myModals").modal("show");
$("#myModalLabel").html("New User");
$("#type").val("new");
waitingDialog.hide();
}
}
//Show Data On Modal For Edit
function setModalData( data )
{
$("#myModalLabel").html(data.id_srt);
$("#id_srt").val(data.id_srt);
$("#type").val("edit");
$("#tujuan_srt").val(data.tujuan_srt);
$("#kepada_srt").val(data.kepada_srt);
$("#tanggal").val(data.tanggal);
$("#myModals").modal("show");
}
//For Execute EDIT/DELETE/ADD NEW To DB
function submitUser()
{
var formData = $("#formUser").serialize();
waitingDialog.show();
$.ajax({
type: "POST",
url: "crud.php",
dataType: 'json',
data: formData,
success: function(data) {
dTable.ajax.reload(); // Automatic Reload Table Page
waitingDialog.hide();
}
});
}
$('#btn1').click(function()
{
$('#formUser').attr('action','setcetak.php');
$('#formUser').submit();
}
);
//Delete Data
function deleteUser( id_srt )
{
clearModals();
$.ajax({
type: "POST",
url: "crud.php",
dataType: 'json',
data: {id_srt:id_srt,type:"get"},
success: function(data) {
$("#removeWarning").show();
$("#myModalLabel").html("Delete User");
$("#id_srt").val(data.id_srt);
$("#type").val("delete");
$("#tujuan_srt").val(data.tujuan_srt).attr("disabled","true");
$("#kepada_srt").val(data.kepada_srt).attr("disabled","true");
$("#tanggal").val(data.tanggal).attr("disabled","true");
$("#myModals").modal("show");
waitingDialog.hide();
}
});
}
//Clear Modal
function clearModals()
{
$("#removeWarning").hide();
$("#tujuan_srt").val("").removeAttr( "disabled" );
$("#kepada_srt").val("").removeAttr( "disabled" );
$("#tanggal").val("").removeAttr( "disabled" );
}
// ADD Description Field
function tambahDesc() {
var desc = document.getElementById("desc").value;
var stre;
stre="<div id='srow" + desc + "'><div class='col-md-12 konten' style='Text-align: Right;'></br><a href='#' style=\"color:#EC090D; cursor:pointer; text-align: Right;\" onclick='hapusElemen(\"#srow" + desc + "\"); return false;'>hapus</a><div class='input-group'><textarea rows='6' cols='100' type='text' class='desce form-control' name='deskripsi[]' placeholder='deskripsi' size='100'></textarea></br></div></div></div>";
$("#divDesc").append(stre);
desc = (desc-1) + 1;
document.getElementById("desc").value = desc;
}
//Delete Description Field
function hapusElemen(desc) {
$(desc).remove();
}
$(function(id_srt) {
var data_table = "";
$.ajax({
type:"POST",
url: "crud.php",
dataType: "json",
data:{id_srt:id_srt,type:"getdes"},
success: function(data) {
for (var i =0; i<data.length; i++){
data_table +="<tr> <td> "+data[i].deskripsi+"</td></tr>";
}
$('#test').append(data_table);
}
});
});
Controller Code :
<?php
require 'config/action.php';
$fungsi = new Fungsi();
//Connection Database
$con = mysqli_connect("localhost","root","","kw");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
switch ($_POST['type']) {
//Tampilkan Data
case "get":
$SQL = mysqli_query($con, "SELECT * FROM srtptr WHERE id_srt='".$_POST['id_srt']."'");
$return = mysqli_fetch_array($SQL,MYSQLI_ASSOC);
echo json_encode($return);
break;
case "getdes": // NEW CODE This Show a table 'deskripsisrt'
$SQL =mysqli_query($con,"SELECT * FROM deskripsisrt WHERE id_srt = '".$_POST['id_srt']."'");
while ($return = mysqli_fetch_array($SQL,MYSQLI_ASSOC)) {
$rows[] = $return;
}
echo json_encode($rows);
break;
//Tambah Data
case "new":
$SQL = mysqli_query($con,
"INSERT INTO kwitansi SET
kwnum='".$_POST['kwnum']."',
tglkw='".$_POST['tglkw']."',
dari='".$_POST['dari']."',
penerima='".$_POST['penerima']."',
nominal='".$_POST['nominal']."',
pembayaran='".$_POST['pembayaran']."'
");
if($SQL){
echo json_encode("OK");
}
break;
//Edit Data
case "edit":
$SQL = mysqli_query($con,
"UPDATE srtptr SET
tujuan_srt='".$_POST['tujuan_srt']."',
kepada_srt='".$_POST['kepada_srt']."',
tanggal='".$_POST['tanggal']."'
WHERE id_srt='".$_POST['id_srt']."'
");
if($SQL){
echo json_encode("OK");
}
break;
//Hapus Data
case "delete":
$SQL = mysqli_query($con, "DELETE FROM srtptr WHERE id_srt='".$_POST['id_srt']."'");
if($SQL){
echo json_encode("OK");
}
break;
}
?>
I think this needs a loop on ajax but I don't know to make the loop ajax.
Assuming that the json coming from controller is like this
[
{"id_des":45,"deskripsi":"test","id_srt":2},
{"id_des":46,"deskripsi":"test1","id_srt":3},
{"id_des":47,"deskripsi":"test2","id_srt":4},
]
update your function of success like this
success: function(data) {
$.each(data, function() {
$.each(this, function(k, v) {
console.log(k + " " +v);
});
});
}

span class="caret" in button-toggle disappears after website gets load in bootstrap

I am facing an issue regarding caret arrow in bootstrap.
Dropdown arrow is supposed to be as default appears in the box. But apparently it is not showing.
Arrow only comes when my site is loading but it gets disappear after the site gets load.
Here is the HTML of my page. I also included the dropdown js to:
<div class="col-md-6">
<div class="form-group">
<label for="name" class="label-head">Goods Type</label>
<div class="dropdown">
<input type="hidden" id="cargoTypeId" />
<button class="btn btn-default dropdown-toggle sales-button" type="button"
data-toggle="dropdown">
Select Goods Type
<span class="caret arrow-sales"></span>
</button>
<ul class="dropdown-menu sales-dropdown" id="goodsTypeList">
</ul>
</div>
</div>
</div>
<div class="col-md-6 right-float">
<div class="form-group">
<label for="name" class="label-head">Body Type</label>
<div class="dropdown">
<input type="hidden" id="bodyTypeId" />
<button class="btn btn-default dropdown-toggle sales-button body-type-value" type="button"
data-toggle="dropdown">
Select Body Type
<span class="caret arrow-sales"></span>
</button>
<ul class="dropdown-menu sales-dropdown" id="bodyTypeList">
</ul>
</div>
</div>
</div>
Here is Javascript
getGoodsType = function (){
$.ajax({
url: serviceURl + "v1/cargo-types",
type: "GET",
crossDomain: true,
contentType: 'application/json; charset=utf-8',
data: "",
success: function (response) {
if (response.cargo_types != null) {
var list = "";
$.each(response.cargo_types, function(index, val) {
list += "<li name='cargo" +val.id +"' >" +val.cargo_type_name +"</li>"
});
$("#goodsTypeList").append(list);
$("#goodsTypeList li").click(function(){
var id = $(this).attr('name');
id = id.replace("cargo","");
$("#cargoTypeId").val(id);
console.log(id);
$(this).parents(".dropdown").find(".dropdown-toggle").html($(this).text() + '<span class="caret arrow-sales"></span>');
});
}
},
statusCode: {
409: function () {
$("body").unmask("");
$("#account-exists").modal("show");
},
500: function () {
$("body").unmask("");
$("#something-went-wrong").modal("show");
}
},
error: function () {
$("body").unmask("");
}
});
};
getBodyType = function (){
$.ajax({
url: serviceURl + "v1/body-types",
type: "GET",
crossDomain: true,
contentType: 'application/json; charset=utf-8',
data: "",
success: function (response) {
if (response.body_types != null) {
var list = "";
$.each(response.body_types, function(index, val) {
list += "<li name='body" +val.id +"'>" +val.body_type_name +"</li>"
});
$("#bodyTypeList").append(list);
$("#bodyTypeList li").click(function(){
var id = $(this).attr('name');
id = id.replace("body","");
$("#bodyTypeId").val(id);
console.log($(this).parents(".dropdown").find(".dropdown-toggle"));
$(this).parents(".dropdown").find(".dropdown-toggle").html($(this).text() +'<span class="caret arrow-sales"></span>');
});
}
getCompanyDetails();
},
statusCode: {
409: function () {
$("body").unmask("");
$("#account-exists").modal("show");
},
500: function () {
$("body").unmask("");
$("#something-went-wrong").modal("show");
}
},
error: function () {
$("body").unmask("");
}
});
};

Categories

Resources