1

This answer has helped me largely but hasn't fully resolved my issues. I'm using code similar to that, which is:

function getResponse() {

    var the_url = "http://www.myurl.com/api/get";

    $.ajax({
      url: the_url,
      dataType: 'jsonp',
      type: 'get',
      success: function(data) {
        var json_response = data;
        alert(data);
      }
    });
}

Basically, instead of just posting a url I need to post a curl because of authentication.

The example works fine with the simple url, but what I am wanting to use for 'the_url' is this:

var the_url = 'curl -u username:password "http://www.myurl.com/api/get"';

This is where I am having issues which means the success statement is never reached.

What is the best way to resolve this, and if it's not achievable could someone recommend the best workaround?

Thanks in advance.

Community
  • 1
  • 1
Lloyd Powell
  • 18,270
  • 17
  • 87
  • 123

3 Answers3

3

You need a page on your server that the JavaScript points at, which has the curl command in it. You can't just run cURL directly as a url like that.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $the_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
Matt Gibson
  • 14,616
  • 7
  • 47
  • 79
3

If you were using simple AJAX, then you could just add custom (basic authentication) header at the begining of your AJAX call. But you are using JSONP, which actually is equivalent to adding <script> tag to your HTML.

So what you are asking is: can I do basic authentication with <script> tag? No, you can't.

The only possibility left for you is to do server side processing, like Matt Gibson suggested.

Note however, that the browser should fire authentication dialog after the JSONP request (also see this answer). Isn't it working in your case??

Community
  • 1
  • 1
freakish
  • 54,167
  • 9
  • 132
  • 169
  • Yeh it does, unless I provide the username and password properties, then it errors. Unfortunately it's no use! – Lloyd Powell Jul 03 '12 at 14:41
  • @ThePower I see, so the only possibility for you is to implement server side, so it will fire `curl` (see Matt Gibson's answer). – freakish Jul 03 '12 at 14:48
2

Update your jquery ajax call to include the username and passward options for HTTP authentication, see the Advanced options in the documentation:

If the server performs HTTP authentication before providing a response,
the user name and password pair can be sent via the username 
and password options.

Update as pointed out in the comments, HTTP authentication simply doesn't work with JSONP, as the questioner used (didn't see that, my bad). I'll leave this answer here anyway for other people to find that don't use JSONP.

Community
  • 1
  • 1
catchmeifyoutry
  • 7,179
  • 1
  • 29
  • 26