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);
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 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 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');
}
I have a modal that updates information on countries.
// Partial code of the modal
<div id="EditModal" class="modal fade" 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-hidden="true">× </button>
<h4 class="modal-title" id="myModalLabel">Edit <label id="EntityType"></label></h4>
</div>
<div class="modal-body">
<div class="row">
#yield('EditModalBody')
</div>
</div>
<div class="modal-footer" style="text-align: center">
{{ Form::submit('Save', ['class' => 'btn btn-success', 'id' => 'editBtn']) }}
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
I'm trying to implement this with AJAX, so that if there are any errors, the modal does not close and the error messaged appear under each input field.
This is my JS:
<script type="text/javascript">
$("#EditModal").submit(function (e) {
e.preventDefault();
var selector = $(this);
$.ajax({
type: 'PATCH',
dataType: 'json',
url: selector.attr("action"),
data: selector.serialize(),
success: function (data) {
if (data.success) {
alert('go go go');
} else {
// for debugging
alert('data');
}
},
error: function (xhr, textStatus, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
I am getting "405 Method not allowed" error, although I declared my controller as a "ressource" like this:
Route::resource('country', 'CountryController',
['except' => ['show']]);
If I do php artisan route:list I can see that the PATCH route is declared.
Any ideas?
EDIT 1:
This is (part of) my controller:
public function update($id, Request $request)
{
$validator = Validator::make($request->all(), $this->getRules(), $this->getMesssages());
if ($validator->fails()) {
$json = new stdClass();
$json->success = false;
$json->errors = $Validator->errors();
}
else {
$json = new stdClass();
$json->success = true;
}
return Response::json($json);
EDIT 2:
So I added this <input type="hidden" name="_token" value="{{{ csrf_token() }}}"/> in my modal and I no longer get the 405 error. I still have a problem that I always get the "error" part of my JS (only that now I get status 0)
type: 'PATCH' does not exists on HTTP methods thus will not be recognized by Laravel.
Try this:
$.ajax({
type: 'POST',
dataType: 'json',
url: selector.attr("action"),
data: {
'_method': 'PATCH',
'data': selector.serialize(),
},
You have to submit the method PATCH as _method Post data.
Edit
Your controller function looks wrong. The correct order would be
public function update(Request $request, $id)
instead of
public function update($id, Request $request)
OT: I already submitted an addition for the Laravel documentation that gives you a hint about this problem but it was rejected with no comment.
My code was working fine before. But Now it is not working. I am working on codeigniter and I am uploading a file using jquery ajax. I donot know why my code stop working. If you can find the issue please let me know.
Here is the controller code
public function updatedp()
{
$var = $_FILES['fileUp'];
$img=$_FILES['fileUp'];
$config['upload_path'] = 'webim/dp_images';
$config['overwrite'] = 'TRUE';
$config["allowed_types"] = 'jpg|jpeg|png|gif';
$config["max_size"] = '1400';
$config["max_width"] = '1400';
$config["max_height"] = '1400';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('fileUp'))
{
$this->data['error'] = $this->upload->display_errors();
echo json_encode(array("result"=>$this->data['error']));
exit;
} else {
$data=array('active'=>0);
$this->db->where('userid','1');
$this->db->update('music_user_dp',$data);
$uname['uname'] =$this->session->all_userdata('uname');
$uname['id'] =$this->session->all_userdata('id');
$post_data = array(
'id' => '',
'userid' => $uname['id']['id'],
'profilepic'=>$var['name'],
'updatedate' => date("Y-m-d H:i:s"),
'active' => '1'
);
$this->Userpage_model->insert_dp_to_db($post_data);
echo json_encode(array("result"=>"Success"));
exit;
}
}
My jquery code which calling above function:
$("#btnupdate").click(function(event){
if($("#fileupload2").val() != ''){
if (typeof FormData !== 'undefined') {
var form = $('#formname').get(0);
var formData = new FormData(form);
$.ajax({
type: "POST",
url: "Userpage/updatedp",
data: formData,
mimeType:"multipart/form-data",
dataType: 'json',
xhr: function() {
return $.ajaxSettings.xhr();
},
cache:false,
contentType: false,
processData: false,
success: function(result){
toastr8.info({
message:'Profile Picture Updated',
title:"New Image Uploaded",
iconClass: "fa fa-info",
});
}
});
event.preventDefault();
}
} else {
toastr8.info({
message:'Error Occured',
title:"Please try again",
iconClass: "fa fa-info",
});
}
});
HTML:
<div class="modal fade" id="myModal" role="dialog">
<form enctype="multipart/form-data" name="formname" id="formname" method="post" action="">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header ">
<script type="text/javascript">
$(document).ready(function(){
$('#mgupload-dp').click(function(e){
$('#fileupload2').click();
e.preventDefault();
});
});
</script>
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Create profile picture</h4>
</div>
<div class="modal-body">
<div class="text-center" style="width:100%"> <img src="<?php echo base_url(); ?>img/profile.png" alt="add dp" id="pop-dp" >
<button type="button" class="btn btn-default text-center" id="mgupload-dp">Choose picture to upload</button>
<input type="file" id="fileupload2" name="fileUp" class="hidden-dp" accept="image/*">
</div>
<div class="clearfix"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="btnupdate">Update Picture</button>
</div>
</div>
</div>
</div>
</form>
</div>
Files are not uploading and I am getting this error
A PHP Error was encountered
Severity: Notice
Message: Undefined index: fileUp
Filename: controllers/Userpage.php
Open the Firebug in FF.
Click on the ajax call URL under Console.
See what are passed under "Post" tab.
If fileUp is present there, use $this->input->post('fileUp'); to fetch the contents.