405 from ajax get - suspect csrf stuff misbehaving - javascript

I have some JavaScript that looks like:
$(document).ready(function() {
var csrftoken = getCookie();
$.ajaxSetup({
cache : false,
data : null,
beforeSend : function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
});
And I have some JavaScript that looks like:
jQuery.ajax({
external : true,
type : "GET",
url : url,
datatype : "json",
async : true,
error : function( jqxhr, textStatus, errorThrown ) {
alert("error");
console.log(url);
console.log(jqxhr);
console.log(textStatus);
console.log(errorThrown);
},
success : function(data) {
if (data.status == "OK") {
// do stuff;
} else {
alert("Error: Google Directions API returned the status code " + data.status);
}
}
});
url is an external url. It asks Google Directions for some directions. If I just go there with my browser I get some nice json.
But if the code above executes I get a 405 and the following message "Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin"
I have 'django.middleware.csrf.CsrfViewMiddleware' installed.
I'm doing a lot of Googling to find out how to fix this but so far I can't find the problem.
My question is: How do I get this to work?
I'll keep looking for an answer in the meantime...
Stuff I've tried (in various combinations):
jsonp instead of json
crossDomain: true
I have verified that the line xhr.setRequestHeader("X-CSRFToken", csrftoken); is not called for the offending url

Check your settings file for the correct values, like:
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = ('127.0.0.1:8000', )

Related

how to read token from header by js

I'm trying to read token from header by plain java script , so I have two pages
A page request B page by
var B = function(){
$.ajax({
url: 'b.html',
method:'get',
dataType: 'json',
success: function(data) {
//do some handle functions
},
error: function(error){
console.log(error);
},
beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization','Bearer ' + access_token ); }
});
}
so, now i want read Authorization access token in B page by javascript !
You can use the XMLHttpRequest.getAllResponseHeaders() method to find the token header and retrieve the response.
More Information can be found at : https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

Get location from JSON in javascript

I am working now in a phonegap android application, I need the user's current address, so that i have used this
JSON api.
This is my code to get data for location updates from JSON api
$.ajax('http://maps.googleapis.com/maps/api/geocode/json?latlng=26.9008773,75.7403539&sensor=true', {
dataType: 'jsonp',
timeout: 3000,
data: {
_method: 'GET'
},
success: function (data,status) {
if (data._status != 200) {
console.log('received error', data._status);
// handle error
}else{
console.log('received data', data);
// do something useful with the data
}
},
error: function(data,status) {
var myObject = JSON.stringify(data);
console.log("Data Returned is " + myObject);
console.log("Status is " + status);
alert('error');
},
complete: function(data, status) {
alert('complete');
}
});
Every time it goes on error section , then the complete section, never goes into the success part.
the console output is :
12-10 11:11:34.393: I/Web Console(10620): Data Returned is {"readyState":4,"status":404,"statusText":"error"} at file:///android_asset/www/index.html:263
12-10 11:11:34.393: I/Web Console(10620): Status is error at file:///android_asset/www/index.html:264
Can anyone tell me, where exactly the problem is ?
If I remember correctly the default security policy in PhoneGap is to block all network access. You need to whitelist http://maps.googleapis.com.
The api you request does not support jsonp, the final request will like this:
http://maps.googleapis.com/maps/api/geocode/json?callback=jQuery18309743240959942341_1386656119920&latlng=26.9008773,75.7403539&sensor=true&_method=GET&_=1386656120107
with the callback param, but the output is still json, not javsscript file like
jQuery18309743240959942341_1386656119920(jsonDataHere...)
Take a look at this: https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse, it request url like this
https://maps.googleapis.com/maps/api/js/GeocodeService.Search?5m2&1d40.714224&2d-73.96145200000001&7sUS&9sen&callback=_xdc_._4cni6z&token=46423
And the output is:
_xdc_._4cni6z && _xdc_._4cni6z( { ....
That's jsonp.
ajax_call ='http://maps.googleapis.com/maps/api/geocode/json?latlng=26.9008773,75.7403539&sensor=true';
$.ajax({
type: "GET",
url: ajax_call,
cache:false,
dataType: "json",
success: function(response){
$.each(response.results, function(key, value) {
//alert(value.formatted_address);
console.log(value.formatted_address);
});
}
}).done(function() {
})

jquery ajax does not send request

I have a problem with the following code.
var sendJson = (JSON.stringify(comanda));
$.ajax({
url: 'sendMail.php',
type : "post",
data: sendJson,
success: function(data){
alert("Comanda dumneavoastra a fost trimisa");
}
});
Seems like data is not sent.... any idea why?
Ok... I know nothing is sent because I monitor requests with firebug.
I get no errors, nothing in console. Checked if it is activated, it is.
Here's what I meant with my comment:
var sendJson = (JSON.stringify(comanda));
$.ajax({
url: '/resource_url_goes_here',
type : 'POST',
data: sendJson,
success: function(data){
/* implementation goes here */
},
error: function(jqXHR, textStatus, errorThrown) {
/* implementation goes here */
}
});
Note that the ajax request has an error callback now. All requests should have an error callback so you can easily identify when errors are happening (as you've seen, firebug doesn't catch everything).
Another thing that I find helpful sometimes is StatusCodes:
$.ajax({
url: '/resource_url_goes_here',
type : 'POST',
data: sendJson,
statusCode: {
404: function() {
/*implementation for HTTP Status 404 (Not Found) goes here*/
},
401: function() {
/*implementation for HTTP Status 401 (Unauthorized) goes here*/
}
},
success: function(data){
/* implementation goes here */
},
error: function(jqXHR, textStatus, errorThrown) {
/* implementation goes here */
}
});
This will execute a function when a specific status code is returned by the server (404 and 401 in this snippet) and you can have a specific handler for the status codes you need.
You can find more about this here.

Can I test if URL is reachable using AJAX + cross-domain + jsonp?

I'm using JQuery to fetch information from an URL and display it on my page asynchronously. The URL comes from other domain, so I use JSONP to get the data. That works fine.
However, when the remote URL is down (which happens once in a while) my page hangs as JQuery AJAX doesn't call the 'success' or 'error' functions.
I'm using JQuery 1.7.
My code looks like:
$.ajax({
type : "GET",
url : "http://otherdomain.com/somePage.html",
data : params,
dataType : "jsonp",
jsonp : "jsonp",
success : function (response, textS, xhr) {
alert("ok");
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("not ok " + errorThrown);
}
});
If "somePage" is up, then I see the message "ok". If "somePage" is not reachable, then I don't see anything.
Any ideas on how can I get "error" function get called? Or more importantly, how to detect if the cross-domain URL is reachable?
Is that even possible?
Thanks,
add a timeout
$.ajax({
type : "GET",
url : "http://otherdomain.com/somePage.html",
data : params,
timeout:3000,
dataType : "jsonp",
jsonp : "jsonp",
success : function (response, textS, xhr) {
alert("ok");
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("not ok " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
}
});
DEMO

Response parser error

This is a cross-domain AJAX request to my web service.
$(document).ready(function(){
$.ajax({
url: 'http://storage.loc/api/getowners/?host=http://www.mail.ru/&callback=parseJSON',
dataType: 'jsonp',
crossDomain: true,
type: 'GET',
jsonp: false,
jsonCallback: 'parseJSON',
error: function(){
alert('Error');
},
complete: function(jqXHR, textStatus){
alert(textStatus);
}
});
});
function parseJSON(data)
{
var links = [];
$.each(data.users, function(key,value) {
links.push = ''+value+'<br />';
});
}
The response is:
parseJSON({"users":{"user0":"rulezz87","user1":"karazyab"}})
The response seems to be correct, but textStatus is "parsererror" and array in parseJSON() is empty. I`m not a pro in jQuery, so can you tell me, what i did wrong?
The response is incorrect sinde the list of users is not an array. It should be like:
{ "users" : [ {"user0" : "rulezz87"}, {"user1" : "karazyab"} ] }
So, the error message is correct and the fact that it cannot parse from JSON also.

Categories