How to use jquery of cloudinary to display success message - javascript

I am using cloudinary Upload widget to upload multiple image. I am success on uploading the images to cloudinary but I am not able to show success message after process is completed.I have used following javascript to upload multiple images.
<script src="//widget.cloudinary.com/global/all.js" type="text/javascript"></script>
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script type="text/javascript">
document.getElementById("upload_widget_opener").addEventListener("click", function() {
cloudinary.openUploadWidget({ cloud_name: 'shreeya', upload_preset: 'album_widget', tags: '{{ uploadTag }}' },
function(error, result) { console.log(error, result) });
}, false);
</script>
In the documentation, these is given how to show success message after upload process is completed .The given code in documentation how to show success is given below
$(document).on('cloudinarywidgetsuccess', function(e, data)
{
console.log("Global success", e, data);
});
Now ,I need help how to use this jquery code to show message after image upload process is completed.

According to the documentation of cloudinary in your question only, you can use the following:
<!-- Just make the placeholder for message (anywhere on the necessary place in the document)-->
<!-- like -->
<span id="fileResponce"></span>
Then you can use the same event provided by cloudinary:
$(document).on('cloudinarywidgetsuccess', function(e, data) {
$('#fileResponce').text('Files uploaded successfully..!'); //and append the message in the placeholder span
});

You've already got an event listener setup for when the files are uploaded. That's this line:
function(error, result) { console.log(error, result) }
You just need to extend that to check what the result is
document.getElementById("upload_widget_opener").addEventListener("click", function() {
cloudinary.openUploadWidget({
cloud_name: 'shreeya',
upload_preset: 'album_widget',
tags: '{{ uploadTag }}'
},
function(error, result) {
if (result && result.event === 'success') {
console.log("Global success", result);
}
if (error) {
console.log("Error", error);
}
}
);
}, false);
See:
https://cloudinary.com/documentation/upload_widget#cloudinary_createuploadwidget_options_resultcallback
cloudinary.createUploadWidget(options, resultCallback)
resultCallback is an optional function called for event handling. The
callback method has the following signature function(error, result)
where error is either null if successful or an error message if there
was a failure, while result is a JSON object detailing the triggered
event.

Related

"can't access property "getAuthInstance", gapi.auth2 is undefined" error while trying to use YouTube data API

so I'm kinda new to API and stuffs like this. Recently I've got a task to list videos from a specific Youtube channel. So the workaround I got is to first collect the id of uploads playlist, then get all videos from that playlist to show them. But the thing is I couldn't go so far, I first got the code from Googles API documentation, did some edits (my api key and stuff like this) and when I run I get this error:
Uncaught TypeError: can't access property "getAuthInstance", gapi.auth2 is undefined
here's the code i'm using (i'll delete my API Key, so don't think its the error):
<script src="https://apis.google.com/js/api.js"></script>
<script>
/**
* Sample JavaScript code for youtube.channels.list
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#javascript
*/
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({
scope: "https://www.googleapis.com/auth/youtube.readonly"
})
.then(function() {
console.log("Sign-in successful");
},
function(err) {
console.error("Error signing in", err);
});
}
function loadClient() {
gapi.client.setApiKey("my API key was here");
return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
.then(function() {
console.log("GAPI client loaded for API");
},
function(err) {
console.error("Error loading GAPI client for API", err);
});
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.youtube.channels.list({
"part": [
"contentDetails"
],
"id": [
"My Channel ID was here"
]
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) {
console.error("Execute error", err);
});
}
/*gapi.load("client:auth2", function() {
gapi.auth2.init({
client_id: "YOUR_CLIENT_ID"
});
});*/
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>
from the looks of the error it seea ms to me that there's problem with api.js library or maybe there supposed to be another function I need to execute before calling getAuthInstance. I don't have any idea what is happening so hopefully someone can explain to me what is happening, thanks
I don't know much about this stuff myself so I went to the docs and found this section for you:
https://developers.google.com/identity/sign-in/web/reference#gapiauth2getauthinstance
Turns out you need to initialise auth first - the bit you've commented out at the bottom of your code:
/*gapi.load("client:auth2", function() {
gapi.auth2.init({
client_id: "YOUR_CLIENT_ID"
});
});*/
Give that a test and see what you get :D

Loading undefined number of file contents with ajax by config only one sucess listener

i have a json config that has a array of objects, containing file names. and i need to load them in a row and have a event when all files are ready loaded for displaying them as code snippet on my homepage.
config.json:
{
"author": "TypedSource",
"date": "2017-04-16",
"files": [
{
"lang": "HTML",
"fileName": "sample.html.txt"
},
{
"lang": "PHP",
"fileName": "sample.php.txt"
},
]
}
TypeScript code:
$(document).ready(function(){
$.get('config.json')
.ready(function(data){
console.log('success on loading config');
$.when(
// i want to load every file here
// but this for can't work inside the $.when
// it is just pseudo code for explain what i want to do
for(let i = 0; i < data.files.length; i++) {
$.get(data.files[i].fileName);
}
}.then(
function(){
// success listener for all files loaded
console.log('success on loading all files');
console.log(arguments);
// now build the template for each response[0] and bind it to highlight.js code block
}
function(){
// error listener if a file can't be loaded
// ATTENTION: if an error occured, no single success is given
console.error('error on loading files');
console.log(arguments[0].responseText());
}
)
})
.fail(function(){
console.error('error on loading config file');
console.log(arguments[0].responseText);
});
});
$.get only accepts 1 url to load, $.when is the option i know, but normaly i have to assign every call inside the when by hand. does somebody know how to handle it?
Create an array of the request promises to pass to Promise.all() which won't resolve until all request promises have resolved
$.getJSON('config.json').then(function(config) {
var requests = config.files.map(function(file) {
return $.get(file.fileName);
});
Promise.all(requests).then(function(res) {
console.log(res)
res.forEach(function(txt) {
$('body').append('<p>' + txt + '</p>')
});
});
});
The order of the results array in Promise.all() will be the same as the files array order in your config file
DEMO

