Rails Flash Notice Via Ajax after completed method - javascript

I want to have a flash notice sent back to my view via ajax when my controller successfully completed an uploaded file. However I don't know exactly how to handle the response from the server. What I have below is what I believe is very close to what I want but it's not quite working. Any help would be greatly appreciated. Thank you!
My Controller
def import
begin
Thread.new do
Order.import(params[:file])
ActiveRecord::Base.connection.close
end
rescue
redirect_to root_url, notice: "Invalid CSV file format."
end
format.js { flash.now[:notice] = "Here is my flash notice" }
end
My Ajax Javascript
$(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('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);
},
complete: function(xhr) {
status.html(xhr); //I think I need to change this but not sure what to
}
});
});

def import
begin
Thread.new do
Order.import(params[:file])
ActiveRecord::Base.connection.close
end
rescue
redirect_to root_url, notice: "Invalid CSV file format."
end
#notice = "Here is my flash notice"
end
$(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('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);
},
complete: function(response) {
// replace the response in the div which displays notice
status.html(response)
}
});
});

Related

How to send one or more data through jquery.ajax

I copied this code from stackoverflow it working fine when i upload multiple file through it. but i cannot send other parameter with it . it only upload the file but dont send the other parameter. i tried different way but i am unable to send the data.
My code is below but i dont send the second parameter of NewDir:foldername to my php file
This is my javascript code///////////
function OnProgress(event, position, total, percentComplete){
//Progress bar
console.log(total);
$('#pb').width(percentComplete + '%'); //update progressbar percent complete
$('#pt').html(percentComplete + '%'); //update status text
}
$(document).ready(function(){
$('#files').change(function(){
var files = $('#files')[0].files;
var foldername = $('#Reciter_Name').val();
var error = '';
var form_data = new FormData();
var bar = $('.bar');
var status = $('#status');
var percent = $('.percent');
if(foldername == ''){
alert("Your Don't enter any name");
return false;
}
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['mp3']) == -1)
{
error += "Invalid " + count + " Mp3 File"
}
else
{
form_data.append("files[]", files[count]);
}
}
if(error == '')
{
$.ajax({
url:"<?php echo base_url(); ?>index.php/admin/upload", //base_url()
return http://localhost/tutorial/codeigniter/
method:"POST",
data:{form_data,NewDir:foldername},
contentType:false,
cache:false,
processData:false,
beforeSend:function()
{
// $('#uploaded_files').html("<label class='text-success'>Uploading...</label>");
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(data)
{
$('#uploaded_files').html(data);
$('#files').val('');
}
})
}
else
{
alert(error);
}
});
});
This is my php code given below///////////
function upload()
{
sleep(3);
if($_FILES["files"]["name"] != '')
{
$output = '';
$config["upload_path"] = './uploads/audio/';
$config["allowed_types"] = 'mp3';
$config["overwrite"] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
for($count = 0; $count<count($_FILES["files"]["name"]); $count++)
{
$_FILES["file"]["name"] = $_FILES["files"]["name"][$count];
$_FILES["file"]["type"] = $_FILES["files"]["type"][$count];
$_FILES["file"]["tmp_name"] = $_FILES["files"]["tmp_name"][$count];
$_FILES["file"]["error"] = $_FILES["files"]["error"][$count];
$_FILES["file"]["size"] = $_FILES["files"]["size"][$count];
if($this->upload->do_upload('file'))
{
$data = $this->upload->data();
$output .= '
<input type="hidden" name="url[]" value="'.base_url().'uploads/audio/'.$data["file_name"].'" />
<input type="hidden" name="surahname[]" value="'.$data["file_name"].'" />
'.$data["file_name"].'
';
}
}
}
echo $output;
}
So please tell me how i can pass data from php file.
/////////////////////////////////////////////////////////////////
You just need to add
form_data.append('NewDir',foldername);
Before assign form_data to ajax data variable

Upload progress bar inside modal not working when ajax call

