I have a function in a controller that will return an array that contains data from dataBase, that data will be sent to my success function as a json file ,
i want to display those informations in a div in my modal, and i can't do that so here is my controller function :
public function list_salle($id)
{
$data= $this->salle_model->get_all_salle($id);
$this->output->set_output(json_encode($data));
}
and here is my js function and its ajax :
function consulter_salle(id)
{
$.ajax({
url : "<?php echo site_url('index.php/batiment/list_salle')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
var table_header = "<table class='table table-striped table-bordered'><thead><tr><td>head_x</td><td>head_y</td></tr></thead><tbody>";
var table_footer = "</tbody></table>";
var html ="";
for (row in data)
{
html += "<tr><td>"+data.id +"</td><td>"+data.libelle+"</td></tr>";
}
var all = table_header +html+ table_footer;
// show bootstrap modal when complete loaded
$('.modal-title').text('Test');
$('#salle_list').html(all);
$('#modal_list').modal('show');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error displaying data');
}
});
}
and here is my modal :
<div class="modal fade" id="modal_list" 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>
<h3 class="modal-title">Liste des salles</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<div class="form-body">
<div id="salle_list"></div>
</div>
</form>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
</div>
So the data is sent correctly as a json file but i can't display it and i think the problem in the loop and the .html function , please help
thank you !
Your for loop in the ajax looks like it should be a foreach, but even then it's wrong. You're iterating over a json object, look at this question if you want some alternatives on how to do that: How do I iterate over a JSON structure?. One answer there gives a loop like this:
$(jQuery.parseJSON(JSON.stringify(data))).each(function() {
html += "<tr><td>"+this.id +"</td><td>"+this.libelle+"</td></tr>";
}
I found a solution :
success: function(data)
{
var table_header = "<table class='table table-striped table-bordered'><thead><tr><td>Identifiant</td><td>Libelle</td></tr></thead><tbody>";
var table_footer = "</tbody></table>";
var html ="";
data.forEach(function(element) {
html += "<tr><td>"+element.id +"</td><td>"+element.libelle+"</td></tr>";
});
var all = table_header +html+ table_footer;
$('.modal-title').text('Liste des salles');
$('#salle_list').html(all);
$('#modal_list').modal('show');
}
Related
hello guys i have a problem with my ajax data json, i have a project about scan a barcode with a webcam but it just views the code of the barcode, the data in the database not call in my ajax, this is the code of blade, i'm using a modal
this is the modal
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="scanModalLabel">Scan Barcode</h5>
<button type="button" class="close close-btn" data-dismiss="myModal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<dl class="row">
<dt class="col-sm-4"><h4>Kode Barang</h4></dt>
<dd class="col-sm-8" id="kode_barang"></dd>
</dl> <hr>
<table class="table align-items-center tabel-detail" >
<thead class="thead-light">
<tr>
<th>Nama Barang</th>
<th>Harga Jual</th>
<th>Stok</th>
<th>Insert</th>
</tr>
</thead>
<tbody class="list">
</tbody>
</table>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
this is the jquery code
var args = {
autoBrightnessValue: 100,
resultFunction: function(res) {
[].forEach.call(scannerLaser, function(el) {
$(el).fadeOut(300, function() {
$(el).fadeIn(300);
});
});
scannedImg.attr("src", res.imgData);
scannedQR.text(res.format + ": " + res.code);
console.log(res.code);
document.getElementsByName('qrcode')[0].value = res.code;
var kode= res.code;
$('#kode_barang').text(': '+kode);
$.ajax({
url:"{{ route('daftar_produk.scan') }}",
method:'GET',
data:{kode:kode},
dataType:'json',
success:function(data)
{
$('.list').html(data.table_data)
}
});
$('#myModal').modal('show');
},
this is the controller
public function cekScan(Request $req)
{
$id = $req->get('kode');
$output='';
$produk = Produk::findOrFail($id)
->where('kode_barang', '=', $id)
->select('produks.*')
->first();
$no = 0;
$data = array();
foreach ($produk as $list) {
$no ++;
$output .= '<tr><td>'.$no.'</td><td>'.$list->nama_barang.'</td><td>'."Rp.".format_uang($list->harga_jual).'</td><td>'.$list->stok.'</td><td><a type="button" data-stok=(('.$list->stok.')) data-id=(('.$list->id.')) data-nama=(('.$list->nama_barang.')) data-kode=(('.$list->kode_barang.')) data-harga=(('.$list->harga_jual.')) class="btn btn-primary btn-pilih" role="button">Insert</a></td></tr>';
}
$data = array(
'table_data' => $output
);
return json_encode($data);
}
this is the route
Route::get('transaksi/scan', '\App\Http\Controllers\ProdukController#cekScan')->name('daftar_produk.scan');
what should i do the error said "jquery.min.js:2 GET http://localhost:8080/rezkastore1/%7B%7B%20route('daftar_produk.scan')%20%7D%7D?kode=2135758676 404 (Not Found)"
Seems like problem with URL.
You can't access the route in JS file.
Make a global variable in blade for ajaxURL then use in JavaScript.
<script>
var ajaxURL = '{{ route('daftar_produk.scan') }}';
</script>
<script src="xyz.js"></script>
I have no idea wether you write your Javascript section, in Laravel Blade View or in separate JS file. If you write it within Laravel Blade Template, you may use
$.ajax({
url:"{{ route('daftar_produk.scan') }}",
but I recommend you to write complete URL within your AJAX call. Make your AJAX call like this :
$.ajax({
url:"/transaksi/scan",
method:'GET',
data:{kode:kode},
dataType:'json',
success:function(data) {
$('.list').html(data.table_data)
}
});
Instead of using findOrFail(), you can use find() or regular where() with error handler, because findOrFail() will returns 404 not found if it can't find any records, here is the cekScan function
public function cekScan(Request $req)
{
$id = $req->get('kode');
$output='';
$produk = Produk::where('kode_barang', '=', $id)->first();
if (!$produk) {
return json_encode(['table_data' => 'Barang Tidak Ditemukan']);
}
$no = 0;
$data = array();
foreach ($produk as $list) {
$no ++;
$output .= '<tr><td>'.$no.'</td><td>'.$list->nama_barang.'</td><td>'."Rp.".format_uang($list->harga_jual).'</td><td>'.$list->stok.'</td><td><a type="button" data-stok=(('.$list->stok.')) data-id=(('.$list->id.')) data-nama=(('.$list->nama_barang.')) data-kode=(('.$list->kode_barang.')) data-harga=(('.$list->harga_jual.')) class="btn btn-primary btn-pilih" role="button">Insert</a></td></tr>';
}
$data = array(
'table_data' => $output
);
return json_encode($data);
}
Maturnuwun
I've been using CodeIgniter for a little while, and I'm trying to get a modal to work. I'm using bootstrap library so the model itself is rather simple to show. The thing is I'm trying to load it with dynamic information from a database using ajax. But I can't seem to trigger it. My script doesn't do anything, I've been trying for quite a while now.
function fun(control){
$.ajax({
url:'<?=base_url()?>admin/proveedores/userDetails/'+control.id,
method: 'post',
data: {uid: control.id},
dataType: 'json',
success: function(response){
var len = response.length;
if(len > 0){
// Read values
var uname = response[0].razon_social;
var name = response[0].cuit;
var email = response[0].rubro;
$('#suname').text(uname);
$('#sname').text(name);
$('#semail').text(email);
}
</script>
The HTML PART
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div >
Username : <span id='suname'></span><br/>
Name : <span id='sname'></span><br/>
Email : <span id='semail'></span><br/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The function call
<tr id="<?= $e['id'] ?>" onclick="fun(this)" data-toggle="modal" data-target="#myModal" >
The Controller
public function userDetails($cid){
// POST data
// $postData = $this->input->post();
// get data
$data = $this->model_proveedores->get($cid);
echo json_encode($data);
}
I think it will helpful for you.
Please keep the modal content inside a div with id myModal and call ajax within the modal show action.
The Modal
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog" role="document">
// your modal content
</div>
</div>
The Call Button
<tr data-id="<?= $e['id'] ?>" data-toggle="modal" data-target="#myModal">
The Script
var modal = $("#myModal");
modal.on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var id = button.data('id');
$.ajax({
url : '<?= base_url() ?>admin/proveedores/userDetails/'+id,
type : 'post',
dataType : 'json',
data : { uid: id},
success : function(response)
{
var len = response.length;
if(len > 0){
// Read values
var uname = response[0].razon_social;
var name = response[0].cuit;
var email = response[0].rubro;
$('#suname').text(uname);
$('#sname').text(name);
$('#semail').text(email);
}
},
error : function(xhr)
{
console.log(xhr)
}
});
});
Your response is JSON encoded. You must decode that before using it as an object.
response=JSON.parse(response);
I have a problem on my modal form when I open the edit modal ,the modal pop up and it fetched my data and that is WORKING WELL but when I close the modal and click the add new user, the data is automatically fetched why is it fetched when I close the modal it should be reset to blank?
how can I reset or clear my form modal after i close the modal and not doing anything?
here is my Edit Javascript/Ajax code
$('#btnClose').click(function(){
$('#myForm')[0].reset();
}); //I Tried this block of code, but it didnt work
//Edit/Show
$('#showdata').on('click','.item-edit', function(){
var id = $(this).attr('data');
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Edit Employee');
$('#myForm').attr('action', '<?php echo base_url() ?>employees/updateEmployee');
$.ajax({
type: 'ajax',
method: 'get',
url: '<?php echo base_url() ?>employees/editEmployee',
data: {id:id},
async: false,
dataType:'json',
success: function(data){
$('input[name=txtEmployeeName]').val(data.employee_name);
$('textarea[name=txtAddress]').val(data.address);
$('input[name=txtId]').val(data.id);
},
error: function(){
aler('Could not edit Data');
}
});
});
and here is my modal (I use this modal to create and edit my data so it is just a one modal)
<!--MODAL-->
<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form id="myForm" action="" method="post" class="form-horizontal">
<input type="hidden" name="txtId" value="0">
<div class="form-group">
<label for="name" class="label-control col-md-4">Employee Name</label>
<div class="col-md-8">
<input type="text" name="txtEmployeeName" class="form-control">
</div>
</div>
<div class="form-group">
<label for="address" class="label-control col-md-4">Address</label>
<div class="col-md-8">
<textarea class="form-control" name="txtAddress"></textarea>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btnSave" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!--END MODAL-->
IN CASE you need to see my add/create javascript code here it is
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//form validation
var employeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (employeeName.val() == '') {
employeeName.parent().parent().addClass('has-error');
}else{
employeeName.parent().parent().removeClass('has-error');
formValid = false;
}
if (address.val()=='') {
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
formValid = false;
}
if (!formValid) {
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if (response.success) {
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if (response.type=='add') {
var type = 'added'
}else if(response.type=='update'){
var type = 'updated'
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(3000).fadeOut('slow');
showAllEmployees();
}else{
alert('Error');
}
},
error: function(){
alert('Data is not added');
}
});
}
});
Replace
$('#btnClose').click(function(){
$('#myForm')[0].reset();
});
with the following code,
$("#myModal").on("hidden.bs.modal", function () {
$('#myForm')[0].reset();
});
I have a modal form (simple) that I want to insert in my BD, but I'm not getting the expected result
modalview
this is the button that calls my modal:
<button type='button' class='btn btn-info' data-toggle="modal" data-target="#modal-default-cliente"><span class='fa fa-plus'></span></button>
this is my modal:
<div class="modal fade" id="modal-default-cliente">
<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">Agregar Usuario</h4>
</div>
<div class="modal-body">
<form method="POST" id="clienteform">
<div class="form-group">
<label for="nombrecompleto">Nombre Completo:</label>
<input type="text" class="form-control" name="nombremodal" id="nombremodal" required="required">
</div>
<div class="form-group">
<label for="telefono">Teléfono:</label>
<input type="text" class="form-control" name="telefonomodal" id="telefonomodal">
</div>
<div class="form-group">
<label for="direccion">Dirección:</label>
<input type="text" class="form-control" name="direccionmodal" id="direccionmodal">
</div>
<div class="form-group">
<input type="submit" name="action" class="btn btn-success" value="Guardar">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary pull-right" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
This is my Javascript code, which by the way the parameters of the form arrive
$(document).on("submit", "#clienteform", function(event){
event.preventDefault();
var nombre = $("#nombremodal").val();
var telefono = $("#telefonomodal").val();
var direccion = $("#direccionmodal").val();
$.ajax({
url: base_url+"mantenimiento/Ventas/agregarClientemodal",
method:'POST',
success: function(data){
alert(data);
$("#modal-default-cliente").modal("hide");
}
});
});
This is my action in the "Ventas" Controller:
public function agregarClientemodal(){
$data = array(
'Nombre' => $this->input->post("nombremodal") ,
'Telefono' => $this->input->post("telefonomodal"),
'Direccion' => $this->input->post("direccionmodal"),
'Estado' => "1"
);
$this->Ventas_model->agregarClientemodal($data);
}
and finally my function in the Sales model:
public function agregarUsuariomodal($data){
return $this->db->insert("Clientes",$data);
}
I'm new to Codeigniter, and when I click on my save button, my modal window does nothing
Expected behavior: save the record and hide the modal
behavior obtained: clicking on the submit does nothing
what am I doing wrong? What do I need to validate? any help for me?
Hope this will help you :
Pass form post values with ajax's data using var formdata = $(this).serialize();, and use site_url() for the URL
Your ajax should be like this :
$(document).ready(function(){
$("#clienteform").on("submit", function(event){
event.preventDefault();
var formdata = $(this).serialize();
$.ajax({
url: '<?=site_url("mantenimiento/Ventas/agregarClientemodal");?>',
method:'POST',
data : formdata,
success: function(data)
{
alert(data);
$("#modal-default-cliente").modal("hide");
}
});
});
});
Your agregarClientemodal method should be like this :
public function agregarClientemodal()
{
$data = array(
'Nombre' => $this->input->post("nombremodal") ,
'Telefono' => $this->input->post("telefonomodal"),
'Direccion' => $this->input->post("direccionmodal"),
'Estado' => "1"
);
$this->Ventas_model->agregarClientemodal($data);
echo "success";
exit;
}
Your base_url variable is not defined in javascript/jquery.
So you need to change that line into:
$.ajax({
url: '<?php echo base_url("mantenimiento/Ventas/agregarClientemodal");?>',
method:'POST',
success: function(data){
alert(data);
$("#modal-default-cliente").modal("hide");
}
});
it will generate correct url.
Further you can check console for error logs.
My code in view script
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('admin_technical/fileUploadblockquotes')?>";
} else {
url = "<?php echo site_url('admin_technical/ajax_updateblockquotes')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{reload_table();
alert(data.status);
$('#modal_formbq').modal('hide');
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data'+errorThrown);
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
view html modal
<div class="modal fade" id="modal_formbq" 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>
<h3 class="modal-title">Objectives</h3>
</div>
<div class="modal-body form">
<form id="form" class="form-horizontal" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Title</label>
<div class="col-md-9">
<input name="title" placeholder="Caption" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
controller
public function ajax_updateblockquotes()
{
$data = array(
'text' => $this->input->post('title'),
'id' => $this->input->post('id'),
);
$this->person->updateblockquotes($data);
echo json_encode(array("status" => TRUE));
}
im my model
public function updateblockquotes($data)
{
extract($data);
$this->db->where('id', $id);
return $this->db->update('technical_slide_blockquotes', array('text' => $text));
}
The problem is when I do a debugging using the developer tool from google chrome the result is true, no errors found but when I look the database nothing change on it.