How to pass a parameter from a view to the controller with Ajax? Codeigniter - ajax

I am just learning and I would like you to help me solve this problem: I have two views, in view 1 it shows me a list of users, when clicking on any of them you must open another view showing the information about that user in view 2 .
To do that in view 1 with js I capture the user's id and send it to the controller by ajax, and in the controller it sends it to the model and the model response returns to the controller and sends it to view2, to show only the information of the selected user, the question is that it does not work, could you help me, what am I doing wrong?
View 1: This is the paragraph where you click and capture the id and the ajax that sends that id to the controller.
View1
<p onclick="detalles('<?=$p->usuarioId?>');"> <?=$p->usuarioId?><i class="fa fa-check-circle"></i> <?php echo $p->user ?></p>
<script>
function detalles(id=null){
$ (document) .ready (function () {
console.log(id);
$.ajax({
type: "POST",
data : {'id': id},
dataType:"html",
url: "usuarios_admin/ver",
success: function(result)
{
alert("good");
console.log("result",result);
}
});
});
}
</script>
Controller
public function ver(){
$id = $this->input->post("id");
if($id != null) {
$data = $this->PostUser->find($id);
echo json_encode($data);
$this->load->view('usuarios/vista2', $data);
}
}
model:
function find($id){
$this->db->select();
$this->db->from($this->table);
$this->db->where($this->table_id, $id);
$query = $this->db->get();
return $query->row();
}
view2:
here you must see the user data
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 lininfo">
<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5 sinpa">
<p class="colorp">Name:</p>
</div>
<div class="col-lg-7 col-md-7 col-sm-7 col-xs-7 sinpa">
<p class="colorpi"><?php $data['name'] ?></p>
</div>
</div>

try this, i think there should be typo mistake
<p onclick="detalles('<?php echo $p->usuarioId ?>');"> <?php echo $p->usuarioId; ?>
<i class="fa fa-check-circle"></i> <?php echo $p->user ?></p>

Is your 2nd view load after ajax call?
Have you print your return data in ajax success,because you define dataType:"html" in ajax but you return json data from controller.

Thank you for your answers, it came out.
I had to print on the view this way to see the data:
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 lininfo">
<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5 sinpa">
<p class="colorp">Name :</p>
</div>
<div class="col-lg-7 col-md-7 col-sm-7 col-xs-7 sinpa">
<p class="colorpi"><?php echo $user->name ?></p>
</div>
</div>
controller:
public function ver(){
$id = $this->input->post("id");
if($id != null) {
$data['user'] = $this->PostUser->find($id);
$this->load->view('usuarios/vista2', $data);
}
}
ajax y view 1
<div class="hi">
<!-- here you would see the result of ajax -->
<div>
<script>
function detalles(id=null){
$ (document) .ready (function () {
console.log(id);
$.ajax({
type: "POST",
data : {'id': id},
dataType:"html",
url: "usuarios_admin/ver",
success: function(result)
{
$('.hi').html(result);
}
});
});
}
</script>

Related

Ajax request for delete image doesnt work in laravel

