Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Authentication with jQuery.ajax request and jsonp

I have some local html/js files with which I'd like to invoke some remote servers via https and eventually use Basic Authentication for the request.

I am encountering two problems. First is that if I don't specify 'jsonp' for the dataType, jQuery.ajax() request returns the error:

Access to restricted URI denied code: 1012

Are my requests considered cross-domain because my main work file is stored locally, but retrieving data from a server elsewhere?

So fine, I update the call so it now looks like:

$.ajax({ 
     url: myServerUrl,
     type: "GET", 
     dataType: "jsonp", // considered a cross domain Ajax request if not specified
     username: myUsername,
     password: myPassword,

     success: function(result)
     {
        // success handling
     },
     error: function(req, status, errThrown){
         // error handling
     }
})

Because I need to use Basic Authentication, I'm passing in the username/password but if I monitor the request, I don't see it being set and additionally, the server sends an error response since it doesn't have the expected info.

Additionally, because I have jsonp set, beforeSend won't get invoked.

How do I pass along the credentials using Basic Authentication for this request?

like image 202
Abel Vita Avatar asked Aug 25 '10 23:08

Abel Vita


People also ask

Can JSONP be used with Ajax?

JSONP has nothing to do with Ajax, since it does not use XMLHttpRequest. Instead, it dynamically inserts <script> tag into a webpage.

What is JSONP in Ajax?

JSONP stands for JSON with Padding. Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object.

What is JSONP jquery?

JSONP (which stands for JSON with Padding) builds on this technique and provides us with a way to access the returned data. It does this by having the server return JSON data wrapped in a function call (the “padding”) which can then be interpreted by the browser.


1 Answers

The short version is you can't do this. Your suspicions are correct, because you're local and these files are remote, you can't access them, you're being blocked by the same-origin policy. The work-around for that is JSONP, but that really doesn't seem to apply to your situation...

JSONP works differently, it's a GET request via a <script> tag include to get the file, so you're not sending special headers or anything.

You'll need to proxy the request through the server you're on (the domain of where this script is running) or another proxy option, but going from the client to another domain is blocked, mainly for security reasons.

like image 163
Nick Craver Avatar answered Sep 17 '22 15:09

Nick Craver