When accessing a localhost's protected CouchDB database via $.ajax, it prompts an alert asking for the username/password. If i cancel the prompt, CouchDB alerts an error and my $.ajax error callback is never executed. If i pass in an authorized user to the url (http://user:pass#local...), the success callback is executed properly.
So, is possible to make authenticated ajax queries to Couch and use my own error handling functions?
Edit, code:
var request = $.ajax({
url: myUrl,
type: "GET",
dataType: "jsonp",
success: function(){
console.log("ok");
},
error: function(){
console.log("error");
}
});
If myUrl does not include credentials, like http://localhost:5984/mydb/handshakeDoc, error callback is never executed after cancelling the prompt.
If myUrl include invalid credentials, like http://user:invalidpass#localhost:5984/mydb/handshakeDoc, error prompt still appears and error callback is never executed after cancelling the prompt.
If myUrl include valid credentials, success callback is executed
----- possible solution -----
So, I got a solution that worked for me. However I had to use apache as a Proxy server to circumvent the cross origin policy.
The idea here is to remove the problems with the cross domain policy and use an http-server to proxy our request locally to the couchdb service. Every request for example.com/couch will be redirected to the couchdb service. That way you don't have to use a jsonp request anymore.
The initial problem you asked about whether or not you can use your own error handling is directly linked to jsonp requests in jQuery as they do not use the error handlers - They never get called at all.
Apache configuration:
<VirtualHost 123.123.123.123:80>
ServerName example.com
ProxyPass /couch http://localhost:5984
ProxyPassReverse /couch http://localhost:5984
</VirtualHost>
jQuery ajax request:
var request = $.ajax({
url: "http://example.com/couch",
dataType: "json",
}).done(function() {console.log("done");})
.fail(function() {console.log("fail");})
.always(function() {console.log("always");});
});
----- Original post -----
You could try this:
var request = $.ajax({
url: myUrl,
type: "GET",
username: user,
password: pass,
dataType: "jsonp",
success: function(){
console.log("ok");
},
error: function(){
console.log("error");
}
});
jQuery gives you the possibility to use the http basic auth via two ajax parameters (username and password).
Or you might wanna try the CouchDB jQuery plugin.
Related
I create an account with yaler, to comunicate with my arduino yun. It works fine, and i'm able to switch on and off my leds.
Then i created a web page, with a button that calls an ajax function with GET method to yaler (yaler web server accept REST style on the URL)
$.ajax({
url: "http://RELAY_DOMAIN.try.yaler.net/arduino/digital/13/1",
dataType: "json",
success: function(msg){
var jsonStr = msg;
},
error: function(err){
alert(err.responseText);
}
});
This code seem to work fine, infact the led switches off and on, but i expect a json response in success function (msg) like this:
{
"command":"digital",
"pin":13,
"value":1,
"action":"write"
}
But i get an error (error function). I also tried to alert the err.responseText, but it is undefined....
How could i solve the issue? Any suggestions???
Thanks in advance....
If the Web page containing the above Ajax request is served from a different origin, you'll have to work around the same origin policy of your Web browser.
There are two ways to do this (based on http://forum.arduino.cc/index.php?topic=304804):
CORS, i.e. adding the header Access-Control-Allow-Origin: * to the Yun Web service
JSONP, i.e. getting the Yun to serve an additional JS function if requested by the Ajax call with a query parameter ?callback=?
CORS can probably be configured in the OpenWRT part of the Yun, while JSONP could be added to the Brige.ino code (which you seem to be using).
I had the same problem. I used JSONP to solve it. JSONP is JSON with padding. Basically means you send the JSON data with a sort of wrapper.
Instead of just the data you have to send a Java Script function and this is allowed by the internet.
So instead of your response being :
{"command":"digital","pin":13,"value":0,"action":"write"}
It should be:
showResult({command:"analog",pin:13,value:0,action:"write"});
I changed the yunYaler.ino to do this.
So for the html :
var url = 'http://try.yaler.net/realy-domain/analog/13/210';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'showResult',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.action);
},
error: function(e) {
console.log(e.message);
}
});
};
function showResult(show)
{
var str = "command = "+show.command;// you can do the others the same way.
alert (str);
}
My JSON is wrapped with a showResult() so its made JSONP and its the function I called in the callback.
Hope this helps. If CORS worked for you. Could you please put up how it worked here.
I have the development enviroment consisting of the Apache HTTP server for fast Javascript development and the application server (WebSphere) that provides the JSON REST API. Of course, Access-Control-Allow-Origin is set (to *).
The following code results in error:
xhr.post({
url: "http://localhost:8080/rest-sample/rest/test/list",
handleAs: "json",
load: onload
});
RequestError: Unable to load
http://localhost:8080/rest-sample/rest/test/list status: 0
ErrorCtor()create.js (Zeile 13) onError()xhr.js (Zeile 80)
var err = Error.call(this, message),
There is a JavaScript error thrown instead of sending the AJAX request. However, in the same time, the following jQuery snipplet function perfect:
var url = "http://localhost:8080/rest-sample/rest/test/list"
$.post(url, {}, onLoad, 'json')
My question is: what I'm doing wrong? How to send the AJAX request to the other server using Dojo?
I'm using dojo 1.9
Your server must also send Access-Control-Allow-Headers: x-requested-with.
I think xhr.post is no longer supported, i suggest to use dojo/request, or at least dojo/request/xhr
require(["dojo/request/xhr"], function(xhr){
xhr("http://localhost/rest-sample/rest/test/list", {
handleAs: "json",
method: "POST"
}).then(function(data){
// Do something with the handled data
}, function(err){
// Handle the error condition
}, function(evt){
// Handle a progress event from the request if the
// browser supports XHR2
});
});
If it's Cross origin problem i would suggest using ReverseProxy on your http server.
add this to your httpd.conf
ProxyPass /rest-sample/ http://localhost:8080/rest-sample/
I have to make ajax request for mobile web app, I used the following code
$.ajax({
type: type, //GET or POST or PUT or DELETE verb
url: requestURL, // Location of the service
// contentType: "application/x-www-form-urlencoded", // content type sent to server
dataType: "xml", //Expected data format from server
processData: false, //True or False
success: successCallback, //On Successfull service call
error: serviceFailed// When Service call fails
});
But it failed with error "Error: Access is denied. I am calling .aspx service from javascript
You cannot submit AJAX requests to domains other than the one serving the web page. If it is a sub domain causing the problems, you can use this code to resolve it.
document.domain = location.host.replace(/^.*?([^.]+\.[^.]+)$/g,'$1');
Is it possible to catch the HTTP errors (like 404, 500, 504 etc) when we call an external webservice by specifying an absolute url?. (like setting the url: attribute of $.ajax call to have a url value as http://api.geonames.org/findNearbyPostalCodes.
Right now I'm unable to receive any errors although firebug is catching them and showing it in the console.
Can someone help?
Here is my code.
$.ajax({
type: 'GET',
url: "http://api.geonames.org/findNearbyPostalCodes",
data: '{"lat":47,"lng":"9","username":"demo"}',
dataType: 'json',
cache:false,
async:false,
statusCode:{
404: function(){
alert('Page not found');
},
500: function(){
alert('Page not found');
},
504: function(){
alert('Unknown host');
}
},
success: function(data){
alert(data);
}
error: function (xhr, exception, thrownError)
{
alert(xhr.status);
}
});
No, it is not possible with cross-domain (external) requests using only client-side code. This is because cross-domain requests rely on JSONP - ie, injecting a script tag that loads code from an external source. Unfortunately, the <script> element does not have anything like an onerror event.
You can handle errors with same-domain requests because these typically use XMLHttpRequest, which returns a lot of useful information like status codes and response headers.
Your best bet would be to use your local server as a proxy.
If using an absolute URL causes the domain to be different from the domain of your page (cross-domain request), then the only way to successfully execute an ajax call is to use JSONP which will cause the ajax library to use <script> tags for the cross-domain request instead of the more typical XMLHttpRequest used for same-domain requests.
You will not be able to intercept any sort of status codes from the loading of the cross-domain <script> tag.
In your case, you cannot check the status code (assuming you're not making the request from api.geonames.org).
jQuery will always return a "0" as the status if the request is cross-domain:
$.ajax({
type: 'GET',
url: 'http://someotherdomain.com/api/query',
dataType: 'json',
data: '{"first": 1, "second": 2}',
complete: function(response) { // the 'response' object has the status code
if (response.status == '200') {
// do something on success
} else if (response.status == '0') {
alert('Your request is cross-domain');
}
}
});
If the request happens to be within the same domain, you'll get a valid status code that you can check (the complete attribute of the $.ajax() function will run after any success or failure callbacks are run).
So I'm trying to make a request to the Stack Exchange API with the following jQuery code:
$.ajax({
type: 'POST',
url: 'http://api.stackoverflow.com/1.1/stats',
dataType: 'jsonp',
success: function() { console.log('Success!'); },
error: function() { console.log('Uh Oh!'); }
});
But when I open the file on my machine, in either FireFox or Chrome, and make the request, I get this error:
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token :
Uh Oh!
I don't have a clue what's going on. I know the Stack Exchange API Gzips its responses, would this cause any trouble?
You have to set an unconventional parameter to get the SO API to work. Rather than the conventional callback, you need to pass a jsonp parameter.
Furthermore, you can't do POST with JSONP.
$.ajax({
type: 'GET',
url: 'http://api.stackoverflow.com/1.1/stats',
dataType: 'jsonp',
success: function() { console.log('Success!'); },
error: function() { console.log('Uh Oh!'); },
jsonp: 'jsonp'
});
It is not possible to do cross-domain AJAX using the conventional XMLHTTPRequest. This is for security reasons (it's call the same-origin policy).
There is a workaround. script tags are not subject to this restriction. This means that you can insert a script tag into the document that calls a URL. If you define a globally-accessible function in your script and tell the remote server what that function is called, the server can pass code that wraps the data to be sent in a call to that function.
The difficulty you had here is with the StackOverflow API. Conventionally, you would use the callback argument in your request, to tell the server what your function is called. However, StackOverflow's API asks you to use the jsonp parameter instead.
Try this URL: http://api.stackoverflow.com/1.1/stats?jsonp=callme
"callme" is the name of your callback function - in your GLOBAL NAMESPACE (window object).
By the way, if you are running Firefox and have the JSONView add-on installed you can test the above URL (and yours for comparison) directly.
Result from calling the URL:
callme({
"statistics": [
...
]
})