I want to delete the image in the preview box, as well as delete it in the database using ajax. Deleting the image in the preview box was successful, but deleting it from the database didn't work.
here my ajax:
$(document).ready(function() {
document.getElementById('pro-image').addEventListener('change', readImage, false);
$(".preview-images-zone").sortable();
$(document).on('click', '.image-cancel', function() {
let no = $(this).data('no');
let idData = $(this).data('id');
$(".preview-image.preview-show-" + no).remove();
$.ajax({
type: 'POST',
url: '{{url("unit/API/simpan")}}',
data: {
'id': idData
},
success: function(data) {
alert('success');
}
});
});
});
My Html:
<!-- Percobaan Preview -->
<fieldset class="form-group">
<div class="offset-md-2 col-md-6">
Upload Gambar
<input type="file" id="pro-image" name="gambarku[]" style="display: none;" class="form-control" multiple>
</div>
</fieldset>
<div class="preview-images-zone offset-md-2 col-md-8">
<!-- Gambar Utama -->
<div class="preview-image preview-show-1">
<div class="image-cancel" data-no="1">x</div>
<div class="image-zone"><img id="pro-img-1" src="{{asset('storage/rumah/'.$rumahku->gambar_rumah)}}"></div>
</div>
<!-- Gambar Tambahan -->
<?php $counter = 2 ?>
#foreach($rumahku->gambar as $rows)
<div class="preview-image preview-show-{{$counter}}">
<div class="image-cancel" data-no="{{$counter}}" data-id="{{$rows->id_gambar}}">x</div>
<div class="image-zone"><img id="pro-img-{{$counter}}" src="{{asset('storage/rumah/'.$rows->gambar_unit)}}"></div>
</div>
<?php $counter++ ?>
#endforeach
</div>
<!-- /preview -->
my route
Route::post('unit/API/simpan/{id}', 'partner\UnitController#simpanGambar');
my controller
public function simpanGambar($id)
{
$gambar = Gambar::find($id);
$gambar->delete();
}
you can try this
Route::post('unit/API/simpan', 'partner\UnitController#simpanGambar');
and
public function simpanGambar(Request $request)
{
$gambar = Gambar::find($request->id);
$gambar->delete();
}
or in ajax
$.ajax({
type: 'POST',
url: '{{url("unit/API/simpan")}}' +'/'+ id, <---------- pass id here

Need guidance on how to populate a DIV using server side Ajax query then iterate with #foreach. Currently getting 'undefined variable' error

In a Laravel project I'm attempting to use Ajax to populate a DIV and then use #foreach to populate the store gallery. If possible I wanted to use a Server side content generation strategy. However, something silly is going on that I can't figure out-- I'm getting the following error:
$user_query is undefined
Make the variable optional in the blade template. Replace {{ $user_query }} with {{ $user_query ?? '' }}
How is this (#foreach ($user_query as $item)) suppose to be constructed in the blade?
routes
Route::get('/ajaxStoreRequest', 'StoreController#ajaxStoreRequest');
Route::post('/ajaxStoreRequest/post', 'StoreController#ajaxStoreRequestPost');
Here is the StoreController.php:
<?php
namespace App\Http\Controllers;
use App\Coin;
use Illuminate\Http\Request;
use App\DataTables\StoresDataTable;
use App\DataTables\StoresDataTableEditor;
use Illuminate\Support\Facades\DB;
class StoreController extends Controller
{
public function ajaxStoreRequest()
{
return view('store.index');
}
public function ajaxStoreRequestPost(Request $request)
{
$user_query= DB::table('coins')
->select('id','year', 'mint', 'series', 'rating', 'rating_group','photo_link1', 'for_sale_price')
->where('for_sale', '=', 1)
->where('sold', '=', 0)
->where('series', '=', $request->series)
->where('year', '=', $request->year)
->where('mint', '=', $request->mint)
->where('rating_group', '=', $request->rating_group)
->get();
return response()->json($user_query);
}
}
a DD($user_query); shows the following array format
Illuminate\Support\Collection {#552
#items: array:1 [
0 => {#555
+"id": 2
+"year": 1878
+"mint": "Philadelphia"
+"series": "Morgan Dollar"
+"rating": "Ungraded"
+"rating_group": "PCGS"
+"photo_link1": "editor/20200328_002220_888888966_732020162248388.jpg"
+"for_sale_price": "44"
}
]
}
Here is the Ajax script from the bottom of the store/index.blade.php
<script type="text/javascript">
$.ajaxSetup({
beforeSend: function(xhr, type) {
if (!type.crossDomain) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
},
});
$(".btn-submit").click(function(e){
e.preventDefault();
var series = $("#series option:selected").val();
var year = $("input[name=year]").val();
var mint = $("#mint option:selected").val();
var rating_group = $("#rating_group option:selected").val();
var price_filter = $("input[name=price_filter]:checked").val();
$.ajax({
type:'POST',
url:'/ajaxStoreRequest/post',
data:{series:series, year:year, mint:mint, rating_group:rating_group, price_filter:price_filter},
success:function(result){
$('.collapse').collapse('show');
$('#user_query').html(result);
}
});
});
</script>
Here is the HTML further up in the store/index.blade.php
<div class="row row-deck js-gallery collapse">
<div class="user_query" id="user_query">
#foreach ($user_query as $item) <!-- THIS IS THE ERROR -->
<div class="col-md-6 col-xl-4">
<div class="block">
<div class="options-container">
#if ($item->photo_link1)
<img class="img-fluid options-item" src="storage/{{$item->photo_link1}}" style="width:300px; height:300px" alt="">
#else
<img class="img-fluid options-item" src="images/no-user-profile-picture-1200x900.jpg" style="width:300px; height:300px" alt="">
#endif
<div class="options-overlay bg-black-75">
<div class="options-overlay-content">
<a class="btn btn-sm btn-primary img-lightbox" href="gallery/{{$item->id}}">
View
</a>
<a class="btn btn-sm btn-light" href="javascript:void(0)">
<i class="fa fa-plus text-success mr-1"></i> Add to cart
</a>
</div>
</div>
</div>
<div class="block-content">
<div class="mb-2">
<div class="h4 font-w600 text-success float-right ml-1">${{$item->for_sale_price}}</div>
<a class="h4" href="be_pages_ecom_store_product.html">{{$item->year}}-{{$item->mint}}</a>
</div>
<p class="font-size-sm text-muted">{{$item->series}} ({{$item->rating}} {{$item->rating_group}})</p>
</div>
</div>
</div>
#endforeach
</div>
</div>
I'm attempting to use Ajax to populate a DIV and then use #foreach
This is fundamentally backwards. store/index.blade.php is rendered server side, so any data returned from your ajax call must be added to the DOM using JavaScript.

I have a probllem when the button delete has clicked but the data cannot delete and the url not show the id

I have tried to solve this problem several hours but I never solve this problem
I have a problem with my code, when I click the delete button from json, I can't get the ID just link from the console like this:
example :
That happened : request
I want Like this : request/?id=1
I paste some code to check :
Controller request.php:
public function delete()
{
// $this->m_request->delete($this->input->post('id_form'));
$id = $this->input->post('id_form');
$data = $this->m_request->DeleteRequest($id);
echo json_encode($data);
}
Model m_request.php:
public function DeleteRequest($id)
{
$hasil = $this->db->query("DELETE FROM request WHERE id_form='$id'");
return $hasil;
}
And Then View (I just put the modal script and ajax json script) :
Modal View :
<div class="modal fade" id="ModalHapus" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Hapus Request</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">X</span></button>
</div>
<form class="form-horizontal">
<div class="modal-body">
<input type="hidden" name="kode" id="textkode" value="">
<div class="alert alert-warning">
<p>Apakah Anda yakin mau menghapus request ini?</p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button>
<button class="btn_hapus btn btn-danger" id="btn_hapus">Hapus</button>
</div>
</form>
</div>
</div>
Ajax/JSON Script :
//GET HAPUS
$(document).on('click', '.hapus', function() {
var id = $(this).attr('data');
$('#ModalHapus').modal('show');
$('[name="kode"]').val(id);
})
// Hapus Request
$('#btn_hapus').on('click',function(e){
e.preventDefault();
var id = $('textkode').val();
$.ajax({
type: "POST",
url: "<?= site_url('request/delete')?>",
dataType: "JSON",
data: {id:id},
success: function(data){
// $('#ModalHapus').modal('hide');
console.log(data)
load_data();
}
});
return false;
})
There are a lot of reasons why the ajax request is possibly not working. The first thing which came in my mind is, that you have not specified an ID and method of the input form. Make sure you have both in your HTML form tag. For example:
<form id=“id_form” method=“post” class=“...”>
...
<input type="text" name="kode" id="textkode">
</form>
In you JS Code do the following
$.ajax({
type: "POST",
url: "<?= site_url('request/delete')?>",
dataType: "JSON",
data: $(“#id_form”).serialize(),
success: function(data){
console.log(data)
load_data();
}
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nERROR: "+ err);
}
});
Also change the your delete function to this:
public function deleteTableRow()
{
$id = $_POST['textkode']; // Because I'm not sure what this->input->post() makes
$result = $this->m_request->DeleteRequest($id);
echo json_encode(array('id' => $id, 'result' => $result)); // The contents of array should then be displayed in the console of your webbrowser
}
Note that I changed the function name. It could be very misleading for other programmers, because delete is used in many programming languages as destructor for dynamic objects!
Additionally I would recommend to create an ajax.php file to parse different kind of ajax request. This file would also work as a controller, but just for ajax calls. In case you have several forms, the code is more readable.

How to use variable data after Ajax Call Success - Laravel

I created a small file manager to manage my files. On the one hand, the folder structure is shown thanks to JsTree. On the right I would like that based on the click on the left folder I was shown the files contained in that folder.
At the click an Ajax call is made which calls the selectFiles method to go through the routes. Now in the console i see the correct data, but i don't know how to use it into foreach in the blade.
AJAX:
// chiamata Ajax per selezionare files in base all'id
$('#treeview').on("select_node.jstree", function (e, data) {
var id = data.node.id;
$.ajax({
type: 'POST',
url: 'archivio_documenti/+id+/selectFiles',
data: {id:id},
success: function(data) {
console.log('Succes!',data);
},
error : function(err) {
console.log('Error!', err);
},
});
});
DocumentiController.php:
/**
* Selzionare files in base all'id della cartella
*/
public function selectFiles(Request $request){
try{
$id = $request->id;
$files = \App\Documento::where('cartella_id',$id)->get();
return response()->json(compact('files'));
}
catch(\Exception $e){
echo json_encode($e->getMessage());
}
}
Route:
Route::post('archivio_documenti/{id}/selectFiles', 'DocumentiController#selectFiles');
Update:
#foreach($files as $key => $file)
<div id="myDIV" class="file-box">
<div class="file">
{!! Form::open(['method' => 'DELETE','route' => ['documento.destroy', $file->id]]) !!}
<button type="submit" class="#" style="background: none; border: none; color: red;">
<i class='fa fa-trash' aria-hidden='true'></i>
</button>
{!! Form::close() !!}
<i class='fa fa-edit' aria-hidden='true'></i>
<input id="myInput_{{$key}}" type="text" value="{{'project.dev/'.$file->path.'/'.$file->file}}">
<i class="btnFiles fa fa-files-o" aria-hidden="true" data-id="{{$key}}"></i>
<a href="{{' http://project.dev/'.$file->path.'/'.$file->file}}">
<span class="corner"></span>
<div class="icon">
<i class="img-responsive fa fa-{{$file->tipo_file}}" style="color:{{$file->color_file}}"></i>
</div>
<div class="file-name">
{{$file->file}}
<br>
<small>Update: {{$file->updated_at}}</small>
</div>
</a>
</div>
</div>
#endforeach
OK, the foreach of yours is a bit complex, but the idea itself is simple: recreate the foreach loop from your Blade in Javascript and append the result to the DOM.
In your success callback you could e.g. do this:
$('#treeview').on("select_node.jstree", function (e, data) {
var id = data.node.id;
$.ajax({
type: 'POST',
url: 'archivio_documenti/+id+/selectFiles',
data: {id:id},
success: function(data) {
// Build the HTML based on the files data
var html = '';
$.each(data, function(i, file) {
html += '<div class="file" id="file_' + file.id + '">' + file.updated_at + '</div>';
});
// Append the built HTML to a DOM element of your choice
$('#myFilesContainer').empty().append(html);
},
error : function(err) {
console.log('Error!', err);
},
});
});
Obviously, this is simplified and you'd need to use the HTML structure you've shown us in the foreach loop above, but the idea is the same: (1) loop through your files in the data object and build the HTML structure row by row, (2) put the whole HTML block in the DOM, wherever you need it to be displayed after the user clicked on a folder.
Alternative:
If you'd like to keep the foreach loop in Blade instead of of Javascipt, you could move the loop to a separate blade:
folder_contents.blade.php
#foreach($files as $key => $file)
<div id="myDIV" class="file-box">
<div class="file">
{!! Form::open(['method' => 'DELETE','route' => ['documento.destroy', $file->id]]) !!}
<button type="submit" class="#" style="background: none; border: none; color: red;">
<i class='fa fa-trash' aria-hidden='true'></i>
</button>
{!! Form::close() !!}
<i class='fa fa-edit' aria-hidden='true'></i>
<input id="myInput_{{$key}}" type="text" value="{{'project.dev/'.$file->path.'/'.$file->file}}">
<i class="btnFiles fa fa-files-o" aria-hidden="true" data-id="{{$key}}"></i>
<a href="{{' http://project.dev/'.$file->path.'/'.$file->file}}">
<span class="corner"></span>
<div class="icon">
<i class="img-responsive fa fa-{{$file->tipo_file}}" style="color:{{$file->color_file}}"></i>
</div>
<div class="file-name">
{{$file->file}}
<br>
<small>Update: {{$file->updated_at}}</small>
</div>
</a>
</div>
</div>
#endforeach
Then, in your controller:
public function selectFiles(Request $request){
try{
$id = $request->id;
$files = \App\Documento::where('cartella_id',$id)->get();
// Save the view as string
$view = view('folder_contents.blade.php', compact('files')))->render();
// Pass the ready HTML back to Javasctipt
return response()->json(compact('view'));
}
catch(\Exception $e){
echo json_encode($e->getMessage());
}
}
you must set header for ajax
headers: {
'X_CSRF_TOKEN':'xxxxxxxxxxxxxxxxxxxx',
'Content-Type':'application/json'
},
and in Controller
public function selectFiles(Request $request){
try{
$id = $request->id;
$files = \App\Documento::where('cartella_id',$id)->get();
return response()->json($files);
}
catch(\Exception $e){
echo json_encode($e->getMessage());
}
}

Adding records to a drop down menu without form refresh

I want to add records to a drop down menu without form refresh. I'm using codeigniter and bootstrap
Here is the Bootstrap Modal :
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
<h4 id="myLargeModalLabel" class="modal-title">Add Record</h4>
</div>
<div class="modal-body">
<form class="sky-form" id="sky-inchidere" method="post" accept-charset="utf-8" action="">
<dl class="dl-horizontal">
<dt>Name<span class="color-red">*</span></dt>
<dd>
<section>
<label class="input">
<i class="icon-append fa fa-inbox"></i>
<input type="text" value="" name="name" required>
<b class="tooltip tooltip-bottom-right">Add New Record</b>
</label>
</section>
</dd>
</dl>
<hr>
<button type="submit" class="btn-u" style="float:right; margin-top:-5px;">Submit</button>
</form>
</div>
</div>
</div>
Ajax script :
$(document).ready(function(){
$("#sky-inchidere").submit(function(e){
e.preventDefault();
var tdata= $("#sky-inchidere").serializeArray();
$.ajax({
type: "POST",
url: 'http://localhost/new/oportunitati/add',
data: tdata,
success:function(tdata)
{
alert('SUCCESS!!');
},
error: function (XHR, status, response) {
alert('fail');
}
});
});
});
CI Controller ( i have added the modal code here for test )
public function add() {
$tdata = array( name=> $this->input->post(name),
);
$this->db->insert('table',$tdata);
}
When i use this code i get "fail" error message.
Thanks for your time.
how yo debug:
1. Print your 'tdata' and see what happen;
2. Something wrong here: $this->input->post('name');
Try to use:
$tdata = array(
'name' => $this->input->post('name')
);
I manage to find the problem and correct it. (typo on the table name)
Now I have come across a different problem. In the ajax success I cant refresh the chosen dropdown records i have tried :
success:function(tdata)
{
// close the modal
$('#myModal').modal('hide');
// update dropdown ??
$('.chosen-select').trigger('liszt:updated');
$('#field-beneficiar_p').trigger('chosen:updated');
$('#field-beneficiar_p').trigger('liszt:updated');
},
Any help in how i can refresh the records to see the last added item will be appreciated. I'm using chosen plugin.
from controller send data in json_encode
then in js function
$.ajax({
type: "POST",
url: "<?php echo base_url('login/get_time'); ?>",
data: {"consltant_name": consltant_name, "time": time},
success: function(data) {
var data = JSON.parse(data);
var options = '';
options = options + '<option value="">Please Select One</option>'
$.each(data, function(i, item) {
options = options + '<option value="' + item + '">' + item + '</option>'
});
selectbox.html(options);
}});

Resources