I'm pulling images from an API that uses an image from an insecure location (http). In order to properly serve it on my app, I need it to be via https. Is there any way to convert it prior to being served on the page?
Here's what I have:
$(document).ready(function() {
console.log("ready!");
var url = 'https://api.petfinder.com/pet.getRandom';
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
data: {
key: "4a9698752f4139c768c657d4776e1fbf",
animal: 'dog',
output: 'basic',
format: 'json'
},
// Here is where we handle the response we got back from Petfinder
success: function(response) {
console.log(response); // debugging
var dogName = response.petfinder.pet.name.$t;
var img = response.petfinder.pet.media.photos.photo[2].$t;
var id = response.petfinder.pet.id.$t;
var newName = document.createElement('a');
var newDiv = document.createElement('div');
newName.textContent = dogName;
newName.href = 'https://www.petfinder.com/petdetail/' + id;
var newImg = document.createElement('img');
newImg.src = img;
var list = document.createElement("div");
list.setAttribute("id", "List");
document.body.appendChild(list);
newDiv.appendChild(newName);
list.appendChild(newDiv);
list.appendChild(newImg);
}
})
})
My thought is to encode the object property via a variable then somehow convert that variable, but I don't know how to do it. I don't think I'm googling the right question because this doesn't seem like it would be that hard.
var encodedUrl = encodeURIComponent(img);
console.log(encodedUrl);
Related
I am trying to read data from this API, but it is not working, I have an input box where I enter the isbn number and then get the data, using jsonp. Could you possibly help me in identifying where my error("Cannot read property 'title' of undefined") is?
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(isbn){
var infoUrl = isbn.info_url;
var thumbnailUrl = isbn.thumbnail_url;
var title = isbn.details.title;
var publishers = isbn.details.publishers;
var isbn13 = isbn.details.isbn_13;
console.log(isbn.info_url);
}
});
}
Open Library's API expects bibkeys to be prefixed with their type and a colon, rather than just the number alone:
function add(){
var isbn = 'ISBN:' + $("#isbn").val();
// ...
The colon also means the value should be URL-encoded, which jQuery can do for you:
$.ajax({
url: "https://openlibrary.org/api/books?jscmd=details&callback=?",
data: { bidkeys: isbn },
dataType: "jsonp",
Then, the data it returns reuses the bibkeys you provided as properties:
{ "ISBN:0123456789": { "info_url": ..., "details": { ... }, ... } }
To access the book's information, you'll have to first access this property:
success: function(data){
var bookInfo = data[isbn];
console.log(bookInfo.details.title);
// etc.
}
Example: https://jsfiddle.net/3p6s7051/
You can also retrieve the bibkey from the object itself using Object.keys():
success: function (data) {
var bibkey = Object.keys(data)[0];
var bookInfo = data[bibkey];
console.log(bookInfo.details.title);
// ...
}
Note: You can use this to validate, since the request can be technically successful and not include any book information (i.e. no matches found):
success: function (data) {
var bibkeys = Object.keys(data);
if (bibkeys.length === 0)
return showError('No books were found with the ISBN provided.');
// ...
Example: https://jsfiddle.net/q0aqys87/
I asked a professor, and this is how she told me to solve it:
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(data){
var thumb=data["ISBN:"+isbn+""].thumbnail_url;
....
}
});
}
I'm using Github Gists for a web playground I'm making as a side project. I load two json files into the editor. 1 handles all the libraries (jquery, bootstrap, etc:) and another for the users settings (fontsize, version, etc:)
So anyway I have this JSON named settings
var settings = gistdata.data.files["settings.json"].content
var jsonSets = JSON.parse(settings)
I parse and attempted to grab an object from the JSON and set it as a value of a input textbox.
Now console.log(jsonSets.siteTitle) works perfectly fine
but when I try to change the input dynamically...
$("[data-action=sitetitle]").val(jsonSets.siteTitle).trigger("change")
The problem is it's not actually applying the value!
The only way I've been able to successfully apply the value is...
setTimeout(function() {
$("[data-action=sitetitle]").val(jsonSets.siteTitle).trigger("change")
}, 5000)
Which is ridiculously slow.
Does anyone know why it's not applying the value?
in addition.
How can I solve this problem?
var hash = window.location.hash.substring(1)
if (window.location.hash) {
function loadgist(gistid) {
$.ajax({
url: "https://api.github.com/gists/" + gistid,
type: "GET",
dataType: "jsonp"
}).success(function(gistdata) {
var libraries = gistdata.data.files["libraries.json"].content
var settings = gistdata.data.files["settings.json"].content
var jsonLibs = JSON.parse(libraries)
var jsonSets = JSON.parse(settings)
// Return libraries from json
$.each(jsonLibs, function(name, value) {
$(".ldd-submenu #" + name).prop("checked", value)
})
// Return font settings from json
var siteTitle = jsonSets.siteTitle
var WeaveVersion = jsonSets.version
var editorFontSize = jsonSets.editorFontSize
var WeaveDesc = jsonSets.description
var WeaveAuthor = jsonSets.author
$("[data-action=sitetitle]").val(siteTitle).trigger("change")
$("[data-value=version]").val(WeaveVersion).trigger("change")
$("[data-editor=fontSize]").val(editorFontSize).trigger("change")
$("[data-action=sitedesc]").val(WeaveDesc).trigger("change")
$("[data-action=siteauthor]").val(WeaveAuthor).trigger("change")
}).error(function(e) {
// ajax error
console.warn("Error: Could not load weave!", e)
})
}
loadgist(hash)
} else {
// No hash found
}
My problem was actually related to localStorage.
I cleared it localStorage.clear(); ran the ajax function after and it solved the problem.
var hash = window.location.hash.substring(1)
if (window.location.hash) {
localStorage.clear()
function loadgist(gistid) {
$.ajax({
url: "https://api.github.com/gists/" + gistid,
type: "GET",
dataType: "jsonp",
jsonp: "callback"
}).success(function(gistdata) {
var htmlVal = gistdata.data.files["index.html"].content
var cssVal = gistdata.data.files["index.css"].content
var jsVal = gistdata.data.files["index.js"].content
var mdVal = gistdata.data.files["README.md"].content
var settings = gistdata.data.files["settings.json"].content
var libraries = gistdata.data.files["libraries.json"].content
var jsonSets = JSON.parse(settings)
var jsonLibs = JSON.parse(libraries)
// Return font settings from json
var siteTitle = jsonSets.siteTitle
var WeaveVersion = jsonSets.version
var editorFontSize = jsonSets.editorFontSize
var WeaveDesc = jsonSets.description
var WeaveAuthor = jsonSets.author
$("[data-action=sitetitle]").val(siteTitle)
$("[data-value=version]").val(WeaveVersion)
$("[data-editor=fontSize]").val(editorFontSize)
$("[data-action=sitedesc]").val(WeaveDesc)
$("[data-action=siteauthor]").val(WeaveAuthor)
storeValues()
// Return settings from the json
$(".metaboxes input.heading").trigger("keyup")
// Return libraries from json
$.each(jsonLibs, function(name, value) {
$(".ldd-submenu #" + name).prop("checked", value).trigger("keyup")
})
// Set checked libraries into preview
$("#jquery").trigger("keyup")
// Return the editor's values
mdEditor.setValue(mdVal)
htmlEditor.setValue(htmlVal)
cssEditor.setValue(cssVal)
jsEditor.setValue(jsVal)
}).error(function(e) {
// ajax error
console.warn("Error: Could not load weave!", e)
})
}
loadgist(hash)
} else {
// No hash found
}
I have some javascript code that uploads an image to a server. Below is the ajax call that works correctly.
$.ajax({
url: 'https://api.projectoxford.ai/vision/v1/analyses?',
type: 'POST',
contentType: 'application/json',
data: '{ "Url": "http://images.takungpao.com/2012/1115/20121115073901672.jpg" }',
})
I now need to upload the image a a base64 encoding e.g.
data: 'data:image/jpeg;base64,/9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z'
But that doesn't work, i.e. the server doesn't recognise the data I send and complains.
Does anyone know what the correct format is for sending base64 encoded data in the AJAX call ?
Thanks for all the answers which helped me along.
I had also posted the question to the forums on
https://social.msdn.microsoft.com/Forums/en-US/807ee18d-45e5-410b-a339-c8dcb3bfa25b/testing-project-oxford-ocr-how-to-use-a-local-file-in-base64-for-example?forum=mlapi (more Project Oxford specific) and between their answers and your's I've got a solution.
You need to send a Blob
You need to set the processData:false and contentType: 'application/octet-stream' options in the .ajax call
So my solution looks like this
First a function to make the blob (This is copied verbatim from someone more gifted than I)
makeblob = function (dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], { type: contentType });
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
}
and then
$.ajax({
url: 'https://api.projectoxford.ai/vision/v1/ocr?' + $.param(params),
type: 'POST',
processData: false,
contentType: 'application/octet-stream',
data: makeblob('data:image/jpeg;base64,9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z'
})
.done(function(data) {alert("success");})
.fail(function() {alert("error");});
This is some working code from my own application. You will need to change the contentType and data args in your ajax operations.
var video = that.vars.video;
var code = document.createElement("canvas");
code.getContext('2d').drawImage(video, 0, 0, code.width, code.height);
var img = document.createElement("img");
img.src = code.toDataURL();
$.ajax({
url: '/scan/submit',
type: 'POST',
data: { data: code.toDataURL(), userid: userid },
success: function (data) {
if (data.error) {
alert(data.error);
return;
}
// do something here.
},
error : function (r, s, e) {
alert("Unexpected error:" + e);
console.log(r);
console.log(s);
console.log(e);
}
});
//After received the foto, convert to byte - C# code
Dim imagem = imagemBase64.Split(",")(1)
Dim bytes = Convert.FromBase64String(imagem)
You load the image in canvas, not necessary upload to server.
var ctx = canvas.getContext('2d');
ctx.drawImage(img, selection.x, selection.y, selection.w, selection.h, 0, 0, canvas.width, canvas.height);
var ctxPreview = avatarCanvas.getContext('2d');
ctxPreview.clearRect(0, 0, ctxPreview.width, ctxPreview.height);
ctxPreview.drawImage(img, selection.x, selection.y, selection.w, selection.h, 0, 0, canvas.width, canvas.height);
$('#avatarCanvas').attr('src', canvas.toDataURL());
$('#hdImagembase64').val(canvas.toDataURL());
See, this code get image and draw in canvas, after draw you get base64 string with canvas.toDataURL()
try this :D
The data parameter for jQuery's $.ajax call can be a String, Object, or Array. Based on the working example you gave, it looks like your upload script expects a parameter called "Url":
data: '{ "Url": "http://images.takungpao.com/2012/1115/20121115073901672.jpg" }'
If you wanted to pass the parameter as an Object, you might try:
data: {
Url: 'data:image/jpeg;base64,/9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z'
}
If you want to pass it as a String, you might try:
data: '{ "Url": "data:image/jpeg;base64,/9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z"}'
I am trying to push the base64 of an image in <canvas> to a Node.js server. I have tried many approaches, but most other answers on Stackoverflow centre around this idea, however it doesn't work for me:
saveImage: function(e) {
var canvas = document.querySelector('#canvasElement');
var base64 = canvas.toDataURL();
var image = 'image';
var object = {};
object[image] = base64;
console.log(object);
$.ajax({
url: '/save',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(object)
});
},
Hi I'm learning how to work with protovis, so far so good, but now I stumbled upon a problem I can't seem to solve.
The following is the code. (I have the latest jquery loaded in my headers)
<script type="text/javascript+protovis">
var dataURL = "http://eagereyes.org/media/2010/protovis-primer/earthquakes.json";
var JSONdata = $.ajax({ type: "GET", url: dataURL, async: false }).responseText;
var earthquakes = JSON.parse(JSONdata);
var width = 560;
var height = 245;
var barWidth = width/earthquakes.length;
var gap = 2;
new pv.Panel().width(width).height(height+5)
.add(pv.Bar)
.data(earthquakes)
.bottom(0)
.width(barWidth-gap)
.height(function(d) d.Magnitude * (height/9))
.left(function() this.index * barWidth)
.root.render();
When I try this in Firefox i get this alert:
Syntax:Error JSON.parse
I have validated the JSON on http://www.jsonlint.com/ already. So the problem must be elsewhere.
Anyone knows whats going on here?
Edit
I tried loading the same data in the protoviewer app: http://www.rioleo.org/protoviewer/ and it works. So it must be the code.
Have you tried a regular async callback instead of the synchronous approach? Like:
var dataURL = "http://eagereyes.org/media/2010/protovis-primer/earthquakes.json";
$.ajax({
type: "GET",
url: dataURL,
success: function(response) {
var earthquakes = JSON.parse(JSONdata);
var width = 560;
var height = 245;
var barWidth = width/earthquakes.length;
var gap = 2;
new pv.Panel().width(width).height(height+5)
.add(pv.Bar)
.data(earthquakes)
.bottom(0)
.width(barWidth-gap)
.height(function(d) d.Magnitude * (height/9))
.left(function() this.index * barWidth)
.root.render();
}
});
Also, is that JSON file located on the same server that the page making the request shows in the address bar (exactly http://eagereyes.org)?
Finally, the manual JSON.parse() step isn't necessary. If you add the dataType: 'json' parameter, $.ajax() will automatically deserialize as JSON and uses JSON.parse() where available.
Add a semi-colon ; to the end of your response
Which browser are you using? Some browsers don't define the JSON object. You can download a script from the URL below which will define the JSON object if it doesn't already exist.
https://github.com/douglascrockford/JSON-js
You can check whether JSON is defined as follows:
alert(JSON);
update
OK next thing I'd do is check that the ajax call is actually returning the corect data. Change your code to print the JSON returned from the ajax call.
var JSONdata = $.ajax({ type: "GET", url: dataURL, async: false }).responseText;
alert(JSONdata);
var earthquakes = JSON.parse(JSONdata);
$.ajax({
type: "POST",
url: "saveChangesInEditing.php",
data: idObject,
success: function(data){
dataObject = JSON.parse(data);
$("input[name = 'id']").val(dataObject.id);
$("input[name='full_name']").val(dataObject.full_name);
$("input[name='sport']").val(dataObject.sport);
$("input[name='idol']").val(dataObject.idol);
},
error: function(data){
alert("error!" + data);
}
});