ajaxfileupload problemajaxFileUpload is not a function - ajax

I am using ajaxfileupload to upload file , whenever i upload the file it gives me this error . I tried alot to fix it but no luck .
TypeError: $.ajaxFileUpload is not a function
success: function (data, status)
Here is code my code .
$id =$("#id").val();
$.ajaxFileUpload
(
{
type: "POST",
url: "main_page/save_image_data",
secureuri:false,
fileElementId:'userfile'+id,
dataType: 'json',
data: { "image_id":id},
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
},
/*error: function (data, status, e)
{
alert(e);
}*/
}
)
return false;

There is no command $.ajaxFileUpload in the core of jQuery.
So you are probably trying to use an external library and you have not included it in your <head> .

This can be happened if you have include jquery.min.js inside your page.After remove that file problem will be solved.

add this to your file. this method is removed form upper version of jquery.
jQuery.extend({
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error )
s.error( xhr, status, e );
// If we have some XML response text (e.g. from an AJAX call) then log it in the console
else if(xhr.responseText)
console.log(xhr.responseText);
}
});

this is my solution-----Follow the format of the official:
<script type="text/javascript">
$(document).ready(function() {
var interval;
function applyAjaxFileUpload(element) {
$(element).AjaxFileUpload({
action: "MyJsp.jsp",
onChange: function(filename) {
// Create a span element to notify the user of an upload in progress
var $span = $("<span />")
.attr("class", $(this).attr("id"))
.text("Uploading")
.insertAfter($(this));
$(this).remove();
interval = window.setInterval(function() {
var text = $span.text();
if (text.length < 13) {
$span.text(text + ".");
} else {
$span.text("Uploading");
}
}, 200);
},
onSubmit: function(filename) {
// Return false here to cancel the upload
/*var $fileInput = $("<input />")
.attr({
type: "file",
name: $(this).attr("name"),
id: $(this).attr("id")
});
$("span." + $(this).attr("id")).replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
return false;*/
// Return key-value pair to be sent along with the file
return true;
},
onComplete: function(filename, response) {
window.clearInterval(interval);
var $span = $("span." + $(this).attr("id")).text(filename + " "),
$fileInput = $("<input />")
.attr({
type: "file",
name: $(this).attr("name"),
id: $(this).attr("id")
});
if (typeof(response.error) === "string") {
$span.replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
alert(response.error);
return;
}
$("<a />")
.attr("href", "#")
.text("x")
.bind("click", function(e) {
$span.replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
})
.appendTo($span);
}
});
}
applyAjaxFileUpload("#demo1");
});
</script>
at least ,no more this error. And the action will receive the request

Related

AJAX error return ModelState Error

On my Create page I am using ajax and calling my api controller when creating a person:
<script>
$(document).ready(function() {
var newUrl = '#Url.Action("Index", "PersonInformations")';
var settings = {};
settings.baseUri = '#Request.ApplicationPath';
var infoGetUrl = "";
if (settings.baseUri === "/ProjectNameOnServer") {
infoGetUrl = settings.baseUri + "/api/personinformations/";
} else {
infoGetUrl = settings.baseUri + "api/personinformations/";
}
$("#Create-Btn").on("click",
function(e) {
$("form").validate({
submitHandler: function () {
e.preventDefault();
$.ajax({
method: "POST",
url: infoGetUrl,
data: $("form").serialize(),
success: function () {
toastr.options = {
onHidden: function () {
window.location.href = newUrl;
},
timeOut: 3000
}
toastr.success("Individual successfully created.");
},
error: function (jqXHR, textStatus, errorThrown) {
var status = capitalizeFirstLetter(textStatus);
var error = $.parseJSON(jqXHR.responseText);
//console.log(jqXHR.responseText);
toastr.error(status + " - " + error.message);
}
});
}
});
});
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
});
</script>
Here is the method in my PersonInformations API controller:
[ResponseType(typeof(PersonInformation))]
public IHttpActionResult PostPersonInformation(PersonInformation personInformation)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var lstOfPersons = db.PersonInformations.Where(x => x.deleted == false).ToList();
if (lstOfPersons.Any(
x =>
x.FirstName == personInformation.FirstName && x.LastName == personInformation.LastName &&
x.AId == personInformation.AgencyId && x.ID != personInformation.ID))
{
ModelState.AddModelError("", "This person already exists!");
return BadRequest(ModelState);
}
if (
lstOfPersons.Any(
x => x.Email.ToLower() == personInformation.Email.ToLower() && x.ID != personInformation.ID))
{
ModelState.AddModelError(personInformation.Email, "This email already exists!");
return BadRequest(ModelState);
}
personInformation.FirstName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(personInformation.FirstName);
personInformation.LastName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(personInformation.LastName);
db.PersonInformation.Add(personInformation);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = personInformation.ID }, personInformation);
}
Now when I test this and purposely enter an email that already exists, the ajax request errors out but returns the message:
Error - The Request is invalid
but when I use console.log(jqXHR.responseText)
I get this:
Create
{
"$id": "1",
"message": "The request is invalid.",
"modelState": {
"$id": "2",
"test#test.com": [
"This email already exists!"
]
}
}
How do I get the "This email already exists!" as the error message?
I just figured this out. I know that the modelState was an array type, and the 2nd value was the actual email address entered.
So I edited my button.click event to this:
$("#Create-Btn").on("click",
function(e) {
$("form").validate({
submitHandler: function () {
e.preventDefault();
var emailValue = $("#Email").val();
$.ajax({
method: "POST",
url: infoGetUrl,
data: $("form").serialize(),
success: function () {
toastr.options = {
onHidden: function () {
window.location.href = newUrl;
},
timeOut: 3000
}
toastr.success("Individual successfully created.");
},
error: function (jqXHR, textStatus, errorThrown) {
var status = capitalizeFirstLetter(textStatus);
var error = $.parseJSON(jqXHR.responseText);
toastr.error(status + " - " + error.modelState[emailValue]);
}
});
}
});
});
Find the error message via array bracket notation along with getting the actual value of the email trying to be submitted did the trick.

Blueimp jQuery File Upload Audio/Video Preview

After some googling, I cant find an example of using the audio & video preview extensions of the jQuery file upload plugin.
http://blueimp.github.io/jQuery-File-Upload/
Has anyone used these who can provide a minimal example?
you just have to add the jquery.fileupload-video file when you use the plugin for upload your videos. This is how I use it
$(function () {
'use strict';
var url = YourURL+"public/server/php/";
$('#fileupload').fileupload({
url: url,
method: 'POST',
dataType: 'json',
autoUpload: true,
acceptFileTypes: /(\.|\/)(mp4)$/i,
maxFileSize: 40000000, // 40 MB
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 300,
previewMaxHeight: 200,
previewCrop: true,
}).on('fileuploadadd', function (e, data) {
data.context = $('<div class="col-md-3 videopreview" />').appendTo('#files');
$.each(data.files, function (index, file) {
var node = $('<p/>');
if (!index) {
node
.append('<br>')
}
node.appendTo(data.context);
});
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append($('<span class="text-danger"/>').text(file.error));
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
if (file.url) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link).append($('<span/>').text(file.name));
$( "#filesHidden" ).append( '<input type="hidden" name="images[]" value="' + file.name + '">' );
} else if (file.error) {
var error = $('<span class="text-danger"/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
}
});
}).on('fileuploadfail', function (e, data) {
$.each(data.files, function (index, file) {
var error = $('<span class="text-danger"/>').text('File upload failed.');
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
Also remember to add the following
jquery.ui.widget.js
load-image.min.js
jquery.iframe-transport.js
jquery.fileupload.js
jquery.fileupload-validate-es_ES.js //This is just for the language
jquery.fileupload.css

jQuery Form plugin doesn't calls Method in IE 8

I am trying to upload files to server, but when i am submitting form it doesn't calls ActionResult. It works in chrome, FF but not in IE. When i am removing enctype="multipart/form-data" attribute from form in IE, then it calls method, but without file uploading...
I have such input:
<input id="jqueryfileupload" type="file" name="files" data-upload-id="#documentUniqueId"
data-url="#Url.Action(MVC.Profile.Documents().AddRouteValue("documentUniqueId", documentUniqueId))" multiple>
jQuery code:
$(document).on('change', '.documents-upload-container #jqueryfileupload', function (e) {
e.preventDefault();
e.stopPropagation();
var $this = $(this);
//input itself is not in the form tag, so i am creating form here and
//submitting it this way
var formContainer = $('<form action="' + $this.data('url') + '" enctype="multipart/form-data" method="POST"></form>');
$this.appendTo(formContainer);
var contentTypeOption = $.browser.msie ? 'text/html' : 'application/json';
var iframeOption = $.browser.msie ? true : false;
var options = {
dataType: 'json',
//contentType: contentTypeOption,
//iframe: iframeOption,
method: 'POST',
success: function (response, textStatus, xhr, form) {
alert(response);
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr);
alert(textStatus);
alert(errorThrown);
},
clearForm: true
};
$(formContainer).ajaxSubmit(options);
return false;
});
There are no errors and alerts are not throwing at all in IE. Just method is not called...
Action Method:
[HttpPost]
public virtual ActionResult Documents(IEnumerable<HttpPostedFileBase> files, string documentUniqueId)
{
var result = new ContentResult();
if (files != null)
{
foreach (var item in files)
{
string docName = documentUniqueId + "_" + item.FileName;
var filename = Path.Combine(Server.MapPath("~/App_Data"), docName);
item.SaveAs(filename);
}
var docs = files.Select(x => new
{
url = Url.Action(MVC.Profile.Documents(documentUniqueId + "_" + x.FileName, x.ContentType)),
name = x.FileName,
contentType = x.ContentType,
id = documentUniqueId + "_" + x.FileName
});
result.Content = new JavaScriptSerializer().Serialize(docs);
return result;
}
result.Content = new JavaScriptSerializer().Serialize(new { success = false });
return result;
}
[HttpGet]
public virtual ActionResult Documents(string fileName, string contentType)
{
var docPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
return File(docPath, contentType);
}
I use this plugin : http://malsup.com/jquery/form/
I think you are not inserting the form in the page. that's the problem. you have to add formContainer.appendTo(container);
try this code:
$(document).on('change', '.documents-upload-container #jqueryfileupload', function (e) {
e.preventDefault();
e.stopPropagation();
var $this = $(this);
var container = $this.parents('.documents-upload-container').addClass("current-container");
var formContainer = $('<form action="' + $this.data('url') + '" enctype="multipart/form-data" method="post"></form>');
$this.appendTo(formContainer);
formContainer.appendTo(container);
var contentTypeOption = $.browser.msie ? 'text/plain' : 'application/json';
var iframeOption = $.browser.msie ? true : false;
var options = {
dataType: 'json',
contentType: contentTypeOption,
//iframe: iframeOption,
method: 'POST',
//data: { 'isIE': iframeOption },
success: function (response, textStatus, xhr, form) {
alert(response);
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr);
alert(textStatus);
alert(errorThrown);
},
clearForm: true
};
formContainer.ajaxSubmit(options);
return false;
});

jquery validation ie8 submitHandler not firing

I have this script:
var pUserName = $('#UserName'), pPassword = $('#Password'), pRememberMe = $('#RememberMe');
$(function () {
Initialize();
$('#logon button').click(function () {
$.event.trigger('AjaxButtonClick', this);
$.event.trigger('AjaxLoader', '#logon .form');
$('form#logon').valid();
});
});
function Initialize() {
returnUrl = getParameterByName('ReturnUrl');
$('form#logon').validate({
submitHandler: function (form) {
logOn(returnUrl);
},
invalidHandler: function (e, validator) {
showAnimatedStatusText($('.message'), 'Please fill in the required fields highlighted below.', 'warning');
$.event.trigger('AjaxButtonError');
$.event.trigger('AjaxLoader');
},
errorPlacement: function (error, element) {
return true;
},
highlight: function (element) {
$(element).parent().addClass("input-validation-error");
},
unhighlight: function (element) {
$(element).parent().removeClass("input-validation-error");
}
});
};
function logOn(returnUrl) {
$.ajax({
url: '/_Account/LogOn',
type: 'POST',
data: '{ "UserName": "' + pUserName.val() + '", "Password": "' + pPassword.val() + '", "RememberMe": ' + pRememberMe.is(':checked') + ', "returnUrl": "' + returnUrl + '" }',
dataType: 'text json',
contentType: 'application/json; charset=utf-8',
success: function (o) {
if (o.success) {
// Success code
$.event.trigger('AjaxButtonSuccess');
} else {
showAnimatedStatusText($('.message'), o.error, 'error');
$.event.trigger('AjaxButtonError');
}
$.event.trigger('AjaxLoader');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
showAnimatedStatusText($('.message'), 'An uncaught error has occurred, please contact your system administrator (Error code: 150).', 'error');
$.event.trigger('AjaxButtonError');
$.event.trigger('AjaxLoader');
}
});
};
this works fine in all browsers except ie8. For some reason the submitHandler is never called. If I enter incorrect data invalidHandler is called fine, but submitHandler never is.
Does anyone know why?
Cheers,
/r3plica
The problem was that using a element in ie8 does not appear to work the same way as an even if you supply . To get this working I had to change my validation script to look like this:
$('#logon').validate({
submitHandler: function () {
// Do not submit
},
invalidHandler: function (e, validator) {
showAnimatedStatusText($('.message'), 'Please fill in the required fields highlighted below.', 'warning');
$.event.trigger('AjaxButtonError');
$.event.trigger('AjaxLoader');
},
errorPlacement: function (error, element) {
return true;
},
highlight: function (element) {
$(element).parent().addClass("input-validation-error");
},
unhighlight: function (element) {
$(element).parent().removeClass("input-validation-error");
}
});
and the calling button click look like this:
$('#logon button').click(function () {
$.event.trigger('AjaxButtonClick', this);
$.event.trigger('AjaxLoader', '#logon .form');
if ($('#logon').valid()) {
logOn(returnUrl);
};
});
doing it this way fixed the issue.

Backbone collection fetch error with no information

I have a strange problem with the fetch of a backbone collection I am working with. In one particular instance of my code I perform a fetch (exactly how I do it in other areas of the code which all work fine), the fetch never seems to make it to the server and the developer tools shows the request as red with the word (canceled) in the status/text field.
I've walked this through into the backbone sync method and I see the $.ajax being built and everything looks fine. Has anyone run into this problem?
here is my code if it helps, this is a function that calls two .ashx services to first check for a file's existence then to open it. The part that isn't working for me is the "me.collection.fetch().
openDocument: function () {
var me = this,
fileId = me.model.get('id'),
userId = Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
fileRequest = '/genericHandlers/DownloadFile.ashx?id=' + fileId + '&userId=' + userId,
fileCheck = '/genericHandlers/CheckFileExistance.ashx?id=' + fileId + '&userId=' + userId;
//hide tooltip
me.hideButtonTooltips();
// Check for file existance
$.ajax({
url: fileCheck
})
.done(function (data) {
if (data && data === "true") {
document.location.href = fileRequest;
me.collection.fetch();
} else if (!!data && data === "false") {
"This file is no longer available.".notify('error');
}
})
.fail(function (data) {
"Something went wrong during the File Existance check".notify('error');
"Something went wrong during the File Existance check".log(userId, 'error', 'Docs');
});
},
my collection:
// docsCollection.js - The collection of ALL the documents available to a given user
// Document Collection
Dashboard.Collections.DocsCollection = Backbone.Collection.extend({
model: Dashboard.Models.DocumentUploadModel,
url: function () {
return 'apps/docs/Docs/' + this.userId;
},
initialize: function (options) {
this.userId = options.userId;
this.deferredFetch = this.fetch();
},
comparator: function (model) {
return -(new Date(model.get('expirationDate')));
},
getDaysSinceViewedDocuments: function () {
return this.filter(function (model) {
return model.get('daysSinceViewed') !== null;
});
},
getNewDocuments: function () {
return this.filter(function (model) {
return model.get('isNew');
});
},
getExpiredDocuments: function () {
return this.filter(function (model) {
return model.get('isExpired');
});
}
});
and my model:
Dashboard.Models.DocumentUploadModel = Backbone.Model.extend({
defaults: {
fileArray: [],
name: '',
description: '',
accesses: [],
tags: [],
expirationDate: ''
},
initialize: function () {
this.set({
userId: Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
expirationDate: (this.isNew()) ? buildExpirationDate() : this.get('expirationDate')
}, { silent: true });
function buildExpirationDate() {
var date = new Date((new Date()).getTime() + 24 * 60 * 60 * 1000 * 7),
dateString = "{0}/{1}/{2}".format(date.getMonth() + 1, date.getDate(), date.getFullYear());
return dateString;
}
},
firstFile: function () {
return this.get('fileArray')[0];
},
validate: function (attributes) {
var errors = [];
if (attributes.name === '' || attributes.name.length === 0)
errors.push({
input: 'input.txtName',
message: "You must enter a name."
});
if (attributes.description === '' || attributes.description.length === 0)
errors.push({
input: 'textarea.taDescription',
message: "You must enter a description."
});
if (errors.length > 0)
return errors;
return;
},
sync: function (method, model, options) {
var formData = new FormData(),
files = model.get("fileArray"),
$progress = $('progress'),
success = options.success,
error = options.error;
// Nothing other than create or update right now
if (method !== "create" && method !== "update")
return;
// Build formData object
formData.append("name", model.get("name"));
formData.append("description", model.get("description"));
formData.append("accesses", model.get("accesses"));
formData.append("tags", model.get("tags"));
formData.append("expirationDate", model.get("expirationDate"));
formData.append("userId", model.get("userId"));
formData.append("isNew", model.isNew());
// if not new then capture id
if (!model.isNew())
formData.append('id', model.id);
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
xhr = new XMLHttpRequest();
xhr.open('POST', '/genericHandlers/UploadDocsFile.ashx');
xhr.onload = function () {
if (xhr.status === 200) {
if (success)
success();
} else {
if (error)
error();
}
}
if ($progress.length > 0) {
xhr.upload.onprogress = function (evt) {
var complete;
if (evt.lengthComputable) {
// Do the division but if you cant put 0
complete = (evt.loaded / evt.total * 100 | 0);
$progress[0].value = $progress[0].innerHTML = complete;
}
}
}
xhr.send(formData);
},
upload: function (changedAttrs, options) {
this.save("create", changedAttrs, options);
}
});
You're assigning a value to document.location.href before you try to fetch your collection:
document.location.href = fileRequest;
me.collection.fetch();
Changing document.location.href will change the whole page and in the process, any currently running JavaScript will get shutdown so I wouldn't expect your me.collection.fetch() to ever get executed.

Resources