Image upload with PHP and AJAX not working - javascript

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>

Related

Save ajax post data on div to localStorage

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');
});
};

Loading JS for dynamic modals

i'm currently trying to solve the issue of JS not loading for dynamic modals.
The modals are called by using:
<a href="#" class="btn btn-icon btn-bg-light btn-active-color-primary btn-sm me-1"
id="<?php echo $row['id']; ?>" data-bs-toggle="modal" data-bs-
target="#kt_modal_new_target_<?php echo $sald_id; ?>">
The modal loads up, but all the functions, like SweetAlert2, FormValidation doesn't seem to be working. I've tried using wildcard for the querySelector but that did't seem to help, as the functions would only work on the first modal generated. Is there any way to call the js after every modal creation?
The .js file that contains the functions.
"use strict";
var KTModalNewCard = function () {
var submitButton;
var cancelButton;
var validator;
var form;
var handleForm = function() {
validator = FormValidation.formValidation(
form,
{
fields: {
'sald_nr': {
validators: {
notEmpty: {
message: 'Nurodykite Vardą ir Pavardę!'
}
}
},
'receiver_email': {
validators: {
emailAddress: {
message: 'Klaidingas el. pašto adreso formatas'
}
}
},
'coupon_value': {
validators: {
notEmpty: {
message: 'Nurodykite kupono vertę!'
}
}
},
'coupon_term': {
validators: {
notEmpty: {
message: 'Nurodykite kupono galiojimo terminą!'
}
}
}
},
plugins: {
trigger: new FormValidation.plugins.Trigger(),
bootstrap: new FormValidation.plugins.Bootstrap5({
rowSelector: '.fv-row',
eleInvalidClass: '',
eleValidClass: ''
})
}
}
);
// Action buttons
submitButton.addEventListener('click', function (e) {
// Prevent default button action
e.preventDefault();
// Validate form before submit
if (validator) {
validator.validate().then(function (status) {
console.log('validated!');
if (status == 'Valid') {
// Show loading indication
submitButton.setAttribute('data-kt-indicator', 'on');
// Disable button to avoid multiple click
submitButton.disabled = true;
setTimeout(function() {
// Remove loading indication
submitButton.removeAttribute('data-kt-indicator');
// Enable button
submitButton.disabled = false;
// Show popup confirmation
Swal.fire({
text: "Kuponas sukurtas sėkmingai!",
icon: "success",
buttonsStyling: false,
confirmButtonText: "Gerai!",
customClass: {
confirmButton: "btn btn-primary"
}
}).then(function (result) {
if (result.isConfirmed) {
modal.hide();
}
});
}, 2000);
} else {
// Show error message.
Swal.fire({
text: "Kuriant kuponą rasta klaidų, bandykite dar kartą.",
icon: "error",
buttonsStyling: false,
confirmButtonText: "Gerai!",
customClass: {
confirmButton: "btn btn-primary"
}
});
}
});
}
});
cancelButton.addEventListener('click', function (e) {
e.preventDefault();
Swal.fire({
text: "Ar tikrai norite atšaukti?",
icon: "warning",
showCancelButton: true,
buttonsStyling: false,
confirmButtonText: "Taip, atšaukti",
cancelButtonText: "Grįžti",
customClass: {
confirmButton: "btn btn-primary",
cancelButton: "btn btn-active-light"
}
}).then(function (result) {
if (result.value) {
form.reset(); // Reset form
modal.hide(); // Hide modal
} else if (result.dismiss === 'cancel') {
Swal.fire({
text: "Kupono kūrimas neatšauktas",
icon: "error",
buttonsStyling: false,
confirmButtonText: "Gerai!",
customClass: {
confirmButton: "btn btn-primary",
}
});
}
});
});
}
return {
init: function () {
modalEl = document.querySelector("[id^='kt_modal_new_target_']");
if (!modalEl) {
return;
}
modal = new bootstrap.Modal(modalEl);
form = document.querySelector("[id^='kt_modal_new_target_form_']");
submitButton = document.querySelector("[id^='kt_modal_new_target_submit_']");
cancelButton = document.querySelector("[id^='kt_modal_new_target_cancel_']");
initForm();
handleForm();
}
};
}();
KTUtil.onDOMContentLoaded(function () {
KTModalNewCard.init();
});
The form:
<form id="kt_modal_new_target_form_<?php echo $sald_id; ?>" class="form" name="kt_modal_new_target_form_<?php echo $nr; ?>">
<!--begin::Heading-->
<div class="mb-13 text-center">
<!--begin::Title-->
<h1 class="mb-3">Šaldytuvo Nr. <?php echo $nr; ?> nustatymai</h1>
<!--end::Title-->
<!--begin::Description-->
<div class="text-gray-400 fw-bold fs-5">Jei kyla neaiškumų, papildomą informaciją rasite
čia.</div>
<!--end::Description-->
</div>
<!--end::Heading-->
<!--begin::Input group-->
<div class="fv-row">
<label class="required fs-6 fw-bold mb-2">
Šaldytuvo numeris</label>
<i class="fas fa-exclamation-circle ms-2 fs-7" data-bs-toggle="tooltip" title="Nurodykite tik numerį"></i>
<input type="text" class="form-control form-control-solid" value="<?php echo $nr; ?>" id="sald_nr_input" name="sald_nr" required/>
<input type="hidden" id="sald_nr" name="sald_id" value="<?php echo $sald_id; ?>">
<input type="hidden" id="sald_nr_old" name="sald_nr_old" value="<?php echo $nr; ?>">
<!--end::Input-->
</div>
<br>
<div class="fv-row">
<label class="required fs-6 fw-bold mb-2">
Šaldytuvo zona</label>
<i class="fas fa-exclamation-circle ms-2 fs-7" data-bs-toggle="tooltip" title="Nurodykite zoną"></i>
<input type="text" class="form-control form-control-solid" value="<?php echo $zona; ?>" name="sald_zona" required/>
<!--end::Input-->
</div><br>
<div class="d-flex flex-stack">
<!--begin::Label-->
<div class="me-5">
<label class="fs-6 fw-bold form-label">Ar rodyti šį šaldytuvą sąraše?</label>
<div class="fs-7 fw-bold text-gray-400">Jei šaldytuvas nebus rodomas, nebus galimybės pildyti jo temperatūrinių parodymų.</div>
</div>
<!--end::Label-->
<!--begin::Switch-->
<div class="fv-row">
<label class="form-check form-switch form-check-custom form-check-solid">
<input class="form-check-input" type="checkbox" name="checkbox" value="1" <?php if($sald_status == "1"){ ?>
checked="checked"
<?php } ?>/>
<span class="form-check-label fw-bold text-gray-400">Rodyti</span>
</label>
<!--end::Switch-->
</div>
</div><br>
<script>
</script>
<div class="text-center">
<button type="reset" id="kt_modal_new_target_cancel_<?php echo $sald_id; ?>" class="btn btn-white me-3">Atšaukti</button>
<button type="submit" id="kt_modal_new_target_submit_<?php echo $sald_id; ?>" class="btn btn-primary">
<span class="indicator-label">Išsaugoti</span>
<span class="indicator-progress">Prašome palaukti...
<span class="spinner-border spinner-border-sm align-middle ms-2"></span></span>
</button>
</div>
<!--end::Actions-->
</form>
Any suggestion on how to make the dynamic modals use these functions? Thanks in advance.

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() }}">