I have page where drag and drop upload works , When drag and dropped it opens a modal which has progress bar. The drag and drop functionality works well. When the file is dropped the modal is opened but the progress bar doesn't seem to increase at all. Even after the success response of the ajax call the the progress bar is still the same.
<div class="modal-body">
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
</div>
Here is my Jquery
$("html").on("drop", function(e) {
e.preventDefault();
e.stopPropagation();
$('#myModal').modal('show');
var dt = e.dataTransfer || (e.originalEvent && e.originalEvent.dataTransfer);
var files = e.target.files || (dt && dt.files);
if (files) {
for(var i = 0; i<e.originalEvent.dataTransfer.files.length;i++){
var file_ext = e.originalEvent.dataTransfer.files[i].name.split('.').pop();
console.log(file_ext);
if ((file_ext == 'pdf') || (file_ext == 'docx') || (file_ext == 'txt')) {
console.log('right file');
var resume = e.originalEvent.dataTransfer.files[i];
var resume_name = resume.name;
console.log(resume_name);
var form_data = new FormData();
form_data.append("resume",resume);
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$.ajax({
url : '/resume_upload',
type : 'POST',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
mimeType: "multipart/form-data",
data : form_data,
beforeSend: function() {
$('#myModal').modal('show');
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(data) {
$('#myModal').modal('hide');
console.log(data.msg);
//alert(data.msg);
},
processData : false,
contentType : false,
error : function(xhr ,status ,error){
console.log(xhr);
alert(xhr);
}
});
}
And how do i create multiple progress divs when more than one file is dropped.

how to run the following function jquery with a button?

The truth is that very little jquery, and I have the following jquery code with django and what it does is this.
to select the file:
<input id="chunked_upload" type="file" name="the_file">
the following jquery code is automatically executed
<script type="text/javascript">
var md5 = "",
csrf = $("input[name='csrfmiddlewaretoken']")[0].value,
form_data = [{"name": "csrfmiddlewaretoken", "value": csrf}];
function calculate_md5(file, chunk_size) {
var slice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
chunks = chunks = Math.ceil(file.size / chunk_size),
current_chunk = 0,
spark = new SparkMD5.ArrayBuffer();
function onload(e) {
spark.append(e.target.result); // append chunk
current_chunk++;
if (current_chunk < chunks) {
read_next_chunk();
} else {
md5 = spark.end();
}
};
function read_next_chunk() {
var reader = new FileReader();
reader.onload = onload;
var start = current_chunk * chunk_size,
end = Math.min(start + chunk_size, file.size);
reader.readAsArrayBuffer(slice.call(file, start, end));
};
read_next_chunk();
}
$("#chunked_upload").fileupload({
url: "{% url 'api_chunked_upload' %}",
dataType: "json",
maxChunkSize: 100000, // Chunks of 100 kB
formData: form_data,
add: function(e, data) { // Called before starting upload
$("#messages").empty();
// If this is the second file you're uploading we need to remove the
// old upload_id and just keep the csrftoken (which is always first).
form_data.splice(1);
calculate_md5(data.files[0], 100000); // Again, chunks of 100 kB
data.submit();
},
chunkdone: function (e, data) { // Called after uploading each chunk
if (form_data.length < 2) {
form_data.push(
{"name": "upload_id", "value": data.result.upload_id}
);
}
$("#messages").append($('<p>').text(JSON.stringify(data.result)));
var progress = parseInt(data.loaded / data.total * 100.0, 10);
/*$("#progress").text(Array(progress).join("=") + "> " + progress + "%");*/
$('#progress .progress-bar').css('width',progress + '%');
$('#progress .progress-bar').css('aria-valuenow',progress + '%');
},
done: function (e, data) { // Called when the file has completely uploaded
$.ajax({
type: "POST",
url: "{% url 'api_chunked_upload_complete' %}",
data: {
csrfmiddlewaretoken: csrf,
upload_id: data.result.upload_id,
md5: md5
},
dataType: "json",
success: function(data) {
$("#messages").append($('<p>').text(JSON.stringify(data)));
}
});
},
});
</script>
this code upload the file into several pieces with a progress bar. The problem is that I want the code to run only if I click a button to load and not how.
I tried as follows:
<input id="chunked_upload" type="file" name="the_file">
<button id="enviar">Enviar</button>
<script type="text/javascript">
var md5 = "",
csrf = $("input[name='csrfmiddlewaretoken']")[0].value,
form_data = [{"name": "csrfmiddlewaretoken", "value": csrf}];
function calculate_md5(file, chunk_size) {
var slice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
chunks = chunks = Math.ceil(file.size / chunk_size),
current_chunk = 0,
spark = new SparkMD5.ArrayBuffer();
function onload(e) {
spark.append(e.target.result); // append chunk
current_chunk++;
if (current_chunk < chunks) {
read_next_chunk();
} else {
md5 = spark.end();
}
};
function read_next_chunk() {
var reader = new FileReader();
reader.onload = onload;
var start = current_chunk * chunk_size,
end = Math.min(start + chunk_size, file.size);
reader.readAsArrayBuffer(slice.call(file, start, end));
};
read_next_chunk();
}
$('button#enviar').click(function(){
$("#chunked_upload").fileupload({
url: "{% url 'api_chunked_upload' %}",
dataType: "json",
maxChunkSize: 100000, // Chunks of 100 kB
formData: form_data,
add: function(e, data) { // Called before starting upload
$("#messages").empty();
// If this is the second file you're uploading we need to remove the
// old upload_id and just keep the csrftoken (which is always first).
form_data.splice(1);
calculate_md5(data.files[0], 100000); // Again, chunks of 100 kB
data.submit();
},
chunkdone: function (e, data) { // Called after uploading each chunk
if (form_data.length < 2) {
form_data.push(
{"name": "upload_id", "value": data.result.upload_id}
);
}
$("#messages").append($('<p>').text(JSON.stringify(data.result)));
var progress = parseInt(data.loaded / data.total * 100.0, 10);
/*$("#progress").text(Array(progress).join("=") + "> " + progress + "%");*/
$('#progress .progress-bar').css('width',progress + '%');
$('#progress .progress-bar').css('aria-valuenow',progress + '%');
},
done: function (e, data) { // Called when the file has completely uploaded
$.ajax({
type: "POST",
url: "{% url 'api_chunked_upload_complete' %}",
data: {
csrfmiddlewaretoken: csrf,
upload_id: data.result.upload_id,
md5: md5
},
dataType: "json",
success: function(data) {
$("#messages").append($('<p>').text(JSON.stringify(data)));
}
});
},
});
})
The problem I have to do with this method is that:
I must first click and then I select the file.
and should be reversed where must first select the file and then click to work.
need councils how to do it please
Create a Button into your template and replace:
data.submit();
by:
$("#SubmitButtonid").off('click').on('click', function () {
data.submit();
});

AJAX drag and drop

I have created an AJAX drag and drop file upload form. But when the upload is complete it shows file upload done. But I want it to be redirected to another page. How can I do this?
This is my code
function sendFileToServer(formData,status)
{
var uploadURL ="upload.php"; //Upload URL
var extraData ={}; //Extra Data.
var jqXHR=$.ajax({
xhr: function()
{
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload)
{
xhrobj.upload.addEventListener('progress', function(event)
{
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable)
{
percent = Math.ceil(position / total * 100);
}
status.setProgress(percent);
}, false);
}
return xhrobj;
},
url: uploadURL,
type: "POST",
contentType:false,
processData: false,
cache: false,
data: formData,
success: function(data){
status.setProgress(100);
$("#status1").append("File upload Done<br>");
}
});
status.setAbort(jqXHR);
}
To redirect to another page, use window.location.
window.location = "http://www.yoururl.com";

jQuery .text() does not appear in html, but in console.log

I have this line of code
$('.bartext').text(percentComplete + "%");
In the html it renders like
<p class="bartext text" style="font-size: 14.020371290794092px;"></p>
But the console.log of
console.log($('.bartext').text(percentComplete + "%"));
says
[p.bartext text, prevObject: x.fn.x.init[1], context: document, selector: ".bartext", jquery: "1.10.2", constructor: function…]
With outerHTML of
"<p class="bartext text" style="font-size: 14.020371290794092px;">100%</p>"
And outerText of
"100%"
EDIT: The whole part
$.ajax({
xhr: function()
{
var XHR = new window.XMLHttpRequest();
XHR.addEventListener('progress', function(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
console.log(percentComplete);
$('.bar').css('width', (percentComplete * 2));
$('.bartext').text(percentComplete + "%");
}
}, false);
return XHR;
},
type: 'GET',
url: page,
data: {ajax : 1},
success: function(data) {
$('.content').empty().append(data);
}
});
What is going on?
Thank you!!!
:D
use $('.bartext').html(percentComplete + "%");
Are you shure, that percentComplete has a value
?

Categories