0

I am using laravel 5.2, and trying to post request to external website

my ajax is:

$("#userLogin").click(function(){
    var usrEmail = $("#usr_email").val();
    var usrPassword = $("#usr_password").val();
    $.ajax({ 
        xhrFields: {
            withCredentials: true
        },
        url: 'http://username:password@website.com/APIs/public/login',
        data: {email: usrEmail, password:usrPassword},
        type: 'GET',
        error: function (request, error) {
            console.log(arguments);
        },
        success: function(data) {
            alert(data);
        }
    });
    event.preventDefault();
});

in .htaccess file

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"  
    Header set Access-Control-Allow-Credentials true
</IfModule>


but I am getting this error

"NS_ERROR_DOM_BAD_URI: Access to restricted URI denied"
Ashraf Hefny
  • 508
  • 1
  • 6
  • 20

1 Answers1

0

You can not send ajax data to a url like http://username:password@website.com/APIs/public/login This URL seems to use Basic Auth. So you need to use the beforeSend callback to add a HTTP header with the authentication information:

var username = $("input#username").val();
var password = $("input#password").val();  

function make_base_auth(user, password) {
  var tok = user + ':' + password;
  var hash = btoa(tok);
  return "Basic " + hash;
}
$.ajax
  ({
    type: "GET",
    url: "http://website.com/APIs/public/login",
    dataType: 'json',
    async: false,
    data: '{YOUR DATA + LARAVEL _token}',
    beforeSend: function (xhr){ 
        xhr.setRequestHeader('Authorization', make_base_auth(username, password)); 
    },
    success: function (){
        ...
    }
});
Sky
  • 4,244
  • 7
  • 54
  • 83
  • How can I generate that `_token` ? – Ashraf Hefny Feb 18 '16 at 11:43
  • @AshrafHefny In your `HTML`, you have to generate token. Add this in your `HTML` or `form` to generate token and then send this token with your ajax data too: `` – Sky Feb 18 '16 at 11:46
  • @AshrafHefny See this too: http://stackoverflow.com/questions/32738763/laravel-csrf-token-mismatch-for-ajax-post-request – Sky Feb 18 '16 at 11:50
  • I've generate `_token` and send it with post array, but still the same error – Ashraf Hefny Feb 18 '16 at 11:59
  • Ajax reload the page without any error or alert success message – Ashraf Hefny Feb 18 '16 at 12:21
  • @AshrafHefny Because you have to add this in your Button Click Event function: `e.preventDefault();`: `$("#submit_button").click(function (event) { event.preventDefault(); // Your Ajax });` – Sky Feb 18 '16 at 18:00