Cloudinary + Sails.js direct upload doesn't work - javascript

i'm trying to make cloudinary direct upload working but something in the documentation is missing... here are the steps i'm doing:
Controller:
/**
* MyaccountController
*
* #description :: Server-side logic for managing myaccounts
* #help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: 'MyCloudName',
api_key: 'MyAPIKey',
api_secret: 'MyAPISecret'
});
Now this is my layout:
<!--SCRIPTS-->
<script type="text/javascript" src="/js/dependencies/sails.io.js"></script>
<script type="text/javascript" src="/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/js/jquery.ui.widget.js"></script>
<script type="text/javascript" src="/js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="/js/jquery.fileupload.js"></script>
<script type="text/javascript" src="/js/jquery.cloudinary.js"></script>
<script src="../node_modules/cloudinary-jquery-file-upload/cloudinary-jquery-file-upload.js"></script>
<script type="text/javascript">
cloudinary.cloudinary_js_config();
var cloudinary_cors = "http://" + window.location.host + "/cloudinary_cors.html";
console.log(cloudinary_cors);
cloudinary.uploader.image_upload_tag('photo', { callback: cloudinary_cors });
$(".photo").cloudinary_fileupload();
// Using the config function
var cl = cloudinary.Cloudinary.new();
cl.config( "MyCloudName", "MyAPIKey");
/*
$.cloudinary.config({ cloud_name: 'MyCloudName', api_key: 'MyAPIKey'});
</script>
My form:
<form action="" method="post" enctype="multipart/form-data" class="upload_form">
<div class="form-group">
<label>Foto de perfil</label>
<input type="file" name="photo" id="photo" class="photo">
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Cargar</button>
</div>
</form>
I don't get why it isn't working, in the docs it says Cloudinary's jQuery plugin requires your cloud_name and additional configuration parameters to be available. Note: never expose your api_secret in public client side code.
To automatically set-up Cloudinary's configuration, include the following line in your view or layout:
cloudinary.cloudinary_js_config()
This is done...
Direct uploading from the browser is performed using XHR (Ajax XMLHttpRequest‎) CORS (Cross Origin Resource Sharing) requests. In order to support older browsers that do not support CORS, the jQuery plugin will gracefully degrade to an iframe based solution.
This solution requires placing cloudinary_cors.html in the static folder of your Node application. This file is available in the html folder of Cloudinary's Javascript library. The following code builds a URL of the local cloudinary_cors.html file:
Done...
Direct upload file tag
Embed a file input tag in your HTML pages using the image_upload_tag view helper method.
The following example adds a file input field to your form. Selecting or dragging a file to this input field will automatically initiate uploading from the browser to Cloudinary.
cloudinary.uploader.image_upload_tag('image_id', { callback: cloudinary_cors });
this is what i don't get... this is the uploader? how should i use it? and then i don't know what else to do, i'm using different docs to make it work but nothing helps... I hope anyone who did this can help me, thanks!

On controller initialize cloudinary as
var uploader = cloudinary.uploader.image_upload_tag('image_id', { callback: cloudinary_cors, html: { multiple: 1 } });
and pass it to view and render it over there,
<%-uploader%>
then use jquery to get data:
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {}
you can use this script to bind the data to some hidden fields inside your form and
cloudinary-fileupload will be generated when <%-uploader%> is rendered

In addition to CodeBean's answer, note that it seems that there are different ways of using Cloudinary that are mixed here (in the original code as was in question).
Controller
As far as it can be seen from here, the MyaccountController controller doesn't do a thing:
You're requiring "cloudinary" - presumably from npm install, which creates an instance of the jQueryless Cloudinary class.
The variable is local to the controller so has no effect on the rest of the code
View:
Only one of these lines is required (preferably the second one):
<script type="text/javascript" src="/js/jquery.cloudinary.js"></script>
<script src="../node_modules/cloudinary-jquery-file-upload/cloudinary-jquery-file-upload.js"></script>
This method returns a string with the <script> tag. The string should be then embedded in the HTML code. It is a server side code.
Here, it does nothing.
cloudinary.cloudinary_js_config();
If you're using the jQuery File Upload code, you should refer to $.cloudinary. cloudinary was never defined in your layout.
Now you're creating a jQueryless instance, which you don't use afterwards.
var cl = cloudinary.Cloudinary.new();
cl.config( "MyCloudName", "MyAPIKey");
Finally, there's an open-ended comment with the code you were supposed to use in the beginning of the whole script:
/*
$.cloudinary.config({ cloud_name: 'MyCloudName', api_key: 'MyAPIKey'});
Regardless of CodeBean's response, you still need to config $.cloudinary.

Related

How to use external html file in current html code

I am trying to load an external HTML page (common navigation) into my current HTML page. I tried the load function but it is deprecated. Can you tell me another way to include it? I am not using any server.
Here's my code
<!DOCTYPE html>
<html>
<head>
<script src="ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#content').load(" nav.html ");
});
</script>
</head>
<body>
<div id="content "></div>
</body>
</html>
Try this
<script>
function loadPage(href) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", href, false);
xmlhttp.send();
return xmlhttp.responseText;
};
document.getElementById('content').innerHTML =
loadPage('your_html_file.html');
</script>
<div id="content">
</div>
Take both file pages in same directory then you can use simple button on link to use external file. for example
<button> External file </button>
Button is your choice it's just example for understanding you can simple use html link.
You should use the SSI-function.
There is several ways but this can solve your problem.
<!--#include virtual="PathToYourFile/YourFile.html" -->
This can be inserted into a <div> for further styling in CSS.
REMEMBER! Due to some limitations in html-doctypes you cannot inlude a .html-file into an .html-file. You have to use another format as .shtml where you can inlude your .html-files. You can include .html into your .shtmlfile. This was also what .shtml was originally created for.
This is because it is part of the XHTML (Dynamic XML HTML)...
To change a file
Your approach on the HTML is correct and also your JS. I include a lot of html-files containing texts there.
My approach is that when a page is loaded some text will be loaded with the <!--#include virtual="" --> inside a <div>. Below JS is used to change the content in the <div>. As Daniel Beck stated below: "...at least in Apache the server needs to be configured to check particular file extensions...".
You configure your file in your .htaccess-file. But ONLY do this if you know what you are doing.
Some (newer?) servers have a default setup of which you don't need to alter the .htaccess-file if you want to be able to include .html-files. At least you are able to include .html-files into .shtml-files.
I have included a Mimetype converter which tells the browser how it should read the file. For txt/html I have told the script that it should use the character encoding ISO-8859-1. Others as UTF-8 could also be used. This depends on your and your receivers native language.
Take into consideration to use the e.preventDefault();. With this i tells the browser NOT to see this as navigation link and will therefore only load the content in the <div>.
$(function() {
$('#ButtonsID').click(function(e) {
$('.DivClass').load('PathToFile/File.shtml');
e.preventDefault();
});
});
$.ajaxSetup({
'beforeSend': function(xhr) {
xhr.overrideMimeType('text/html; charset=ISO-8859-1');
}
});

jQuery/ Javascript .get method for reading text files

I just started working on my school assignment with some regular expressions in Javascript. I can't seem to figure out how to actually read data from a text file into variable using jQuery method .get(). When I try my code out nothing happens. It seems like it never enters .get() section. Here is my code:
JS file:
document.getElementById('file').onchange = function(){
var file = "New Text Document.txt"; //this will later be the selected file
$.get(file,function(data){
var myVar = data;
$("#123").html(myVar);
});
};
HTML file:
<!DOCTYPE html>
<html>
<head>
<title>animacija</title>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<input type="file" name="file" id="file">
<script type="text/javascript" src="func.js"></script>
<div id="123"></div>
</body>
</html>
The code snippet seems to be ok, but it will not work locally since $.get is for ajax requests and requires full available server path.
I rather recommend you the use of FileReader API.
HTML
<title>animacija</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<body>
<input type="file" name="file" id="file">
<div id="123"></div>
</body>
JavaScript
document.getElementById('file').onchange = function() {
var file = this.files[0];
var FR = new FileReader();
FR.readAsText(file);
FR.onload = function(data) {
var myVar = data.target.result;
$("#123").html(myVar);
}
};
JSFiddle
Hope it works for you!
Most browsers will not allow file: resources to read other local files. This is to prevent attacks where a downloaded HTML document could start reading (and transmitting) the contents of your hard drive (or at least your Downloads folder) as soon as you open it.
The other thing you need to know here is that $.get is used for getting resources from an HTTP server, while file inputs are used to allow a user to select a file from their local drive. I realize in your case it's a little confusing, because your web page is on your local hard drive, but imagine if your HTML and scripts were being hosted online, and some other user (not you) was using them to process their own locally-stored files.
MDN has a good tutorial on how to get started with <input type="file"> inputs.
The code won't work locally due to cross-origin limitations.
It works fine when run on a remote server and all files are in the same folder.
If you want to read local files (aka. files selected by user through the file input) you can read more about FileAPI here:
https://www.html5rocks.com/en/tutorials/file/dndfiles/

How do i remote include a javascript file in Titanium appcelerator and use the functions of that file?

I am required to remotely include into my appcelerator project, a javascript file available at a particular link, and use the function declared in that file to process some data.
What i would like to achieve is something like the following in html -
<script src="https://some-link/Data.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var testVariable = someMethod(localdata);
});
//use testVariable as necessary
</script>
//someMethod() is declared in remotely available Data.js
I am a newb at Appcelerator and im not really able to follow some of the threads i have come across, so some detailed help would be really appreciated. Thank you in advance.
Well according to me , you should first understand few points first :
You want to include a remote file hosted at some server , now as the Titanium code converts to native code at compile time , you cannot include Titanium API's from remote file.
If you want to include a remote file , then only option which I see is loading that file in webview.
Now coming to your problem , as you said that you want to fetch some data only from remote server by triggering some JS function from remote file. So following is what would I do :-
a/ Create a hidden webview in my main window with a EventListener of webview. Something like :
var webview = Titanium.UI.createWebView({url:'localHtmlFile.html'});
//event listener to handle the response from webview
Ti.App.addEventListener('fromWebView', function(e)
{
var testVariable = e.data;
});
b/ In localHtmlFile.html file :
<!DOCTYPE html>
<html>
<body>
<script src="https://some-link/Data.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var testVariable = someMethod();
//respond the fetch data to the main window via fireEvent
Ti.App.fireEvent( 'fromWebView', { data : testVariable } );
});
</script>
</body>
</html>
PS : This is just a logic to begin with , you have to edit code according to your requirements

Prepare jquery before jquery and page load

I have recently discovered the new trend of including all .js script at the end of the page.
From what i have read so far seems pretty ok and doable with an exception.
The way I am working is using a template like:
<html>
<head>
<!-- tags, css's -->
</head>
<body>
<!-- header -->
<div id="wrapper">
<?php
include('pages/'.$page.'.php');
?>
</div>
<!-- footer -->
<!-- include all .js -->
</body>
</html>
Now, if I want to use this example on my page http://www.bootply.com/71401 , I would have to add the folowing code under my jquery inclusion.
$('.thumbnail').click(function(){
$('.modal-body').empty();
var title = $(this).parent('a').attr("title");
$('.modal-title').html(title);
$($(this).parents('div').html()).appendTo('.modal-body');
$('#myModal').modal({show:true});
});
But that would mean I either use that in every page - even if I do not have use for it, either generate it with php in the $page.'php' file and echoing it in the template file, after the js inclusion.
I am sure though, better methods exist and I don't want to start off by using a maybe compromised one.
Thanks!
Please avoid using inline scripts as they are not good maintainable and prevent the browser from caching them. Swap your inline scripts in external files.
Fore example you could put all your JavaScript in one file an check the presence of a specific element before initialize the whole code. E.g.:
$(document).ready(function(){
if($('.thumbnail').length) {
// your thumbnail code
}
});
A better way to execute "page specific" JavaScript is to work with a modular library like requirejs. You can modularize your scripts depending on their functionality (like thumbnails.js, gallery.js etc.) and then load the necessary script(s) depending e.g. on the existence of an element:
if($('.thumbnail').length) {
require(['ThumbnailScript'], function(ThumbnailScript){
ThumbnailScript.init();
});
}
The best way you can go is create a separate file for this code.
Let's name it app.js. Now you can include it under the jQuery inclusion.
<script type="text/javascript" src="app.js"></script>
This will prevent code repeat.
One more thing, pull all the code in $(document).ready(). Here is an example. So your app.js file will look like this:
$(document).ready(function(){
$('.thumbnail').click(function(){
$('.modal-body').empty();
var title = $(this).parent('a').attr("title");
$('.modal-title').html(title);
$($(this).parents('div').html()).appendTo('.modal-body');
$('#myModal').modal({show:true});
});
})

jquery script on html file

I'm using Bottle to make a simple web form and want to set the Selectize.js jquery plugin to a field so the user can set several values to that same field.
Inside my form tag I have the following code:
<label>
<span>Links :</span>
<input type="text" id="input-tags" name="links">
</label>
<script>
$('#input-tags').selectize({
persist: false,
createOnBlur: true,
create: true
});
</script>
And the following .js and .css inside the head tag:
<link href="/selectize.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="/selectize.js"></script>
To deal with static files I have the following route in my .py script:
#get('/<filename:re:.*\.js>')
def javascripts(filename):
return static_file(filename, root='static/js')
#get('/<filename:re:.*\.css>')
def stylesheets(filename):
return static_file(filename, root='static/css')
My route to deal with static files seems to be working properly 'cause I've tested it with other jquery plugin that does not use explicit code within the html file.
On this one, the problem seems to be on the explicit script code bellow the label tag. I found some articles about dealing with JSON but couldn't make it work (I also don't know if that is the right way to go).
Well, my best option was to put that explicit javascript into a new javascript file and add its path to the html like:
<script type="text/javascript" src="/<script_path_here>"></script>
That way my functions that handles the static files on the .py would do their job.

Categories

Resources