Javascript won't do cross domain request from django - javascript

Hi here is an odd problem. I am trying to serve the below index.htm file with django. When you click the button, the page (not the server) does a cross-domain request. If I load the index file direct in a browser it works. However, if I serve it with django, I get "An error occurred trying to load the resource" in the same browser (Safari). I am using (YQL) this method for cross domain requests: http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src="/static/jquery-1.10.0.min.js"></script>
<script type='text/javascript' src="/static/jquery.xdomainajax.js"></script>
<script>
function myFunction()
{
$.ajax({
url: 'http://www.google.com',
type: 'GET',
success: function(res) {
var headline = $(res.responseText).text();
document.getElementById("demo").innerHTML=res;
},
beforeSend : function(xhr, settings) {
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Cache-Control", "no-cache");
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
}
}
});
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
</script>
</head>
<body>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
</html>

Add the following code in your ajax function:
beforeSend : function(xhr, settings) {
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Cache-Control", "no-cache");
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
}
},
And also this function in your script:
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
:D

Related

Get response headers for request created by browser

Suppose index.html has script which has url to external js file (example.js):
<html>
<head>
<script src="/example.js"></script>
</head>
<body></body>
</html>
What I have tried it's create XMLHttpRequest and than manually execute script with window.eval(request.responseText). Any other ways?
To get the response headers when you make a request to server:
Vanilla JS:
var client = new XMLHttpRequest();
client.open("GET", "/some_url", true);
client.send();
client.onreadystatechange = function() {
if (this.readyState == this.HEADERS_RECEIVED) {
console.log(client.getResponseHeader("some_header"));
}
}
jQuery:
$.ajax({
type: 'GET',
url: '/some_url',
success: function(data, textStatus, request) {
console.log(request.getResponseHeader('some_header'));
},
error: function(request, textStatus, errorThrown) {
console.log(request.getResponseHeader('some_header'));
}
});

Implementing Microsoft's Project Oxford - Emotion API and file upload

I'm looking to be able to implement the Emotion API from Project Oxford on my website. I've currently written the below HTML/JavaScript code which checks an image from a URL and displays the result of said image after having run the Emotion API:
<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");
},
type: "POST",
// Request body
data: '{"url": "https://philosophybank.files.wordpress.com/2013/08/happy-people.jpg"}',
})
.done(function(data) {
JSON.stringify(data);
alert(JSON.stringify(data));
//console.log(data);
//alert(data.scores);
})
.fail(function(error) {
console.log(error.getAllResponseHeaders());
alert("fail");
});
});
</script>
This code works fine, however I'm looking to implement this on my website such that people upload images themselves locally from their machine with the use of a browse button as opposed to looking up an image using the link. Any help would be very much appreciated!
I mocked this up using application/octet-stream as the body type which allows you to post a binary object (i.e. the image itself), rather than a url to an image. The Emotion API documentation details how this is a supported content type.
I've continued with use of JQuery as per your original example.
You should be able to copy and paste this entire example into a HTML file, add your Emotion API key where it says my-key and it will work
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<input type="file" id="file" name="filename">
<button id="btn">Click here</button>
<script type="text/javascript">
$('#btn').click(function () {
var file = document.getElementById('file').files[0];
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/octet-stream");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
},
type: "POST",
data: file,
processData: false
})
.done(function(data) {
JSON.stringify(data);
alert(JSON.stringify(data));
})
.fail(function(error) {
alert(error.getAllResponseHeaders());
});
});
</script>
</body>
</html>

Project Oxford - HTTP 404 when calling Computer Vision API through Javascript

I am trying to get JSON data from Microoft Project Oxford through a API call. I followed the API reference but when I make a call I get a 404 error.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
"visualFeatures": "All",
};
$.ajax({
url: "https://api.projectoxford.ai/vision/v1/analyses&" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","0000000000000000");
},
type: "POST",
// Request body
data: '{ "Url": "http://www.sweetheartmotors.ca/sites/default/files/audi_PNG1736.png" }',
})
.done(function(data) {
alert("success");
//display data
console(data);
})
.fail(function() {
alert("error");
});
});
</script>
What is stopping me from making the call?
You need to change the URL to end in a question mark, rather than an ampersand: https://api.projectoxford.ai/vision/v1/analyses?
Unfortunately most of the samples on the projectoxford.ai site contain this error.

ajax request to Microsoft Emotion API in javascript

I am trying to try the microsoft emotion api. I am running a simple python web server with CORS enabled. Below is my server python file with which I start the server:
python-server.py
#! /usr/bin/env python2
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer
class CORSRequestHandler (SimpleHTTPRequestHandler):
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
if __name__ == '__main__':
BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)
I have an index.html file in which I am sending the http request:
index.html
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<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",JSON.stringify({"my-key"}));
},
type: "POST",
// Request body
data: JSON.stringify({"url": "http://tinyurl.com/2g9mqh"}),
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
After about 30 seconds I get the connection refused response. The http request code was taken from the emotion api's page I linked earlier. I wonder whether I need a real server or is there a mistake in the code? Thanks.
The JSON needs to be sent out as a string. So change your body specification to:
data: "{\"url\": \"http://...\"}"
Please use the code below(replace your-key), just save it as a .html and open it in the browser it shut work(without any server). If it works then try it in your python server.
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<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","your-key");
},
type: "POST",
// Request body
data: {"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"},
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Face API</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<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",
"");
},
type: "POST",
// Request body
data: JSON.stringify({
"url": "http://i1.mirror.co.uk/incoming/article6395000.ece/ALTERNATES/s1200/MAIN-David-Beckham-next-James-Bond.jpg"
}),
})
.done(function(data) {
console.log(data);
})
.fail(function(e) {
console.log(e);
});
});
</script>
</body>
</html>

Gmail contacts api access error

I want access client gmail contacts using gmail api. but it give error like "Uncaught SecurityError: Blocked a frame with origin "http://" from accessing a frame with origin "https://accounts.google.com". The frame requesting access has a protocol of http", the frame being accessed .
my code
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="jquery-2.1.1.min.js"></script>
<script>
function auth() {
var config = {
'client_id': 'ID',
'scope': 'https://www.google.com/m8/feeds'
};
gapi.auth.authorize(config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.ajax({
url: 'https://www.google.com/m8/feeds/contacts/default/full?alt=json',
dataType: 'jsonp',
data: token
}).done(function(data) {
console.log(JSON.stringify(data));
});
}
</script>
</head>
<body>
<button onclick="auth();">GET CONTACTS FEED</button>
</body>

Categories

Resources