Show Multiple Value With Ajax - javascript

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

Related

Load DataTable data to a Edit Modal

I am trying to create an edit function for my data table. The data table is created using Yajra Data tables. Everything working fine unless when I try to load existing data into the edit modal it fails. No error is showing but the modal does not launch. I have only included a little portion of my code here for easy reference.
Modal:
<!-- Update Status Model Box -->
<div id="updateStatusModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content bg-default">
<div class="modal-body">
<form class="form-horizontal" id="updateStatus">
#csrf
#method('PUT')
<div class="row">
<div class="col">
<div class="form-group text-center">
<h6 class="font-weight-bold">Stage 1</h6>
<label for="stage_1" class="switch">
<input type="checkbox" class="form-control" id="stage_1">
<div class="slider round"></div>
</label>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<div class="col-md">
<label for="firstname">Coding</label>
<input type="text" class="form-control" id="first_name" value="" placeholder="Enter Completed Page Count">
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer justify-content-between">
<button type="button" name="update_btn" id="update_btn" class="btn btn-outline-warning">Update</button>
</div>
</div>
</div>
</div>
jquery funtion:
// Edit action
$(document).on('click', '.updateStatus', function(){
$tr = $(this).closest('tr');
var data = $tr.clidren("td").map(function(){
return $(this).text();
}).get();
console.log(data);
$('#id').val(data[0]);
$('#job_id').val(data[2]);
$('#stage_1').val(data[3]);
$('#conversion').val(data[4]);
$('#updateStatusModal').modal('show');
});
I tried this method I found but this is not working. Can anyone provide me any pointers here?
I've just didn't seen your front scripts (also back-end codes), but instead I can share my implementation for that you need. It works perfectly like showed in this (screenshot).
Here I'll put front and back codes. There is functionality for editing existsing Datatable record, also record deletion.
FRONT
<!--HERE ATTACH NECESSARY STYLES-->
<!--VIEW end-->
<link rel="stylesheet" type="text/css" href="{{ asset('css/admin/datatables.min.css') }}"/>
<table id="yajra_datatable" class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Options</th>
</tr>
</thead>
</table>
<div class="modal modal-danger fade" id="modal_delete">
<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">Delete Language</h4>
</div>
<div class="modal-body">
<p>Are You sure You want to delete this Language?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Cancel</button>
<button id="delete_action" type="button" class="btn btn-outline">Submit</button>
</div>
</div>
</div>
</div>
<div class="modal modal-warning fade" id="modal_edit">
<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">Edit Language</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="language_name">Language Name</label>
<input name="language_name" id="language_name" type="text" value="" class="form-control" placeholder="Language Name">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Cancel</button>
<button id="edit_action" type="button" class="btn btn-outline">Submit</button>
</div>
</div>
</div>
</div>
<input type="hidden" id="item_id" value="0" />
<!--VIEW end-->
<!--HERE ATTACH NECESSARY SCRIPTS-->
<!--SCRIPTS start-->
<script src="{{ asset('js/admin/jquery.dataTables.min.js') }}"></script>
<script type="text/javascript">
var YajraDataTable;
function delete_action(item_id){
$('#item_id').val(item_id);
}
function edit_action(this_el, item_id){
$('#item_id').val(item_id);
var tr_el = this_el.closest('tr');
var row = YajraDataTable.row(tr_el);
var row_data = row.data();
$('#language_name').val(row_data.name);
}
function initDataTable() {
YajraDataTable = $('#yajra_datatable').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('admin.book_languages.ajax') }}",
"columns":[
{
"data": "name",
"name": "name",
},
{
"data": "",
"name": ""
},
],
"autoWidth": false,
'columnDefs': [
{
'targets': -1,
'defaultContent': '-',
'searchable': false,
'orderable': false,
'width': '10%',
'className': 'dt-body-center',
'render': function (data, type, full_row, meta){
return '<div style="display:block">' +
'<button onclick="delete_action(' + full_row.id + ')" type="button" class="delete_action btn btn-danger btn-xs" data-toggle="modal" data-target="#modal_delete" style="margin:3px"><i class="fa fa-remove"></i> Delete</button>' +
'<button onclick="edit_action(this, ' + full_row.id + ')" type="button" class="edit_action btn btn-warning btn-xs" data-toggle="modal" data-target="#modal_edit" style="margin:3px"><i class="fa fa-edit"></i> Edit</button>' +
'</div>';
}
}
],
});
return YajraDataTable;
}
$(document).ready(function() {
var YajraDataTable = initDataTable();
$('#delete_action').on('click', function (e) {
e.preventDefault();
$.ajax({
url: "{{ route('admin.book_languages.delete') }}",
data: {
'item_id': $('#item_id').val(),
'_token': "{{ csrf_token() }}"
},
type: "POST",
success: function (data) {
$('#modal_delete').modal('hide');
YajraDataTable.ajax.reload(null, false);
console.log(data.message);
}
})
});
$('#edit_action').on('click', function (e) {
e.preventDefault();
$.ajax({
url: "{{ route('admin.book_languages.edit') }}",
data: {
'item_id': $('#item_id').val(),
'language_name': $('#language_name').val(),
'_token': "{{ csrf_token() }}"
},
type: "POST",
success: function (response) {
$('#modal_edit').modal('hide');
YajraDataTable.ajax.reload(null, false);
console.log(data.message);
}
})
});
$('#modal_delete').on('hidden.bs.modal', function () {
$('#item_id').val(0);
});
$('#modal_edit').on('hidden.bs.modal', function () {
$('#item_id').val(0);
$('#language_name').val("");
});
});
</script>
<!--SCRIPTS end-->
BACK
public function index() {
return view('admin.book-languages.index');
}
public function ajax() {
$items = BookLanguage::latest('id');
return DataTables::of($items)->make(true);
}
public function delete(Request $request) {
$item_id = $request->get('item_id');
$item = BookLanguage::find($item_id);
if(empty($item)) {
return response()->json([
'success' => false,
'message' => 'Item not found!',
], 200); // 404
} else {
$item->delete();
return response()->json([
'success' => true,
'message' => 'Item successfully deleted.',
], 200);
}
}
public function update(Request $request) {
$item_id = $request->get('item_id');
$item = BookLanguage::find($item_id);
if(empty($item)) {
return response()->json([
'success' => false,
'message' => 'Item not found!',
], 404);
} else {
$item->name = $request->get('language_name');
$item->save();
return response()->json([
'success' => true,
'message' => 'Item successfully updated.',
], 200);
}
}
ROUTES
// ...
// book_languages
Route::group(['prefix' => 'book-languages', 'as' => 'admin.book_languages.',], function () {
Route::get('all', 'BookLanguageController#index')->name('index');
Route::get('ajax', 'BookLanguageController#ajax')->name('ajax');
Route::post('update', 'BookLanguageController#update')->name('edit');
Route::post('delete', 'BookLanguageController#delete')->name('delete');
});
// ...
I think this can help you and others to build wanted functionality. Here this could be also with more hint-comments, but as it not small, I can answer later via post comments.
i am building a Laravel ERP-like web application and am implementing a CRUD function modal like you. I have made mine a server-side processing application with resource APIs in Laravel. Well, please be reminded that i have cut the #extends(layout.app) & #section('stylesheet') parts to go right into the answer. You should extend them in your own application to make everything work.
View.blade script
<script>
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('#customertable').DataTable({
processing: true,
serverSide: true,
dom: 'B<"top"frli>tp',
ajax: {
url: "{{ route('customer.index') }}", //Accessing server for data
columns: [
{data: 'id'}, //data refers to DB column name
{data: 'name'},
{data: 'chiname'},
{data: 'type'},
{data: 'action'}, //this is an addColumn item from Controller
]
});
$('#createNewcustomer').click(function () {
$('#saveBtn').val("create customer");
$('#customerid').val('');
$('#customerForm').trigger("reset");
$('#modelHeading').html("Create New Customer");
$('#customermodal').modal('show');
});
//Control the modal behavior when clicking the edit button.
$('body').on('click', '.editcustomer', function () {
var customerid = $(this).data('id');
$.get("{{ route('customer.index') }}" +'/' + customerid +'/edit', function (data) {
$('#modelHeading').html("Edit Customer");
$('#saveBtn').val("edit-user");
$('#customermodal').modal('show');
$('#customerid').val(data.id);
$('#name').val(data.name);
$('#chiname').val(data.chiname);
$('#type').val(data.type);
})
});
//Create a brand-new record
$('#createNewcustomer').click(function () {
$('#saveBtn').val("create customer");
$('#customerid').val('');
$('#customerForm').trigger("reset");
$('#modelHeading').html("Create New Customer");
$('#customermodal').modal('show');
});
//Update
$('body').on('click', '.editcustomer', function () {
var customerid = $(this).data('id');
$.get("{{ route('customer.index') }}" +'/' + customerid +'/edit', function (data) {
$('#modelHeading').html("Edit Customer");
$('#saveBtn').val("edit-user");
$('#customermodal').modal('show');
$('#customerid').val(data.id);
$('#name').val(data.name);
$('#chiname').val(data.chiname);
$('#type').val(data.type);
})
});
//Save
$('#saveBtn').click(function (e) {
e.preventDefault();
$(this).html('Sending..');
$.ajax({
data: $('#customerForm').serialize(),
url: "{{ route('customer.store') }}",
type: "POST",
dataType: 'json',
success: function (data) {
$('#customerForm').trigger("reset");
$('#customermodal').modal('hide');
table.draw();
},
error: function (data) {
console.log('Error:', data);
$('#saveBtn').html('Error');}
});
});
//Delete
$('body').on('click', '.deletecustomer', function () {
var id = $(this).data("id");
confirm("Are You sure?");
$.ajax({
type: "DELETE",
url: "{{ route('customer.store') }}"+'/'+id,
success: function (data) {
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
</script>
View.blade html-table & modal part
#section('content')
<div class="container">
<div class="card-header border-left"><h3><strong> Customer overview</strong></h3></div>
<br>
<div class="row">
<div class="col-md text-right">
<button type="button" class="btn btn-success" data-toggle="modal" href="javascript:void(0)" id="createNewcustomer">Create Record</button>
</div>
</div>
{{-- Modal --}}
<div id="customermodal" class="modal fade" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modelHeading"></h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times</span></button></div>
<div class="modal-body">
<form id="customerForm" name="customerForm" class="form-horizontal">
<input type="hidden" name="customerid" id="customerid">
<div class="form-group">
<label for="name" class="col-sm-6 control-label">Customer Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-6 control-label">Customer Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="chiname" name="chiname" placeholder="Customer Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-6 control-label">Contract type</label>
<div class="col-sm-12">
<select name="type" id="type" class="form-control">
<option value="" disabled>Type</option>
<option value="Government">Government Contract</option>
<option value="Private">Private Contract</option>
</select>
</div></div>
<br>
<div class="col-sm text-right">
<button type="submit" class="btn btn-outline-secondary" id="saveBtn" value="create">Save changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
{{-- Table --}}
<br>
<div class="row">
<br/>
<br/>
<div class="form-group col-md-12 align-content-center">
<table class="table-fluid center-block" id="customertable">
<thead>
<tr>
<th>id</th>
<th>ChiName</th>
<th>Name</th>
<th>Type</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
#endsection
CustomerController
public function index(Request $request)
{
$customers = Customer::all();
}
return Datatables::of($customers)
->addColumn('action', function($customer){
$btn = 'Edit';
$btn = $btn.' Delete';
return $btn;})
->rawColumns(['action'])
->make(true);
}
return view('customer.Customer'); //my view blade is named Customer under customer dir. put your blade destination here.
}
public function store(Request $request)
{
Customer::updateOrCreate(['id' => $request->customerid],
['name' => $request->name, 'chiname' => $request->chiname,'type' =>$request->type]);
return response()->json(['success'=>'Product saved successfully.']);
}
public function edit($id)
{
$customer = Customer::findorfail($id);
return response()->json($customer);
}
public function destroy($id)
{
Customer::findorfail($id)->delete();
return response()->json(['success'=>'Product deleted successfully.']);
}
Model (pick either A.) $guarded = [] OR B.) $fillable = ['fields','fields'] as you like)
class Customer extends Model
{
protected $fillable = ['name','chiname','type'];
}
web.api (route setting)
Route::resource('customer', 'CustomerController')->middleware('auth');
Migration / DB schema structure
class CreateCustomersTable extends Migration
{
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('chiname');
$table->string('type');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('customers');
}
I have not included any protection in it like gate, auth or so. But basically this is the skeleton of doing CRUD with dataTable in Laravel framework with both JS, Ajax, Jquery, PHP all in one. Kindly be reminded that the queries for such CRUD actions are directly linked to the Database server. If you want to show data processed by the DataTable, use your own jquery function to fetch and show them on the modal. My answer is not the best but i hope it helps you >:)
(I could not post a picture to show you here as i dont have enough reputation lol. gg)

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.

what to retrieve image from database using json ajax function in codeigniter

This is my first time of trying to retrieve image using ajax/json format, all other variable are displaying except the image because i dont know how integrate the syntax in ajax,
And when i open the inspect element on the browser the name of the image is showing and it saving into the image folder as well correctly
what i just need from u guys is help me display the image inside the form without function
Thanks in advance
This is my ajax function
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('person/ajax_edit/')?>/" + firstname,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="id"]').val(data.id);
$('[name="firstName"]').val(data.firstname);
$('[name="lastName"]').val(data.lastname);
$('[name="gender"]').val(data.gender);
$('[name="address"]').val(data.address);
$('[name="gender"]').val(data.gender);
$('[name="telephone"]').val(data.telephone);
$('[name="level"]').val(data.level);
$('name="image"').val(data.image)
$('[name="religion"]').val(data.religion);
$('[name="entrance"]').val(data.entrance);
$('[name="graduate"]').val(data.graduate);
$('[name="parents"]').val(data.parents);
$('[name="dob"]').datepicker('update',data.dob);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Person'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
This is controller
public function ajax_edit($firstname)
{
$data = $this->person->get_by_id($firstname);
$data->dob = ($data->dob == '0000-00-00') ? '' : $data->dob; // if 0000-00-00 set tu empty for datepicker compatibility
echo json_encode($data);
}
This is my model
public function get_by_id($firstname)
{
/*
$this->db->from($this->table);
$this->db->where('id',$id);
$query = $this->db->get();
return $query->row();
*/
$this->db->select("e.*,edu.*");
$this->db->from("student_details e");
$this->db->join("images edu", "edu.firstname = e.firstname", 'left');
$this->db->where('e.firstname', $firstname);
$result = $this->db->get();
return $result->row();
}
This is my view
<div class="form-group">
<label class="control-label col-md-3">Religion</label>
<div class="col-md-9">
<select name="religion" class="form-control">
<option value="">--Select Religion--</option>
<option value="Christain">Christain</option>
<option value="Muslim">Muslim</option>
</select>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-4">Image</label>
<div class="">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="fileupload-new thumbnail" style="width: 200px; height: 150px;"><img src="assets/img/demoUpload.jpg" alt="" /></div>
<div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;"></div>
<div align="center">
<span class="btn btn-file btn-primary"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" name="userfile" ></span>
Remove
<span class="help-block"></span>
</div>
</div>
</div>
</div>
public function DISPLAY() {
$abc = "";
$data = $this->Model1->display('users');
$abc .= "<table class='table table-condensed'><th>ID</th><th>Image</th><th>Name</th>
<th>Email</th><th>Mobile</th><th>Action</th>";
for ($q=0; $q<count($data); $q++){
$abc .= "<tr><td>".$data[$q]['ID']."</td><td>
**<img src='".base_url('uploads/USERS/'.$data[$q]['IMAGE'].'')."'".$data[$q]['IMAGE']." height='50' width='60'></td>**
<td>".$data[$q]['FNAME']." ".$data[$q]['LNAME']."</td>
<td>".$data[$q]['EMAIL']."</td>
<td>".$data[$q]['MOBILE']."</td>
<td><button id='EDIT' class= 'btn btn-primary fa fa-EDIT EDIT' value='".$data[$q]['ID']."' data-toggle='modal' data-target='#myModal'></button></td>
<td><button class='btn btn-danger fa fa-trash DELETE ' value='".$data[$q]['ID']."'data-toggle='modal' data-target='#myModal'></button></td>
</tr></table>";}
print_r($abc);
}}
$.ajax({
url:'<?php echo base_url('index.php/Adminc/DISPLAY/')?>',
success:function(display){
$(".table-condensed").html(display);
},
});

how to update my dynamic web content without reloading the whole page using ajax, jquery, javascript

I have a dynamic table, which contains some userInfo using get method ("/api/dashboard/v1").I have a modal, onSubmit,it adds userInfo to the table using post method ("/api/adduserInfo/v1").
I used window.location.replace("http://localhost:3000/") to reload the page but want "update the table content without reloading the page".
I am not getting any proper solution to solve these problem.please help me someone to fix these problem.My code is in Below:
/index.html
<table class="table-bordered mytable">
<thead class="table-head">
<tr>
<th>Name</th>
<th>Email</th>
<th>Status</th>
<th>Address</th>
<th>Action</th>
</tr>
</thead>
<tbody class="table-body mytabBody">
</tbody>
</table>
<div class="col-md-12 text-right">
<button type="button" data-toggle="modal" data-target="#myModal">Update User Information</button>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Enter User Information</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" class="form-control" id="user_name" placeholder="User name">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email_id" placeholder="Enter email">
</div>
<div class="form-group">
<input type="text" class="form-control" id="address" placeholder="Enter Address">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" id="myFormSubmit">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
/modal.js
/* these function is for save new userInfo to the table */
$(function() {
$('#myFormSubmit').click(function (e) {
e.preventDefault();
var username = $("#user_name").val();
var email = $("#email_id").val();
var address = $("#address").val()
$.ajax({
url: "/api/adduserInfo/v1",
data: {
user_name: username,
email: email,
address: address
},
type: 'post',
dataType: 'html',
success: function(data) {
},
error: function(xhr, status) {
alert("Sorry, there was a problem!");
},
});
window.location.replace("http://localhost:3000/"); //not update only the table content without reloading the page. I want only update the table content not reload the page.
})
});
/table.js
/* fetch table content from the DB */
$(function(){
$.get("/api/menu/v1", function(response) {
//console.log(response);
var html = "";
for(var i = 0; i< response.length ; i++){
html += "<li><a href =''>"+response[i].name+"</a></li>"
}
$('.sidebar-nav').html(html);
});
$.get("/api/dashboard/v1", function (response) {
//console.log(response);
var myhtmlsec= "";
for(var i=0; i<response.data.length; i++) {
myhtmlsec += "<tr class='myTable'>";
myhtmlsec +="<td id='tabUser'>"+response.data[i].user_name+"</td>";
myhtmlsec +="<td id='tabEmail'>"+response.data[i].email+"</td>";
myhtmlsec +="<td id='tabStatus'> </td>";
myhtmlsec +="<td id='tabAddress'>"+response.data[i].address+"</td>";
myhtmlsec +="<td>\
<a href='#' onclick='myEdit(this);return false;' class='table-edit img-size'>\
<img src='image/Edit.png'>\
</img>\
</a>\
<a href='#' onclick='myDelete(this);return false;' class='table-delete img-size'>\
<img src='image/Delete.png'>\
</img>\
</a>\
</td>";
myhtmlsec +="<td class='hide' id='tabId'>"+response.data[i]._id+"</td>";
myhtmlsec +="</tr>"
}
$('.table-body').append(myhtmlsec);
});
});
I tried most all ajax,jquery,javascript method but still Not Updating The Table Without Reload the whole page, on submitting modal also not closing
You can append the result of your ajax in your table just like this
$(function() {
$('#myFormSubmit').click(function (e) {
e.preventDefault();
var username = $("#user_name").val();
var email = $("#email_id").val();
var address = $("#address").val()
$.ajax({
url: "/api/adduserInfo/v1",
data: {
user_name: username,
email: email,
address: address
},
type: 'post',
dataType: 'json',
success: function(data) {
//append the data here just like you do in your other ajax request
var myhtmlsec= "";
for(var i=0; i<data.length; i++) {
myhtmlsec += "<tr class='myTable'>";
myhtmlsec +="<td id='tabUser'>"+data[i].user_name+"</td>";
myhtmlsec +="<td id='tabEmail'>"+data[i].email+"</td>";
myhtmlsec +="<td id='tabStatus'> </td>";
myhtmlsec +="<td id='tabAddress'>"+data[i].address+"</td>";
myhtmlsec +="</tr>";
//and so on...
}
$('.table-body').append(myhtmlsec);
alert("User Information Added Successfully");
},
error: function(xhr, status) {
alert("Sorry, there was a problem!");
},
});
//window.location.replace("http://localhost:3000/"); remove this
})
});

Bootstrap Modal shows up on one page but not the other?

I am trying to code a website using Bootstrap. I already have it implemented on one page using a modal (here) and the other page doesn't seem to show the modal (here) on that page, there is a button that can edit the ban details but when I click the edit button, it does nothing.
Also, I am using jQuery for form submissions so that I can redirect to the returned ID, however, I am stuck on how my function can return the ID because using
get_mysql()->fetch_assoc($result)["id"]
causes a 500 internal server error.
Codes can be found below.
ban.php
<div class="modal fade" id="modal" tabindex="-1" role="dialog">
<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">Edit Ban</h4>
</div>
<form id="form">
<div class="modal-body">
<div class="form-group">
<input type="text" value="<?php echo $ban["uuid"] ?>" id="uuid" name="uuid" placeholder="UUID" class="form-control"/>
</div>
<div class="form-group">
<input type="text" value="<?php echo $ban["reason"] ?>" id="reason" name="reason" placeholder="Reason" class="form-control"/>
</div>
</div>
<input type="hidden" id="id" name="id" value="<?php echo $ban["id"] ?>" />
<div class="modal-footer">
<input type="submit" class="btn btn-primary"/>
</div>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
var uuid = $("#uuid").val();
var reason = $("#reason").val();
$.post("add.php", { id: id, uuid: uuid, reason: reason, key: "<?php echo get_key() ?>" }, function(data) {
location.href = "ban.php?id=<?php echo data ?>";
});
});
});
</script>
index.php
<div class="modal fade" id="modal" tabindex="-1" role="dialog">
<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">Add Ban</h4>
</div>
<form id="form">
<div class="modal-body">
<div class="form-group">
<input type="text" value="<?php echo $ban["uuid"] ?>" id="uuid" name="uuid" placeholder="UUID" class="form-control"/>
</div>
<div class="form-group">
<input type="text" value="<?php echo $ban["reason"] ?>" id="reason" name="reason" placeholder="Reason" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary"/>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
var uuid = $("#uuid").val();
var reason = $("#reason").val();
$.post("functions/add.php", { uuid: uuid, reason: reason, key: "<?php echo get_key() ?>" }, function(data) {
location.href = "functions/ban.php?id=<?php echo data ?>";
});
});
});
</script>
api.php
<?php
define("key", "redacted");
function get_mysql() {
$mysql = new mysqli("localhost", "redacted", "redacted", "redacted");
if($mysql->connect_error) {
die($mysql->connect_error);
}
return $mysql;
}
function add($uuid, $reason) {
$date = gmdate("Y-m-d H:i:s");
get_mysql()->query("insert into bans (uuid, date, reason) values ('$uuid', '$date', '$reason')");
$result = get_mysql()->query("select id from bans where uuid = '$uuid' and date = '$date' and reason = '$reason'");
get_mysql()->fetch_array($result);
return $result["id"];
}
function update($id, $uuid, $reason) {
get_mysql()->query("update bans set uuid = '$uuid', reason = '$reason' where id = $id");
}
function remove($uuid) {
get_mysql()->query("delete from bans where uuid = '$uuid'");
}
function remove_by_id($id) {
get_mysql()->query("delete from bans where id = $id");
}
function get($uuid) {
return get_mysql()->query("select * from bans where uuid = '$uuid'")->fetch_assoc();
}
function get_by_id($id) {
return get_mysql()->query("select * from bans where id = $id")->fetch_assoc();
}
function get_bans() {
return get_mysql()->query("select * from bans");
}
function login($username, $password) {
$password = hash("sha256", $password);
return get_mysql()->query("select count(*) from users where username = '$username' and password = '$password'")->num_rows > 0;
}
function register($username, $password) {
$password = hash("sha256", $password);
get_mysql()->query("insert into `users` (`username`, `password`) values ('$username', '$password'");
}
function get_key() {
return key;
}
?>
I've found the answer thanks to #stain88. I didn't provide the correct link to bootstrap.min.js (facepalm)
Thanks again #stain88.

Categories

Resources