How to use variable data after Ajax Call Success - Laravel - ajax

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

Related

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.

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

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>

Laravel 5: When store data to database The server responded with a status of 405 (Method Not Allowed)

I m new in Laravel and trying to add data to the database via ajax, but it throws this message: "The server responded with a status of 405 (Method Not Allowed)" I define two routes for this one is for form page
Route::get('/create/{id}', 'Participant\ParticipantProjectDefinitionController#create')->name('participant.project-definition.create');
and other route to save this data like this:
// To save Project definition Data
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
And the Ajax code I'm using is this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: {
'_token' : token,
'customer_name' : $('#field_name_0').val(),
'customer_name' : $('#field_data_0').val(),
// 'form_fields' : form_fields
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
Controller code
/**
* create project Definition Form
*
*/
public function create(request $request, $id){
$ProjectDefinitionFields = ProjectDefinitionFields::all();
$ProjectDefinitionFieldRow = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
// dd($ProjectDefinitionFieldRow);
return view('participants.project_definition.create', ['ProjectDefinitionFieldRow' => $ProjectDefinitionFieldRow]);
}
public function store(request $request, $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields){
$project = ProjectDefinitionFields::find('field_id');
$count = ProjectDefinitionFields::where('project_definition_id','=', $id)->count();
$pd_id = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
for($i=0;$i<$count;$i++){
$data[]= array (
'field_name'=>$request->get('field_name_'.$i),
'field_data'=>$request->get('field_data_'.$i),
'user_id' => Auth::user()->id,
// 'user_id' => $request->user()->id,
'project_definition_id' => $pd_id,
// 'field_id' => $projectDefinitionFields->id,
);
}
$project_data = ProjectDefinitionData::create($data);
if($project_data){
return response()->json($project_data);
}
}
Model
on ProjectDefinition
public function formFields(){
// return $this->hasMany('App\Model\ProjectDefinitionFields');
return $this->belongsTo('App\Model\ProjectDefinitionFields');
}
on projectDefinitionFields
public function projectDefinition(){
return $this->belongsTo('App\Model\ProjectDefinition');
}
This is my create.blade.php
<form id="create_project_definition_data_form" enctype="multipart/form-data" >
#csrf
{{ method_field('PUT') }}
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
#section('scripts')
<script src="{{ asset('js/participants/project-definition.js') }}"></script>
<script>
// on document ready
$(document).ready(function(){
var baseUrl = "{{ url('/') }}";
var indexPdUrl = "{{ route('participant.projectDefinition') }}";
var token = "{{ csrf_token() }}";
{{-- // var addUrl = "{{ route('participant.project-definition.create') }}"; --}}
storeDefinitionFormData(token, baseUrl);
// console.log(addUrl);
});
</script>
ERROR
Request URL:http://127.0.0.1:8000/participant/project-definition/create/2kxMQc4GvAD13LZC733CjWYLWy8ZzhLFsvmOj3oT
Request method:POST
Remote address:127.0.0.1:8000
Status code: 405 Method Not Allowed
Version:HTTP/1.0
Add method attribute in form
method="post"
Change your route from
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
to
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
Firstly, you should post here what's your problem and where's your problem we don't need to see all of your code to solve a basic problem.
Your form should be this:
<form id="create_project_definition_data_form" enctype="multipart/form-data" method='post'>
#csrf
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
You should use 'post' method when you're creating a something new, this is safer than using 'get' method. so change route method too.
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
also, in your 'ParticipantProjectDefinitionController->store()' function has
$id, User $user, ProjectDefinitionFields $ProjectDefinitionFields parameters but your router not. We can fix it like this:
Route::post('/store-project-definition-data/{id}/{user}/{ProjectDefinitionFields}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
That means you should pass all of them to your controller.
Soo we can edit your ajax call like this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: { // $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields
'_token' : token,
'id' : 'your_id_field',
'user' : '{{ Auth::user() }}',
'ProjectDefinitionFields' : 'your_definition_fields' // you need to pass type of 'ProjectDefinitionFields'
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
before try it, I'll give you a advice. Read whole documentation and review what others do on github or somewhere else
Route::match(['GET','POST'],'/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
You can try this Route it will resolve 405

Image deleted but page not refreshed ajax laravel

Hi there I am having a problem when I click button delete it deletes the folder with image inside and that is what I want but the page it is not refreshed so I do not know that is deleted till I click refresh
this is the code:
#if($question->question_image)
<img src="{{url('/')}}/images/questions/{{ $question->id }}/medium/{{ $question->question_image }}" class="answer-image-create" id="question_image_box">
<input onchange="readquestionURL(this);" type="file" id="question_file" name="question_image" style="display:none"/>
#else
<img src="{{ asset('noavatars/no-image-selected.png') }}" class="answer-image-create" id="question_image_box">
<input onchange="readquestionURL(this);" type="file" id="question_file" name="question_image" style="display:none"/>
#endif
</div>
{{-- <button type="button" class="btn" id="question_upfile"
style="cursor:pointer; padding-left: 24px; padding-right: 15px;">
<i class="fa fa-upload" aria-hidden="true">
</i>#lang('buttons.upload_image')
</button> --}}
<button type="button" value="{{-- {{ $i }} --}}" class="btn btn-flat btn-default btn-sm delete_image" id="delete_image" title="#lang('buttons.remove_option')"><i class="fa fa-trash-o" aria-hidden="true"></i> </button>
and the javascript code is this:
<script>
$(document).on("click", "button[id=delete_image]", function(data){
var questionid = {{$question->id}};
var element = 'questions';
$.ajax({
type: "POST",
url: "{{ action('website\images\ImagesController#deleteImage') }}",
data: {
_token: "{{ csrf_token() }}",
'id':questionid,
'element' : element,
},
success: function(response) {
console.log(response);
},
error: function(response){
alert("fail");
}
});
function readquestionURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#question_image_box')
.attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
}
});
</script>
The controller is this:
public function deleteImage($element =null, $id = null){
if(request()->ajax()) {
$id = request()->input('id');
$element = request()->input('element');
if($element != null && $id != null){
Storage::disk('public')->deleteDirectory('/images/'.$element. '/'. $id);
}
return 1;
}
}
How can I achieve to delete the image and be refreshed at the same time. Can someone please help me thank you very much .
You can refresh the page using javascript
location.reload();
You'll need to add that line on your ajax's success method.

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