javascript functions stop working after writing another function in the same script

Im doing am employee leave management system. The approve and disapprove buttons were working fine in the beginning. But after writing the code to show employee details in the same modal, the approve and disapprove buttons stopped working. Now it gives error. Does anyone have an idea on whats wrong?
controller
//admin approve leave
public function approveLeave() {
$id = $this->input->post('id');
$result = $this->Admin_Model->approve($id);
if(!$result){
// something went wrong
$data = array(
"value" => $id,
"error" => true,
"msg" => "something went wrong"
);
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
return;
}
// approved leave
$data = array(
"value" => $id,
"error" => false,
"msg" => "successfully updated"
);
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}
modal
<!-- Modal -->
<div class="modal fade" id="pendingLeaveRequest" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Leave Request</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="leave_details" >
<p> </p>
</div>
<div class="modal-footer">
<input type="hidden" name="current_leave_id" id="current_leave_id" value="" />
<button type="button" id="declinebtn" class="btn btn-secondary" data-dismiss="modal">Decline</button>
<button type="button" id="approvebtn" class="btn btn-primary">Approve</button>
</div>
</div>
</div>
</div>
javascript
<script>
$(function(){
var BASE_URL = "http://localhost/employeemgt/index.php/";
$('#pendingLeaveRequest').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
var current_leave_id = button.data('id');
var modal = $(this);
modal.find('input[name="current_leave_id"]').val(current_leave_id);
});
//approve button
$('#approvebtn').click(function(){
var id = $('input[name="current_leave_id"]').val();
$.post(BASE_URL + 'admin/AdminDashboardController/approveLeave',
{'id': id},
function(result){
console.log(result);
if(result.error){
alert('try again');
}else{
alert('Leave has been approved!');
}
});
});
//disapprove button
$('#declinebtn').click(function(){
var id = $('input[name="current_leave_id"]').val();
$.post(BASE_URL + 'admin/AdminDashboardController/disapproveLeave',
{'id': id},
function(result){
console.log(result);
if(result.error){
alert('try again');
}else{
alert('Leave has been disapproved!');
}
});
});
});
//show leave details on modal
$('.detailButton').on('click', function(){
var BASE_URL = "http://localhost/employeemgt/index.php/";
var leave_id = $(this).val();
var i;
$.ajax({
type: 'POST',
dataType: "JSON",
data:{leave_id:leave_id},
url: BASE_URL + 'admin/AdminDashboardController/viewRequest',
success:function(data){
console.log(data);
$('#leave_details').html("<p>" + "Name: " + data[0].user_name + "</p>" +
"<p>" + "Leave Type: " + data[0].leave_type + "</p>" +
"<p>" + "Start Date: " + data[0].leave_start + "</p>" +
"<p>" + "End Date: " + data[0].leave_end + "</p>");
$('#pendingLeaveRequest').modal('show');
},
error:function(error){
alert(error);
}});
});
</script>
view
<div id="showleave">
<h4 class="mb-4">Pending Requests</h4>
<?php
foreach ($leave as $row) {
if($row->status != "1")
{
echo '
<ul class="list-unstyled">
<li class="media border-bottom border-top py-3">
<img class="mr-3" src="http://via.placeholder.com/64x64" alt="Generic placeholder image">
<div class="media-body">
<h5 class="mt-0 mb-1">'.$row->user_name.'</h5>
<p class="mb-0 mt-0">'.$row->leave_start.' to '.$row->leave_end.'</p>
<p class="mt-0">'.$row->leave_type.'</p>
<button type="button" class="detailButton" href="<?php echo $id; ?>" data-id="'.$row->id.'" data-name="'.$row->user_name.'" data-toggle="modal" value="'.$row->id.'">View Request</button>
</div>
</li>
</ul>
';
}
}
?>
</div>
Use
$(document).on('click','#declinebtn',function(){}) instead of $('#declinebtn').click(function(){}) .
change your view code like this :
<div id="showleave">
<h4 class="mb-4">Pending Requests</h4>
<?php
foreach ($leave as $row) {
if($row->status != 1)
{
?>
<ul class="list-unstyled">
<li class="media border-bottom border-top py-3">
<img class="mr-3" src="http://via.placeholder.com/64x64" alt="Generic placeholder image">
<div class="media-body">
<h5 class="mt-0 mb-1"><?= $row->user_name ?></h5>
<p class="mb-0 mt-0"> <?= $row->leave_start.' to '.$row->leave_end ?></p>
<p class="mt-0"><?= $row->leave_type ?></p>
<button type="button" class="detailButton" href="<?php echo $row->id; ?>" data-id="<?= $row->id ?>" data-name="<?= $row->user_name ?>" data-toggle="modal" value="<?= $row->id ?>">View Request</button>
</div>
</li>
</ul>
<?php
}
}
?>
By this I think your problem will be solve
Try this.
$(document).on("click", "#approvebtn", function(event){
// your code here
});
And you can also try triggering your btn from browser console to check if it works.

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);
});
});
}

Categories

Resources