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
Related
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'm generating table rows with data from a database.
Below is my code:
<table class="table table-hover" id="dashEventTable">
<thead>
<tr>
<th>Created at</th>
<th>Seminar Name</th>
<th>Quota</th>
<th>Location</th>
<th>Option</th>
<th style="display:none"></th>
</tr>
</thead>
<tbody script="javascript">
<?php
$one = 1;
$Lihat="SELECT * FROM event where status = '$one'";
$Tampil = mysqli_query( $db, $Lihat );
while ( $hasil = mysqli_fetch_array ( $Tampil ) ) {
$id_event = ( $hasil['id_event'] );
$nama_event = ( $hasil['nama_event'] );
$lokasi = ( $hasil['lokasi'] );
$kuota = ( $hasil['kuota'] );
$created_at = ( $hasil['created_at'] );
{ ?>
<tr>
<td class="created_at"><?php echo date( 'Y-m-d h:i a', strtotime( $created_at ) ); ?></td>
<td class="event_name"><?php echo "$nama_event"; ?></td>
<td class="kuota"><?php echo "$kuota"; ?></td>
<td class="lokasi"><?php echo "$lokasi"; ?></td>
<td>
<a class="btn btn-xs btn-danger btn_delete" data-toggle="modal" href="#deleteDashEvent"><i class="fa fa-trash"></i></a>
</td>
<td class="event_id" style="display:none"><?php echo "$id_event"; ?></td>
</tr><?php }
} ?>
</tbody>
</table>
Now when I click on the button inside the rows, it does two things, the first is going to this JavaScript function:
$( ".btn_delete" ).click(function() {
var $row = $( this ).closest( "tr" ); // Find the row
var event_id = $row.find( ".event_id" ).text();
console.log( event_id );
$.ajax({
url: "contain_data.php",
method: 'post',
data: {
'send': event_id
},
success: function() {
alert( event_id );
}
});
});
From the alert and console log, I saw that I got the correct ID for the event id of the row. The data will then be sent to the PHP file above, and inside that PHP is this:
<?php
if ( isset( $_POST['send'] ) ) {
$id_event = $_POST['send'];
} else {
echo "The data has not been received!";
}
The second thing it does is go to this div for the delete confirmation:
<form action="admin_delete_event.php" enctype="multipart/form-data" id="event_delete_row" method="post" name="delete_event_row">
<div class="modal fade" id="deleteDashEvent">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button aria-label="Close" class="close" data-dismiss="modal" type="button">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Delete Confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure want to delete this event?</p>
</div>
<div class="modal-footer">
<a class="btn btn-default" data-dismiss="modal" href="#">Batal</a>
<button class="btn btn-primary btn_confirm_delete" name="admin_delete_event" type="submit">DELETE</button>
</div>
</div>
</div>
</div>
</form>
When the DELETE button is clicked, it will then go to this PHP file:
<?php
session_start();
include( "config.php" );
if ( isset( $_POST['admin_delete_event'] ) ) {
include( "contain_data.php" );
$zero = 0;
$delete_query = "UPDATE event, jadwal_acara, waktu_pendaftaran
SET event.status = '$zero', jadwal_acara.status = '$zero', waktu_pendaftaran.status = '$zero'
WHERE event.id_event = '$id_event'
AND jadwal_acara.id_event = '$id_event'
AND waktu_pendaftaran.id_event = '$id_event'";
if ( mysqli_query( $db, $delete_query ) ) {
$delete = "Data has been deleted";
echo $delete;
} else {
echo "Error: " . $delete_query . "<br>" . mysqli_error( $db );
}
} else {
echo "The button is not detected!";
}
The problem I am having is that I received this error when I click the delete confirmation button:
The data has not been received!
Undefined variable: id_event in...
Which means that I fail in sending the data.
What am I doing wrong and how can I resolve it?
EDIT: after adding error handling to the php file, the value sent by the ajax is null instead of the id_event, do you guys know why?
Update your AJAX With:
$.ajax({
url: "contain_data.php",
method: 'post',
data : 'send='+event_id,
success:function(){
alert(event_id);
}
});
try to pass your event_id using this way
data : 'send='+event_id,
because you have taken
method: 'post',
Hope it will help
I got your error . Upto submit your first form through is correct when you go for delete conformation you miss that event_id and you just using that one in you "admin_delete_event.php" file that why it giving error
Undefined variable: id_event in...
Now just add an hidden input field in form and submit it then the event_id will be available to you.
<form action="admin_delete_event.php" enctype="multipart/form-data" id="event_delete_row" method="post" name="delete_event_row">
<div class="modal fade" id="deleteDashEvent">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button aria-label="Close" class="close" data-dismiss="modal" type="button">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Delete Confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure want to delete this event?</p>
</div>
<div class="modal-footer">
<a class="btn btn-default" data-dismiss="modal" href="#">Batal</a>
<button class="btn btn-primary btn_confirm_delete" name="admin_delete_event" type="submit">DELETE</button>
</div>
</div>
</div>
</div>
<input type="hidden" name='event_id' value='id' id='event'>
</form>
And just change this in your 1st Ajax
$( ".btn_delete" ).click(function() {
var $row = $( this ).closest( "tr" ); // Find the row
var event_id = $row.find( ".event_id" ).text();
console.log( event_id );
$.ajax({
url: "contain_data.php",
method: 'post',
data: {
'send': event_id
},
success: function() {
$('#event').val(event_id);
alert( event_id );
}
});
});
Then it will work fine.
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 table: Users with 3 different attributes:
ID
firstname
lastname
In the index.ctp page for Users, for each data entry, I have the Edit action available to use.
<div>
<table class="usersTables" id="userTable">
<thead>
<tr>
<th scope="col"><?= $this->Paginator->sort('firstname') ?></th>
<th scope="col" class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user): ?>
<tr>
<td><?= h($user->firstname) ?></td>
<td class="actions">
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $user->id], ['class' => 'view', 'data-id' => $user->id]) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<script type="text/javascript">
$(function () {
$('.edit').click(function () {
ev.preventDefault();
var userId = $(this).attr('data-id');
$('#editModal').modal('show');
alert(userId);
});
});
</script>
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<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" id="editModalLabel">Edit</h4>
<div>
<div class="col-sm-6">
<?= $this->Form->input('firstname', ['class' => 'form-control', 'label' => 'First Name', 'placeholder' => 'First name', 'id' => 'firstname']); ?>
</div>
<div class="col-sm-6">
<?= $this->Form->input('lastname', ['class' => 'form-control', 'label' => 'Last Name', 'placeholder' => 'Last name', 'id' => 'lastname']); ?>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="savebutton" type="button" class="btn btn-primary" data-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
Clicking the Edit button in the table first gives me an alert pop up that tells me which $user->id I selected, then opens up the Edit modal. However, my form inputs are still empty even though the related attributes for that specific datat entry are fileld in the database. I'm not sure how to connect the data-id variable that was then defined as a JavaScript variable to the form input which I believe requires a PHP variable again ($user->firstname).
If I use 'value' => $user->firstname in the firstname form input, I get the data from the very last data entry every time (eg. if I have 3 data entries in my Users table, I will always get the 3rd entry's firstname).
Glad you researched about AJAX. First you need to create a function in your controller that will return a user's details.
// Just an example in the UsersController
public function userDetails($id = null) {
$userDetails = $this->Users->find('all'['where(['id' => $id])])->first();
$this->set(array(
'output' => $userDetails,
'_serialize' => 'output',
'_jsonp'=>true
));
}
Then setup an ajax request from your view.
// in your index.ctp's script
<script type="text/javascript">
$(function () {
$('.edit').click(function () {
ev.preventDefault();
var userId = $(this).attr('data-id');
$('#editModal').modal('show');
$.ajax({
url:"localhost/your_project/Users/userDetails/"+userId+".json",
type:'POST',
success:function(res) {
console.log(res); // check the response in your console
if(res) {
$('#firstname').val(res.firstname);
$('#lastname').val(res.lastname);
}
}
});
});
});
You can send the userId as a post data for the function's parameter.
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.