[symfony2]file upload via ajax? - ajax

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>

Related

I have an issue with ajax request in laravel

I need your help on the following please:
I'm working on a Q&A website with laravel and I'm trying to make a stars rating system for the answers with ajax, here is the code:
Question view page which includes the answers:
//question code here
#foreach($answers->sortByDesc('created_at') as $answer)
<div>
<p>{{$answer->body}}</p></div>
<form method="POST" onsubmit="return saveRatings(this);">
#csrf
<input type="hidden" name="answer_id" value="{{$answer->id}}">
<input type="submit"></input>
<div class="starrr"></div> // Rating stars
</form>
Script:
<script>
$(function (){
var ratings = 0;
$(".starrr").starrr().on("starrr:change" , function(event , value){
var ratings = value;
});
});
function saveRatings(form){
var answer_id = form.answer_id.value;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url : "{{route('rating')}}",
method : "POST",
data : {
answer_id:answer_id,ratings:ratings,
},
success:function(response){
alert (response);
}
});
return false;
}
</script>`
Route:
Route::post('rating', 'RatingController#store')->name('rating');
when I submit the form it doesn't direct me to the URL in the ajax request and throws an error msg :
The POST method is not supported for this route. Supported methods: GET, HEAD, PUT, PATCH, DELETE.
http://127.0.0.1:8000/questions/1

how send id in ajax for laravel

i want to run my ajax after click on one of the options in select tag. and send id of option to ajax url.
please help me . these are my codes.
#foreach($emails as $mail)
<option id="{{$mail->id}}">{{$mail->email}}</option>
#endforeach
</select>
my ajax
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.select option').on('click',function () {
var id=$('.select option:selected').attr("id");
$.ajax({
url:'/mailactive',
type:'get',
dataType:'json',
data:{id:id}
})
})
})
try to use this:
give to your select an id, for example id_select
use #id_select > option:selected in your jQuery selector instead of .select option:selected
then tell me if you still can't get the id
In Your Laravel Blade
<select id="email">
#foreach($emails as $mail)
<option id="{{ $mail->id }}"> {{ $mail->email }} </option>
#endforeach
</select>
If your Route is POST method
$(document).ready(function () {
var id = $('#email').children(":selected").attr("id");
$.post('{{ url('your_POST_route_url') }}', {
'_token': "{{ csrf_token() }}", id:id,
}, function (data) {
console.log(data); // Print your response into your console
});
});
If your Route is GET method
$(document).ready(function () {
var id = $('#email').children(":selected").attr("id");
$.get('{{ url('your_GET_route_url') }}', {
id:id,
}, function (data) {
console.log(data); // Print your response to your console
});
});
You should have return data from your GET or POST method.

Bootstrap file-input does not call the controller method in Laravel

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

Deleting record using laravel and vue js

I'm stuck in making a delete method using vue js and laravel. I tried to add a value to the href attribute using laravel resource and pass an id as a second parameter but when I click on it and display the id on console it shows the same id to all data which is incorrect.
Sample blade:
<a id="deleteRecord" data-id="{{$project->id}}" #click.prevent="deleteRecord" class="btn btn-circle btn-icon-only btn-danger" href="{{ route('projects.store', $project->id) }}">
<i class="icon-trash"></i>
</a>
Vue method:
deleteRecord: function(id) {
var dataId = $('#deleteRecord').attr('href')
console.log(dataId);
}
Inside of your method deleteRecord:
this.$http.delete(url)
.success(function(response) {
console.log(response)
})
.error(function(errors) {
console.log(error)
});
Or using axios inside of your method
axios.delete(url)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
I get it now. I'll just post it here to help others also.
deleteRecord: function(id) {
var url = "projects" + "/" + id;
$.ajax({
url: url,
type: 'DELETE',
data: { "_token": "{{ csrf_token() }}" },
success: function(response) {
//do some success stuff here..
}
});
}

ajax request to controller to update view in laravel

I can't find a working solution for this problem:
I want to update a part of my view without reloading it,
I have a form that collects the data to be passed to the controller,
the controller needs to get the data from the DB and spit out a JSON
to the view so that it can be filled with such data.
I tried to adapt this http://tutsnare.com/post-data-using-ajax-in-laravel-5/ but it's not working at all. The data collected is not reaching the controller.
My uderstanding is the javascript part in the view should listen to the click event and send a GET request to the controller, the controller checks if the data is sent through AJAX, gets the data from DB then returns the response in JSON form, the view is then updated.
Please, does anyone have a working example or can explain?
Simple working example using JQuery:
In you routes.php file:
Route::post('/postform', function () {
// here you should do whatever you need to do with posted data
return response()->json(['msg' => 'Success!','test' => Input::get('test')]);
});
and in your blade view file:
<form method="POST" action="{{ url('postform') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<input type="text" name="test" value="" />
<input type="submit" value="Send" />
</form>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function ($) {
$(document).ready(function()
{
var form = $('form');
form.submit(function(e){
e.preventDefault();
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: form.serialize(),
success: function(data)
{
console.log(data);
if(data.msg){
alert( data.msg + ' You said: ' + data.test);
}
}
})
});
});
});
</script>
As you can see, most of the logic is done in JavaScript which has nothing to do with Laravel. So if that is not understandable for you, I'd recommend to look for jQuery ajax tutorials or rtfm :)
I have experienced submitting a modal form without reloading the entire page. I let the user add option to the dropdown and then repopulate the items on that dropdown without reloading the entire page after and item is added.
you can have custom route to your controller that handles the process and can be called by javascript and will return json
Route::get('/profiles/create/waterSource',function(){
$data = WaterSource::orderBy('description')->get();
return Response::json($data);
});
then the javascript
<script>
$(document).on('submit', '.myForm-waterSource', function(e) {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(html) {
$.get('{{ url('profiles') }}/create/waterSource', function(data) {
console.log(data);
$.each(data, function(index,subCatObj){
if (!$('#waterSource option[value="'+subCatObj.id+'"]').length) {
$('#waterSource').append('<option value="'+subCatObj.id+'">'+subCatObj.description+'</option>');
}
});
$('#myModal-waterSource').modal('hide');
$('#modal-waterSource').val('');
});
}
});
e.preventDefault();
});
</script>
You can view the full tutorial at Creating new Dropdown Option Without Reloading the Page in Laravel 5

Resources