handle 503 error with jquery

I´m using gridfs to store images in a mongoDB. I have an issue when I update images in the background and want to update them on the screen when finished uploading. I fire an event when I have an image document stored in my mongoDB and then I update the screen. It looks like the document is created while uploading the image because if I do it this way, my image is broken with a 503 error (service not available). When I refresh the page the image appears on the screen.
I believe the problem is that I try to get the image when it is still uploading. I would like to do a $.get(imagesURL) and catch the 503 error but I don't know how to do this. If I could catch the error I could do a loop and wait until its uploaded.
Maybe you guys also have better solutions or know how to catch a 503 error using jquery?
I use a normal file input field for the image
(part of my Template Event in meteorjs)
'change #avatarForm': function (event) {
FS.Utility.eachFile(event, function (file) {
Images.insert(file, function (err, fileObj) {
if (err) {
// handle error
} else {
// handle success depending what you need to do
var userId = Meteor.userId();
var imagesURL = {
"profile.image": "/cfs/files/images/" + fileObj._id
};
Meteor.users.update(userId, {$set: imagesURL});
function checkAvatar() {
$.get(imagesURL)
.complete(function () {
Session.set("registerAvatar", "/cfs/files/images/" + fileObj._id);
}).onerror(function () {
console.log("but still uploading");
checkAvatar();
});
console.log("image saved!");
}
checkAvatar();
}
});
});
},
my code should only fire the new image on the screen (url is set as SessionVar) when the image is completed but its not working.
this is my exact error
Failed to load resource: the server responded with a status of 503 (Service Unavailable)
Something like this should work. The pattern is to set a template helper with a reactive data source - in this case, Meteor.user(). When Meteor.user() changes, the template helper will render out the new data without you having to fetch any data manually:
<template name="test">
<div>Profile Image:</div>
{{#if profileImage}}
<div><img src="{{profileImage}}"></div>
{{/if}}
</template>
Template.test.events({
'change #avatarForm': function(event) {
FS.Utility.eachFile(event, function(file) {
Images.insert(file, function(err, fileObj) {
if (err) {
// handle error
} else {
// handle success depending what you need to do
var userId = Meteor.userId();
var profileImage = {
"profile.image.url": fileObj.url(),
"profile.image.id": fileObj._id
};
Meteor.users.update(userId, {
$set: profileImage
});
}
});
});
},
});
Template.test.helpers({
profileImage: function () {
return Meteor.user().profile.image.url;
}
});

can't get Meteor slingshot to work

I am trying to get slingshot to work but having a hard time, I am attaching here the code I have.
The error I get n the console is:
"Exception in delivering result of invoking 'slingshot/uploadRequest': TypeError: Cannot read property 'response' of undefined"
client
Template.hello.events({
'change .uploadFile': function(event, template) {
event.preventDefault();
var uploader = new Slingshot.Upload("myFileUploads");
uploader.send(document.getElementById('uploadFile').files[0], function (error, downloadUrl) {
if (error) {
// Log service detailed response
console.error('Error uploading', uploader.xhr.response);
alert (error);
}
else{
console.log("Worked!");
}
});
}
});
lib
Slingshot.fileRestrictions("myFileUploads", {
allowedFileTypes: ["image/png", "image/jpeg", "image/gif"],
maxSize: null // 10 MB (use null for unlimited)
});
server
Slingshot.fileRestrictions("myFileUploads", {
allowedFileTypes: ["image/png", "image/jpeg", "image/gif"],
maxSize: null,
});
Slingshot.createDirective("myFileUploads", Slingshot.S3Storage, {
AWSAccessKeyId: "my-AWSAccessKeyId",
AWSSecretAccessKey: "my-AWSSecretAccessKey",
bucket: "slingshot-trial-2",
acl: "public-read",
authorize: function () {
//Deny uploads if user is not logged in.
},
key: function (file) {
//Store file into a directory by the user's username.
return file.name;
}
});
I saw the same issue and it was due to xhr being null - try removing the console error line that references it and I'm assuming you'll start seeing the alert with the actual error message:
console.error('Error uploading', uploader.xhr.response);
I ended up putting in a check for xhr before referencing it and then logging it if it existed.

How to prevent error alerts on Fine-Uploader?

Is there any way to prevent alerts where the onError callback is fired?
I only need to capture the error and display it in a different way
Yes, simply override the showMessage option.
For example:
var uploader = new qq.FineUploader({
request: {
endpoint: 'my/endpoint'
},
callbacks: {
onError: function(fileId, filename, reason, maybeXhr) {
//do something with the error
}
},
showMessage: function(message) {
//either include an empty body, or some other code to display (error) messages
}
});

Categories

Resources