I am working on some jquery stuff and ran into this error and I can't figure out how to fix it. I am using the flickr api to view the top 16 photos of the day, and I am doing so using the javascript canvas, but it keeps giving me that error. Here is my code.
var URLs = new Array();
function draw() {
// Loop through all images
var ctx = $('#canvas')[0].getContext("2d");
for (i=0;i<16;i++){
//document.write(URLs[i]);
//alert("hi");
ctx.drawImage(URLs[i],i * 120,i*120,100,100);
}
}
$.ajax({
url: 'http://api.flickr.com/services/rest/?&method=flickr.interestingness.getList&api_key=40ebfc18056e62c7e1cbec778b1db727&format=json&jsoncallback=?',
dataType: "jsonp",
success:function(data){
for(var i = 0; i < 16; i++)
{
var photoURL = 'http://farm' + data.photos.photo[i].farm + '.static.flickr.com/' + data.photos.photo[i].server + '/' + data.photos.photo[i].id + '_' + data.photos.photo[i].secret + '_m.jpg';
URLs[i] = photoURL;
}
draw();
}
})
and
<html>
<head>
<title>Flickr Art gallery</title>
<script src="/js/jquery.js"></script>
<script src="/js/flickr.js"></script>
<style type="text/css">
img { display:none; }
table { margin: 0 auto; }
td { padding:15px; }
</style>
</head>
<body>
<canvas id="canvas" width="1000" height="600"></canvas>
</body>
</html>
The error is happening because of the canvas, when I call drawImage, it throws this, so I was wondering what would cause that. Thanks in advance.
The error was :
Uncaught TypeError: Type error
d.d.extend._Deferred.f.resolveWith jquery.js:16
v jquery.js:16
d.ajaxTransport.send.d.onload.d.onreadystatechange jquery.js:16
The drawImage method wants an Image object, not a string. So, you just need to instantiate your URLs as Image objects:
for(i = 0; i < 16; i++) {
var image = Image.new();
image.src = URLS[i];
ctx.drawImage(image, i * 120, i * 120, 100, 100);
}
The "Type Error" part of your error message is clear enough once you know what drawImage wants. The rest of the error message is a bit of a mess because the exception originates inside a function that is being called by jQuery's AJAX success callback, this means that you end up with several layers of obscurity between you and and your bug.
Related
I've managed to run the following code thanks to this post here Adding Microsoft's Emotion API to HTML website.
<HTML>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","my-key-here");
},
type: "POST",
// Request body
data: '{"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"}',
})
.done(function(data) {
alert("success");
})
.fail(function(error) {
console.log(error.getAllResponseHeaders());
alert("fail");
});
});
</script>
</body>
</head>
</html>
This may seem like stupid question however I've been wondering how to get the emotions output from the HTML file? i.e. instead of the success alert I'd like to generate a text file which shows the output of the Emotions API with each emotion (like it does on their website).
One solution could be to read about Blob's. You could take the response from the ajax call in done() and create the text file you need. Here is an example for using Blob I found on JSFiddle:
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";
saveData(data, fileName);
source
data is an array, one item per face. If you just want to dump the text, you can call JSON.stringify(data). If you want pretty-print it in HTML, take a look at How can I pretty-print JSON using JavaScript?.
I've done this ins my website HowHappy.co.uk which is also on GitHub here: https://github.com/martinkearn/How-Happy
The way I displayed the data in a web site was to enumerate the array of faces in Javascript and use basic CSS to show the rectangle in the right place and Bootstrap popover to show the details data.
There is too much to put in this response so I recommend you look though the GitHub repo, but here are some of the key bits
Javascript
var dataString = JSON.stringify(response);
var data = JSON.parse(dataString);
//draw rectangle for each face
$.each(data.Faces, function (index, value) {
var rect = document.createElement('div');
rect.className = "rect";
rect.style.height = value.faceRectangle.height + "px";
rect.style.width = value.faceRectangle.width + "px";
rect.style.left = value.faceRectangle.left + "px";
rect.style.top = value.faceRectangle.top + "px";
rect.id = "rect" + index;
$('#result').append(rect);
//add popover
var popoverBody = "Happiness: " + Number((value.scores.happiness).toFixed(2))
+ "<br>Fear: " + Number((value.scores.fear).toFixed(2))
+ "<br>Anger: " + Number((value.scores.anger).toFixed(2))
+ "<br>Contempt: " + Number((value.scores.contempt).toFixed(2))
+ "<br>Disgust: " + Number((value.scores.disgust).toFixed(2))
+ "<br>Neutral: " + Number((value.scores.neutral).toFixed(2))
+ "<br>Sadness: " + Number((value.scores.sadness).toFixed(2))
+ "<br>Surprise: " + Number((value.scores.surprise).toFixed(2));
$('#rect' + index).popover({
title: (index + 1)
content: popoverBody,
html: "true",
trigger: "click"
});
});
Css
.rect {
position: absolute;
border-color: #FFEA0E;
border-style: solid;
border-width: 4px;
z-index: 10;
}
#result {
position: relative;
text-align: center;
margin: 0 auto;
width: auto;
}
#resultDetails {
font-size: 3rem;
text-align: center;
}
I'm trying to list all blog posts with the Blogger API v3:
<script type="text/javascript">
function handleResponse(response) {
var post_number = Object.keys(response.items).length; //number of posts
for (i=0; i<post_number; i++) {
$('#content').append('<div id="post' + (i+1) + '" class="post"><p></p></div>');
$('.post p').html(Object.keys(response.items[i].title));
}
}
</script>
<script src="https://www.googleapis.com/blogger/v3/blogs/1961645108677548855/posts?callback=handleResponse&key=AIzaSyAJESQB3ddltUcDbZif3LUnX-Gzr18tBRg"></script>
This does append 3 divs (because of 3 posts) to my content div. But the content of each of this divs is:
<p>
"1"
"2"
"3"
"4"
"5"
</p>
I have no clue why, though I assume that title is an attribute of items[].
Any solutions or clues?
Thanks for answers!
You should removed Object.keys() and try this:
<script type="text/javascript">
function handleResponse(response) {
var post_number = Object.keys(response.items).length; //number of posts
for (i=0; i<post_number; i++) {
$('#content').append('<div id="post' + (i+1) + '" class="post"><p></p></div>');
$('.post p').html(response.items[i].title);
}
}
</script>
<script src="https://www.googleapis.com/blogger/v3/blogs/1961645108677548855/posts?callback=handleResponse&key=AIzaSyAJESQB3ddltUcDbZif3LUnX-Gzr18tBRg"></script>
In you case you shouldn't use Object.keys()
You request doesn't use the maxResults parameter and limited number of posts is retrieved so I recommend to use Google JavaScript Client Library - Blogger API and recursively retrieve all posts of a blog.
See the following example:
<script>
function renderResults(response) {
if (response.items) {
for (var i = 0; i < response.items.length; i++) {
//do whatever you want with the posts of your blog
}
}
if(response.nextPageToken) {
var blogId = 'XXX Your blogId XXX';
var request = gapi.client.blogger.posts.list({
'blogId': blogId,
'pageToken': response.nextPageToken,
'maxResults': 100,
});
request.execute(renderResults);
}
}
function init() {
gapi.client.setApiKey('XXX Get your API Key from https://code.google.com/apis/console XXX');
gapi.client.load('blogger', 'v3', function() {
var blogId = 'XXX Your blogId XXX';
var request = gapi.client.blogger.posts.list({
'blogId': blogId,
'maxResults': 100,
});
request.execute(renderResults);
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>
I am trying to get the URL for all the photos of a facebook page.
How do I get the 'source' URL for this query and JSON structure:
https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=19292868552%3Ffields%3Dalbums.fields(photos.fields(source))&version=v2.1
I am using this success callback from a JSONP request:
function(response) {
for (i = 0; i < **???response.albums.data.length???**; i++) {
alert(**???response.albums.data[i].photos.data[i].source???**)
}
}
Can you help me find the right structure for the parts with the astericks? Because it has two [i]'s i think i'm getting confused..
You need to make sure that you have this in your head:
<script type='text/javascript' src='//connect.facebook.net/en_US/sdk.js'></script>
<script type='text/javascript' src='workFromPage.js'></script>
Now on workFromPage.js
var pre = onload;
onload = function(){
if(pre)pre();
if(!FB)reload();
var photoURLs = [];
// change userId
// make sure you test for login and wrap around code below, if needed
FB.api('/userId/albums', function(resp){
if(resp && !resp.error){
for(var i in resp){
FB.api('/'+resp[i].id+'/photos', function(r){
if(r && !r.error){
for(var n in r){
photoURLs.push(r[n].source);
}
// access photoURLs here
}
}
}
}
}
}
I am trying to upload a file to my server with Phonegap. I am currently stuck when an error that says:
InvalidCastException
Failed to deserialize WP7CordovaClassLib.Cordova.Commands.FileTransfer+UploadOptions[] with JSON value :: ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://server.myapp.srv.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
The HTML + Javascript
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<title>File Transfer Example</title>
</head>
<body>
<button id="uploadPhotoButton">Upload a Photo</button>
<script type="text/javascript" src="cordova-2.2.0.js"></script>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" src="js/camera.js"></script>
<script type="text/javascript">
$(document).one("pause", function () {
console.log('Paused.');
});
$(document).one("resume", function () {
console.log('Resumed.');
});
$(document).one("deviceready", function () {
console.log('Device is ready.');
});
$(document).one("backbutton", function () {
console.log('Back button pressed.');
});
$(document).ready(function () {
console.log('DOM is ready.');
$(document).on("click", "#uploadPhotoButton", function (e) {
console.log('clicked button');
getImage();
});
function getImage() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto, function (message) {
alert('get picture failed');
}, {
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://my.server.co.nz/pages/fileupload", win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
alert("An error has occurred: Code = " = error.code);
}
});
</script>
</body>
</html>
The complete error log.
GapBrowser_Navigated :: /app/www/index.html#/app/www/uploadtest.html
Log:"clicked button"
The thread '<No Name>' (0xf55026a) has exited with code 0 (0x0).
The thread '<No Name>' (0xe3f0326) has exited with code 0 (0x0).
INFO: AppDeactivated
INFO: AppActivated
Log:"Paused."
The thread '<No Name>' (0xf1a02e6) has exited with code 0 (0x0).
Log:"Resumed."
The thread '<No Name>' (0xf2a01d2) has exited with code 0 (0x0).
options = ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://my.server.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
A first chance exception of type 'System.InvalidCastException' occurred in System.ServiceModel.Web.dll
A first chance exception of type 'System.InvalidCastException' occurred in System.ServiceModel.Web.dll
InvalidCastException
Failed to deserialize WP7CordovaClassLib.Cordova.Commands.FileTransfer+UploadOptions[] with JSON value :: ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://server.myapp.srv.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
A first chance exception of type 'System.NullReferenceException' occurred in Lion.MyApp.dll
The thread '<No Name>' (0xfdc025e) has exited with code 0 (0x0).
Log:"Error in error callback: FileTransfer1325332352 = ReferenceError: Invalid left-hand side in assignment"
The thread '<No Name>' (0xfa60286) has exited with code 0 (0x0).
Does anyone have an idea on how to make this work?
Thanks!
W
I'm thinking that you are malforming your options value. Do you need to pass JSON or an actual object?
Right now you are passing an array with text in it.
options = ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://my.server.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
The error seems to involve deserialization issues.
Put your getImage, uploadImage, win, fail outside of $(document).ready 's inline function call.
Reference to win and fail are actually closure, and phone gap gets it as null when it is trying to access those methods directly. Phonegap is probably expecting a global function instead of hidden function inside a function.
PhoneGap's executes its code out side javascript context, what may work in true javascript fashion may not work correctly with phonegap.
I had a problem similar to yours. I solved this, changing mimeType parameter to 'text/plain'.
Do you use params to send? If it's false I think you need send empty params.
I had this problem before, try to prepare the image in the html first, and dont take it directly from the navigator, it may not saving the taken photo in it cash ;)
In my solution I suppose to have an image tage with id ='camera_image'
img id='camera_image'...
Then i set all the variables of the image in it and I upload it (as you will see in the following code).
here's the 2 functions i used:
function takephoto(){
navigator.camera.getPicture(
function(uri){
$('#camera_image').show();
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
uploadPhoto(img);
alert("Success");
},
function(e) {
console.log("Error getting picture: " + e);
},
{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI
});
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
alert("Take picture or select picture from library first.");
return;
}
}
for choosing an existing photo:
function choosephoto(){
navigator.camera.getPicture(
function(uri) {
$('#camera_image').show();
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
uploadPhoto(img);
},
function(e) {
console.log("Error getting picture: " + e);
},
{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.SAVEDPHOTOALBUM
});
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
alert("please select a pic first");
return;
}
}
in the upload function:
function uploadPhoto(img) {
imageURI = img.src ...
ps: sorry for the formatting of my code, it doesn't fix well.
I use the library Highcharts in order to generate some graphics.
I would like to send them to the server and also to do a mysql request in order to save the data informations into my database. The thing is that It just download the file into my compuer.
I really would like to keep it on the server on a predefined folder. It just dowload it.
I wrote this code with many efforts.
I met many problems but I don't know how to pass this last.
Here is the code for generating the image and to download it auomatically:
<script type="text/javascript">//<![CDATA[
$(function(){
/**
* Create a global getSVG method that takes an array of charts as an argument
*/
Highcharts.getSVG = function(charts) {
var svgArr = [],
top = 0,
width = 0;
$.each(charts, function(i, chart) {
var svg = chart.getSVG();
svg = svg.replace('<svg', '<g transform="translate(0,' + top + ')" ');
svg = svg.replace('</svg>', '</g>');
top += chart.chartHeight;
width = Math.max(width, chart.chartWidth);
svgArr.push(svg);
});
return '<svg height="2400px" width="1200px" version="1.1" xmlns="http://www.w3.org/2000/svg">' + svgArr.join('') + '</svg>';
};
/**
* Create a global exportCharts method that takes an array of charts as an argument,
* and exporting options as the second argument
*/
Highcharts.exportCharts = function(charts, options) {
var form
svg = Highcharts.getSVG(charts);
// merge the options
options = Highcharts.merge(Highcharts.getOptions().exporting, options);
// create the form
form = Highcharts.createElement('form', {
method: 'post',
action: options.url
}, {
display: 'none'
}, document.body);
// add the values
Highcharts.each(['filename', 'type', 'width', 'svg'], function(name) {
Highcharts.createElement('input', {
type: 'hidden',
name: name,
value: {
filename: options.filename || 'chart',
type: options.type,
width: 1200,
svg: svg
}[name]
}, null, form);
});
//console.log(svg); return;
// submit
form.submit();
// clean up
form.parentNode.removeChild(form);
};
$('#export').click(function() {
Highcharts.exportCharts([chart1, chart2, chart3]);
});
});//]]>
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script type="text/javascript" src="http://highcharts.com/js/testing-exporting.js"></script>
<div id="container" style="height: 400px; width:1200px"></div>
<div id="container2" style="height: 400px; width:1200px"></div>
<div id="container3" style="height: 400px; width:1200px"></div>
<button id="export">Export all</button>
I just try to send it to to server.
Thank you all verry much in advance for the help.
Receive my Utmost Respect.
Kind Regards SP.
you can try this
var chart = $('#yourchart').highcharts();
svg = chart.getSVG();
var base_image = new Image();
svg = "data:image/svg+xml,"+svg;
base_image.src = svg;
$('#mock').attr('src', svg);
var dataString = $('#mock').html() ; // or just binary code
$.ajax({
type: 'POST',
data: dataString,
url: 'your-server/',
success: function(data){
}
});
Save highchart as binary image