I am new to Laravel. I am using Bootstrap file-input plugin to upload multiple files in Laravel. But in my code, url in the uploadUrl is not called. That means ajax call is not sent to the laravel backend controller and controller method is not called. Could you please help me in resolving this issue? Thank you.
HTML CODE
<div class="form-group">
<label class="col-sm-2 control-label required">FEATURED IMAGES</label>
<div class="col-sm-10">
<input id="featured-file" name="featured-file[]" type="file" multiple class="file-loading">
<p class="notice">Please use to upload 550px width x 670px height images for better view</p>
</div>
</div>
jQuery Code
$("#featured-file").fileinput({
theme: 'fa',
uploadAsync:true,
uploadUrl:"{{ url('/news/uploadimgsaddmode') }}",
uploadExtraData: function() {
return {
_token: '<?php echo csrf_token() ?>',
};
},
allowedFileExtensions: ['jpg', 'png', 'gif','jpeg'],
overwriteInitial: false,
maxFileSize:2000,
maxFilesNum: 10
}).on('fileuploaded', function(event, previewId, index, fileId) {
console.log('File Uploaded', 'ID: ' + fileId + ', Thumb ID: ' + previewId);
}).on('fileuploaderror', function(event, data, msg) {
console.log('File Upload Error', 'ID: ' + data.fileId + ', Thumb ID: ' + data.previewId);
});
Laravel Controller Method
public function uploadimagesaddmode(Request $request){
Session::put('uploaded_files','Hi');
Session::save();
return response()->json(['uploaded' =>'Hi']);
}
And I used some html code to test whether controller method is called or not
<p>#if(Session::has('uploaded_files')) {{ Session::get('uploaded_files') }} #endif</p>
If controller method is called Session values should be printed. But no value is printed.
I found a solution. Thanks for all who responded to my question :)
I edited the jQuery Code. Here's the edited one. It works for me.
$(document).on("ready", function() {
$("#featured-file").fileinput({
theme: 'fa',
allowedFileExtensions: ['jpg', 'png', 'gif','jpeg'],
uploadUrl: "{{ url('news/uploadimgsaddmode') }}",
uploadExtraData: function() {
return {
_token: '<?php echo csrf_token() ?>',
};
},
uploadAsync:true,
overwriteInitial: false,
maxFileSize:2000,
maxFilesNum: 10,
}).on("filebatchselected", function(event, files) {
$("#featured-file").fileinput("upload");
});
});
Related
i wan to be able to dlete a price whereby upon clicking the delete button a modal appears which then shows the yes or no delete buttons.here is the ajax function in the view which contains the delete button
function removeogFuelPriceModel(id)
{
$.ajax({
url: "{{route('industryfuelprice.edit.modal')}}",
type: 'post',
'headers': {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
data: {
'id': id,
},
success: function (response) {
$("#showEditInventoryModal").html(response);
$("#showMsgModal").modal('show');
},
error: function (e) {
console.log('error', e);
}
});
}
here is a div inside the modal which contains the id which redirects to the delete ajax function
<div class="row"
style="width: 100%; padding-left: 0px; padding-right: 0px;">
<div class="col col-m-12 text-center">
<button type="button"
class="btn bg-primary primary-button"
**onclick="deleteData({{$oilgas->id}})"**
data-dismiss="modal">Yes</button>
<button type="button"
class="btn btn-danger primary-button"
data-dismiss="modal">No</button>
</div>
</div>
here is the ajax function in the modal
function deleteData(id) {
const url = "{{ route('industryoilgas.destroyFuelprice', ['model_id' => "MODEL_ID"]) }}".replace("MODEL_ID", id);
$.ajax({
url: url,
method: "POST",
enctype: 'multipart/form-data',
success: function (response) {
$("#showMsgModal").modal('hide')
$("#showEditInventoryModal").html(response)
$('#showMsgModal').modal('show');
$("#addFuelPrice").attr("disabled", false);
$("#addFuelPrice").css({"cursor":"pointer;"});
loadFuelPrice();
}, error: function (e) {
console.log(e.message)
}
});
}
here are my routes
Route::post('show-industry-fuel-price-edit-modal','IndustryOilGasController#showEditModalFuelPrice')->name('industryfuelprice.edit.modal');
Route::post('delete-fuel-price/{id}', 'IndustryOilGasController#destroyFuelprice')->name('industryoilgas.destroyFuelprice');
i don't understand why am getting that error
Make sure you have defined removeogFuelPriceModel() and deleteData() within a blade component, because an Laravel helper method cannot be resolved outside a predefined php file. In this case, you are mostly defining those methods inside a JS file which won't work properly. To address this issue, you may inject those methods inside a script layout within the blade component. I wish this could help you out!
I don't understand why my AJAX submit doesn't work.
I have two forms in my the controller:
$intervento = new Intervento();
$form = $this->createForm(InterventoType::class, $intervento);
$form->handleRequest($request);
$user = new User();
$form_user = $this->createForm(UserType::class, $user);
$form_user->handleRequest($request);
if ($form_user->isSubmitted() && $form_user->isvalid()) {
$response = new Response();
return $this->json(array('risultato' => ' ok'));
}
if ($form->isSubmitted() && $form->isvalid()) { }
return $this->render('interventi/collaudo.html.twig', array(
'form' => $form->createView(),
'form_utente' => $form_user->createView(),
));
In my twig file I start the form and it works:
{{form_start(form_utente,{'attr':{'id':'form-utente'}})}}
.....
<div class="row">
<div class="input-field col s4">
<input type="submit" class="waves-effect waves-light btn-large" value="Submit">
</div>
</div>
</div>
</div>
{{form_end(form_utente)}}
</div>
In my JavaScript file:
$('#form-utente').submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert(data['risultato']);
// setTimeout(function() { window.location.href = "#" }, 500);
// setTimeout(function() { $("#form-stufa").click() }, 500);
},
error: function(){
}
});
});
I also have another AJAX call in this JavaScript, but I don't this gives the problem.
The submit button sometimes returns Error 500, sometimes an undefined alert.
I think it doesn't go to submit in the controller but I don't know why.
Can anyone help me?
Use the FOSJsRoutingBundle for js urls. You need expose your routing.
I have a problem with my search.
Problem 1
Currently if I type in the field it is searching however the search never ever stops, so if I type hello, it will make about 500 requests within a minute.
Problem 2
I am searching in film table to find matching 'title' as well as find business name corresponding to business_id in business table.
Problem 3
Each time request is made it brings back master page again i.e. loading all js and css (which might be why it is making so many requests?) but if I don't extend master, result blade doesn't work.
however even if I input 'e' it brings me back 'guardians of the galaxy' which doesn't have 'e' My thoughts are that it is searching throught business table as well somehow. They have both eloquent one to one relationships
Controller:
public function cinema_search($cinema_value) {
$cinema_text = $cinema_value;
if ($cinema_text==NULL) {
$data = Film::all();
} else {
$data = Film::where('title', 'LIKE', '%'.$cinema_text.'%')->with('business')->get();
}
return view('cinemasearch')->with('results',$data);
}
Form::
<form id="cinema_display">
<div class="form-group">
<input type="text" class="form-control" id="search_cinemas" onkeyup="search_cinema(this.value);" placeholder="Search film">
</div>
<div id="show"
</div>
</div>
</form>
ajax:
function search_cinema(cinema_value) {
$.ajax({
url: '/cinemasearch/' + cinema_value,
type: 'post',
dataType: 'html',
success: function(data) {
$('#show').append(data);
$('.se-pre-con').fadeOut('slow', function () {
$(".container").css({ opacity: 1.0 });
});
},
error: function(data) {
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
cinemasearch.blade(results):
#extends('master') #section('title', 'Live Oldham') #section('content')
#section('content')
<table style="width:100%">
#if (isset($results) && count($results) > 0)
#foreach( $results as $film )
<tr>
<td>{{ $film->business->name }}</td>
<td>{{ $film->title }}</td>
<td>{{ $film->times}}</td>
</tr>
#endforeach
#endif
</table>
#endsection
function search_data(search_value) {
$.ajax({
url: '/searching/' + search_value,
type: 'post',
dataType: 'html',
success: function(data) {
$('#show_search_result').append(data);
$('.se-pre-con').fadeOut('slow', function () {
$(".container").css({ opacity: 1.0 });
});
},
error: function(data) {
$('body').html(data);
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
function tram_stops(tram_value) {
$.ajax({
url: '/tramsearch/' + tram_value,
type: 'post',
dataType: 'html',
success: function(data) {
$("#display").html(data);
var tram_value = tram_value;
},
error: function(data) {
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
/*
setInterval(tram_stops, (30 * 1000));
*/
function search_cinema(cinema_value) {
$.ajax({
url: '/cinemasearch/' + cinema_value,
type: 'post',
dataType: 'html',
success: function(data) {
var items = JSON.parse(data);
var showElement = $('#show');
showElement.html('');
$.each(data, function() {
showElement.append(this.title +' '+ this.times+'<br />');
});
},
error: function(data) {
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
You are returning the wrong response type from cinema_search. Ajax expects a JsonResponse, not what the view helper returns which is \Illuminate\Http\Response. Put your search results in:
return response()->json(['results' => $data]);
to start with if you just want the data. If you want to actually return the rendered view file, you would need to do:
return response()->json(['results' => view('cinemasearch')->with('results',$data)->render()]);
then inject that into your DOM. The problem with rendering server side is nothing is bound client side so if you have any interaction requiring JS, you'll need to create those manually in your success callback.
Problem 1:
Remove the keyUp event in your html and add an event in Jquery.
Your HTML structure is not correct
This:
<form id="cinema_display">
<div class="form-group">
<input type="text" class="form-control" id="search_cinemas" onkeyup="search_cinema(this.value);" placeholder="Search film">
</div>
<div id="show"
</div>
</div>
</form>
Should be:
<form id="cinema_display">
<div class="form-group">
<input type="text" class="form-control" id="search_cinemas" onkeyup="search_cinema(this.value);" placeholder="Search film">
<div id="show">
</div>
</div>
</form>
Then again you should consider to remove the onkeyup event. And change add it in Jquery to something like this:
Problem 2 & 3: I would recommend a raw Query and return an json instead of a view. And you shouldn't check if($cinema_text === NULL) this won't be the case ever. Unless you put NULL in your url and even then it will be an String and not NULL and if('NULL' === NULL) returns false look at this post for the diff of == and ===.
public function cinema_search($cinema_value) {
$cinema_text = $cinema_value;
if (empty($cinema_text)) {
$data = Film::all();
} else {
$data = DB::select('*')
->from('films')
->join('businesses', 'businesses.id', '=', 'films.business_id')
->where('films.title', 'LIKE', '%'.$cinema_text.'%')
->orWhere('bussiness.title', 'LIKE', '%'.$cinema_text.'%')
->get();
}
return response()->json(['results' => $data]);
}
Then in your JavaScript do something like this:
$( document ).ready(function() {
console.log( "ready!" );
$( "#search_cinemas" ).change(function() {
search_cinema(this.value);
console.log( "New value"+this.value+"!" );
});
function search_cinema(cinema_value) {
console.log('setup ajax');
$.ajax({
url: '/cinemasearch/' + cinema_value,
type: 'post',
success: function(data) {
console.log('success!');
var showElement = $('#show');
showElement.html('');
$.each(items, function() {
showElement.append(this.title +' '+ this.times+'<br />');
});
},
error: function(data) {
console.log(data);
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
});
I am newer to ajax. I want to add two fields using ajax and codeigniter.. When i click the submit button the two fields are added but the alert message is not showing also the page is not refreshing. Can any one solve my issue.. Thanks in advance..
This is my Form
<form action="" id="suggestionsform" method="post">
<div class="form-group">
<label for="suggname">Name</label>
<input type="text" class="form-control" name="suggname" id="suggname" placeholder="Enter Your Name" required="required">
</div>
<div class="form-group">
<label for="suggmessage">Suggestion</label>
<textarea class="form-control" rows="4" name="suggmessage" id="suggmessage"
placeholder="Enter Your Suggestions"></textarea>
</div>
<button type="submit" class="btn btn-default" id="suggestions">Submit</button>
</form>
This is my ajax codeing
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(data) {
if (data=='true')
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Controller Coding
public function addSuggestion()
{
$data=array(
'name' => $this->input->post('name'),
'messages' => $this->input->post('suggestion'),
'date' => now()
);
$data=$this->Helen_model->setSuggestion($data);
echo json_encode($data);
}
Model Coding
public function setSuggestion($data){
$this->db->insert('messages', $data);
return $this->db->insert_id();
}
You can achieve like this..
Model
Return true status if insert successful.
public function setSuggestion($data){
$res = $this->db->insert('messages', $data);
if($res){
$result = array('status'=>true,'message'=>'successful');
}
else
{
$result = array('status'=>false,'message'=>'failed');
}
return $result;
}
JS
Check status in success function
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(response) {
data = eval(response);//or data = JSON.parse(response)
if (data.status ===true)
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Try to use echo '{"status": "success"}; on your controller response.
That i see on your script you are shown database response.
i would like to know if it is possible to make a file upload form and send the data via ajax with symfony2 ?
here is my twig view:
<form class="upavatar" method="post" action="{{ path('sbcUserBundle_avatar', {'id': app.security.getToken().getUser().getId()}) }}" {{ form_enctype(form) }}>
{{ form_end(form) }}
{{ form_errors(form) }}
</form>
</div>
<script>
$('.upavatar').submit(function()
{
$.post($(this).attr('action'), $(this).serialize(), function(data) {
$("#upmyavatar").empty();
$("#upmyavatar").html(data);
});
return false;
});
</script>
Because i did a form upload file within symfony2 and without ajax (jquery actually) it works like a charm, but when i try to send it trough ajax the form handler can't find the file variable (i checked with xdebug).So i'am starting to wonder if it's possible to send a file via ajax within symfony2, in the past i successfully used ajax for "normal" form.
Thanks.
ok i got it working by doing that:
<script>
$('#myForm').live('change', function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$(".myavatarupload").empty();
$(".myavatarupload").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color='red'> ERROR</font>");
}
};
$("#myForm").ajaxForm(options);
});
</script>