How to upload file using Ajax and Rails

Javascript, jQuery, Ruby, Ruby on Rails, 2016-02-12 10:58:00 UTC

In this case, we need a plugin 

 

<form id="the_form" action="/page/gambars/form_upload" method="post" enctype="multipart/form-data">
<div>
File<br />
<input name="gambar[gambar_name]" />
</div>
<div>
<button type="submit">Unggah</button>
</div>
</form>
<div class="progress" style="padding: 10px;">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
 
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
  
$('form#the_form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal);
percent.html(percentVal);
$('#page_gambars_grid').datagrid('reload');
},
complete: function(xhr) {
status.html(xhr.responseText);
$('#page_gambars_grid').datagrid('reload');
}
}); 
})(); 
</script>

 


Share: