Last active
August 29, 2015 13:56
-
-
Save tanmaypatel/9086979 to your computer and use it in GitHub Desktop.
Uploading files using AJAX
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Library used: http://malsup.com/jquery/form/ | |
define(['jquery', | |
'amplify', | |
'moment'], | |
function($, amplify, moment, undefined) | |
{ | |
var UPLOAD_SERVICE_BASE = 'http://127.0.0.1:8080/'; | |
var FileUploadService = function(){}; | |
FileUploadService.uploadFileInForm = function(formObject, param1, param2) | |
{ | |
var requestParameters = {}; | |
var uploadFilePromise = $.Deferred(); | |
$(formObject).attr('action', UPLOAD_SERVICE_BASE + '/uploadFile?parameter1=' + param1 + '¶meter2=' + param2); | |
$(formObject).ajaxForm({ | |
success: function(response, textStatus, xhr, form) | |
{ | |
if(textStatus=='success') | |
{ | |
uploadFilePromise.resolve({ | |
result: textStatus | |
}); | |
} | |
}, | |
error: function(xhr, textStatus, errorThrown) | |
{ | |
uploadFilePromise.reject({ | |
error: textStatus | |
}); | |
} | |
}); | |
$(formObject).submit(); | |
return uploadFilePromise.promise(); | |
} | |
return FileUploadService; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
define(['backbone', | |
'underscore', | |
'jquery', | |
'services/FileUploadService'], | |
function(Backbone, _, $, FileUploadService) | |
{ | |
/* .......... */ | |
var uploadPromise = FileUploadService.uploadFileInForm($("#formWithFile"), "parameter", "parameter"); | |
uploadPromise.done(_.bind(function(data) | |
{ | |
var successMessage = "File Uploaded Successfully."; | |
amplify.publish('showsuccessnotification', { | |
message: successMessage | |
}); | |
}, this)); | |
uploadPromise.fail(_.bind(function(error) | |
{ | |
var errorMessage = "File Cannot be Uploaded. Please Try again."; | |
amplify.publish('showerrornotification', { | |
message: errorMessage | |
}); | |
}, this)); | |
uploadPromise.always(_.bind(function() | |
{ | |
// Hide loader | |
}, this)); | |
/* .......... */ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment