After uploading a file, before I save it on the disk, I'm doing some validation.
If something fails, I want to show my custom error message to the user.
I've found something sililar here Uploadify: show error message from HTTP response
How to do this in MVC 3 ?
Tony,
Taken straight from ab mvc3 app that I'm working on right now:
<script type="text/javascript">
function initupLoadify() {
$("#fileInput").uploadify({
uploader: '#Url.Content("~/scripts/swf/uploadify.swf")',
script: '#Url.Action("Upload", "Home")',
cancelImg: '#Url.Content("~/Content/cancel.png")',
auto: true,
sizeLimit: 5500000,
fileDataName: 'fileData',
//scriptData: { 'propertyId': $("#PropertyID").val() },
buttonText: 'Add Schedule',
wmode: 'transparent',
//buttonImg: '#Url.Content("~/Content/button.png")', // make nice gradient image for button
onComplete: function (event, queueId, fileObj, response) {
$("#msg").html(response);
// do something
setTimeout(2000, window.location = '#Url.Action("Index")' + '?id=' + response);
return true;
},
onCancel: function (evt, queueId, fileObj, data) {
$("#msg").html("<br />Operation cancelled");
return true;
},
onOpen: function (evt, queueId, fileObj) {
$("#msg").html("<br />Upload in progress");
return true;
},
onError: function (event, queueId, fileObj, errorObj) {
$("#msg").html(fileObj.name + " was not uploaded ");
if (errorObj.status == 404)
$("#msg").html("Could not find upload script. Use a path relative to: " + "<?= getcwd() ?>");
else if (errorObj.type === "HTTP")
$("#msg").html("error " + errorObj.type + ": " + errorObj.status);
else if (errorObj.type === "File Size")
$("#msg").html(fileObj.name + " " + errorObj.type + " Limit: " + errorObj.info / 1000 + " KB");
else
$("#msg").html("error " + errorObj.type + ": " + errorObj.text);
}
});
};
</script>
hope this helps
Here is an MVC 3 example.
If you're using versions 3.0+ use onUploadComplete instead of onComplete (realize their parameters differ).
Related
I keep getting this weird bug where when I try to set my Authorization header, I keep getting 'InvalidStateError'. Here is my code:
$("#files").kendoUpload({
async: {
saveUrl: myApiUrl + "/" + id,
autoUpload: true
},
upload: function(e) {
var xhr = e.XMLHttpRequest;
if (xhr) {
xhr.addEventListener("readystatechange", function onReady(e) {
if (xhr.readyState === 1 /* OPENED */) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
}
});
}
}
});
It turns out that IE for some reason fires the readystatechange twice for readyState==1. I dont know why but it does. Its the second time that it calls it that make it throw the error. So here is my solution:
After the first time it is called, I just remove the listener.
$("#files").kendoUpload({
async: {
saveUrl: myApiUrl + "/" + id,
autoUpload: true
},
upload: function(e) {
var xhr = e.XMLHttpRequest;
if (xhr) {
xhr.addEventListener("readystatechange", function onReady(e) {
if (xhr.readyState === 1 /* OPENED */) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
xhr.removeEventListener("readystatechange", onReady);
}
});
}
}
});
I don't know why my code is giving error while making the ajax call and not responding or working at all. I ran this on an html file. I took this function - getParameterByName() from another stackoverflow answer.tweet-container tag is down the code below outside this script and an empty division.I tried some jquery also.
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
$(document).ready(function(){
console.log("working");
var query = getParameterByName("q")
// console.log("query");
var tweetList = [];
function parseTweets(){
if (tweetList == 0){
$("#tweet-container").text("No tweets currently found.")
} else {
//tweets are existing, so parse and display them
$.each(parseTweets, function(key, value){
//console.log(key)
// console.log(value.user)
// console.log(value.content)
var tweetKey = value.key;
var tweetUser = value.user;
var tweetContent = value.content;
$("#tweet-container").append(
"<div class=\"media\"><div class=\"media-body\">" + tweetContent + "</br> via " + tweetUser.username + " | " + View + "</div></div><hr/>"
)
})
}
}
$.ajax({
url:"/api/tweet/",
data:{
"q": query
},
method: "GET",
success:function(data){
//console.log(data)
tweetList = data
parseTweets()
},
error:
function(data){
console.log("error")
console.log(data)
}
})
});
</script>
strong text
Fix the quotes to resolve your syntax error:
$("#tweet-container").append("<div class=\"media\"><div class=\"media-body\">" + tweetContent + " </br> via " + tweetUser.username + " | " + "View</div></div><hr/>")
i try to make a Facebook Style User search using elastiquent on Laravel 5.5 that autocomplete ad sugest user by typing some char in input field.
The response from Ajax call return correct object but in my js code there is probably somethings wrong.
This the elasticsearch url http://basketmapp.com/users-list?q=Paolo, and in response i can see that item is correctly fetched:
this is the js used for selectize:
$(document).ready(function () {
var topUserSearch = $('.js-user-search');
if (topUserSearch.length) {
topUserSearch.selectize({
persist: false,
maxItems: 2,
valueField: 'name',
labelField: 'name',
searchField: ['name'],
options: [],
render: {
option: function(item, escape) {
return '<div class="inline-items">' +
(item.avatar ? '<div class="author-thumb"><img src="' + escape(item.avatar) + '" alt="avatar"></div>' : '') +
'<div class="notification-event">' +
(item.first_name ? '<span class="h6 notification-friend"></a>' + escape(item.first_name) + '</span>' : '') +
'</div>';
},
item: function(item, escape) {
var label = item.first_name;
return '<div>' +
'<span class="label">' + escape(label) + '</span>' +
'</div>';
}
},
load: function(query, callback)
{
if (!query.length) return callback();
$.ajax
({
url: '/users-list',
type: 'GET',
dataType: 'json',
data:
{
q: query
},
error: function()
{
callback();
},
success: function(res)
{
callback(res.data);
}
});
}
});
}
});
need your help!
I have a aftersave on Parse cloud code. I have made changes to the table once but the aftersave hook triggers twice
1st Update (Actual update)
Input: {"object":{"addedBy":"tt","albumTitle":"ggh","approved":true,
"createdAt":"2015-12-14T03:07:27.253Z","image":
{"__type":"File","name":"tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg","url":"http://files.parsetfss.com/0accbdba-e3f2-493d-
ac70-1c6bccc367b9/tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg"},"objectId":"p4pLO70gQY","updatedAt":"2015-12-
14T03:07:37.733Z"}}
2nd Update (Shouldn't happen)
Input: {"object":{"addedBy":"tt","albumTitle":"ggh","approved":true,
"createdAt":"2015-12-14T03:07:27.253Z","image":
{"__type":"File","name":"tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg","url":"http://files.parsetfss.com/0accbdba-e3f2-493d-
ac70-1c6bccc367b9/tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg"},"objectId":"p4pLO70gQY","updatedAt":"2015-12-
14T03:07:38.038Z"}}
The only difference between the two updates is the updatedAt time. Will aftersave be triggered even if the update time changes?
How can I avoid the second aftersave execution?
Here is my cloud code :
Parse.Cloud.afterSave("Photos", function (request) {
var albumNameA = "";
var publicUser = "";
var albumOwner = "";
var photoUniqueId = "";
var isApproved = "";
albumNameA = request.object.get("albumTitle");
publicUser = request.object.get("addedBy");
photoUniqueId = request.object.id;
isApproved = request.object.get("approved");
if (request.object.get("createdAt").getTime() == request.object.get("updatedAt").getTime()) {
var getAlbumOwner = new Parse.Object.extend("Albums");
var q3 = new Parse.Query(getAlbumOwner);
q3.equalTo("title", albumNameA);
q3.first({
success: function (results) {
console.log("Checking for Creator name " + results.get("creatorName"));
albumOwner = results.get("creatorName");
console.log("Uploading a Photo Final " + albumNameA + "-by-" + publicUser + "--ownedby--" + albumOwner);
console.log("Uploading a Photo" + albumNameA + "-by-" + publicUser + "--" + photoUniqueId + "--" + isApproved);
var install = new Parse.Object.extend("Installation");
var q2 = new Parse.Query(install);
q2.equalTo("privacy", privateUserNo);
q2.equalTo("username", albumOwner);
q2.find({
success: function (results) {
if (!isApproved) {
Parse.Push.send({
where: q2, // Set our Installation query
data: {
alert: "New Photo uploaded by " + publicUser + " ,waiting for approval"
}
}, {
success: function () {
// Push was successful
console.log("Push success");
},
error: function (error) {
// Handle error
console.log("Push error");
}
})
}
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
} else if (!(request.object.get("createdAt").getTime() == request.object.get("updatedAt").getTime())) {
console.log("all case scenarios");
var getAlbumOwner1 = new Parse.Object.extend("Albums");
var q6 = new Parse.Query(getAlbumOwner1);
q6.equalTo("title", albumNameA);
q6.first({
success: function (results) {
albumOwner = results.get("creatorName");
var sendApproval = new Parse.Object.extend("Photos");
var q4 = new Parse.Query(sendApproval);
q4.descending("updatedAt");
q4.first({
success: function (results) {
var objectIDNeeded = results.id;
var isChanged = results.get("approved");
var currentUpdateTime = results.get("updatedTime");
console.log("Your Photo, " + publicUser + " ,has been approved by " + albumOwner);
var install = new Parse.Object.extend("Installation");
var q5 = new Parse.Query(install);
q5.equalTo("privacy", privateUserNo);
q5.equalTo("username", publicUser);
q5.find({
success: function (results) {
Parse.Push.send({
where: q5, // Set our Installation query
data: {
alert: "Your Photo has been approved by " + albumOwner
}
}, {
success: function () {
// Push was successful
console.log("Push success");
},
error: function (error) {
// Handle error
console.log("Push error");
}
})
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
}
});
i'am using the Barcode Scanner for phonegap build, How would i retrieve the QR Codes URL data and display the webpage into a Iframe or div
$(document).ready(function(e) {
$("#scanner_mode").click(function() {
cordova.plugins.barcodeScanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
function (error) {
alert("Scanning failed: " + error);
}
);
});
});
Right i have tried this but its not working, so how would i get the src of a iframe to load result.text url
$(document).ready(function(e) {
$("#scanner_mode").click(function() {
cordova.plugins.barcodeScanner.scan(
function (result) {
document.getElementById("frame").src = result.text;
},
function (error) {
alert("Scanning failed: " + error);
}
);
});
});
yep so its working :)
$(document).ready(function(e) {
$("#scanner_mode").click(function() {
cordova.plugins.barcodeScanner.scan(
function (result) {
document.getElementById("frame").src = result.text;
},
function (error) {
alert("Scanning failed: " + error);
}
);
});
});
that works :)