-2

I am trying to get the JSON response from a URL having authentication, The code is mentioned below

$.getJSON({
    'url': 'http://test.etravelsmart.com/etsAPI/api/getStations',
    'beforeSend': function(xhr) {
        //May need to use "Authorization" instead
        xhr.setRequestHeader("Authentication","Basic " + encodeBase64("*****" + ":" + "****"))
    },
    success: function(result) {
         alert(result);
        $.each(result, function(i, field) {
               var StationId = field.stationId;
               var StationName = field.stationName;
                $("#txtLabourId").append("<option>" + StationName + "</option>");
           });
    }
 });

I am trying to display the values in a

<select id="txtLabourId"></select>

But having authentication i am not getting the response. All help appreciated

JRG
  • 4,037
  • 3
  • 23
  • 34
Shreyas Achar
  • 1,407
  • 5
  • 36
  • 63

1 Answers1

0

The remote resource http://test.etravelsmart.com/etsAPI/api/getStations is not available to you via JavaScript. See the other question and answers for information.


You also have some errors regarding your use of the jQuery methods.

You are passing an AJAX config object where $.getJSON() expects a url string.

Instead, use $.ajax() where you can also take advantage of the username and password properties...

$.ajax({
  url: 'http://test.etravelsmart.com/etsAPI/api/getStations',
  dataType: 'json',
  username: '*****',
  password: '****'
}).done(function(result) {
  // etc
}).fail(function(jqXHR, textStatus, errorThrown) {
  console.error(textStatus, errorThrown)
})
Phil
  • 157,677
  • 23
  • 242
  • 245
  • No sir, Still i am not able to retrieve the data – Shreyas Achar Aug 16 '17 at 07:05
  • @ShreyasBandimat and the glaring error message in your console is...? – Phil Aug 16 '17 at 07:07
  • 1
    XMLHttpRequest cannot load http://test.etravelsmart.com/etsAPI/api/getStations. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 401. – Shreyas Achar Aug 16 '17 at 07:07
  • Its the error i am getting in console – Shreyas Achar Aug 16 '17 at 07:08
  • do you have access to the server code ? the easiest way to solve this problem is to add this header `Access-Control-Allow-Origin: *` on server side – Olivier Boissé Aug 16 '17 at 07:31
  • @oliv37 I suggest you post your comment on the question above so Shreyas can see it. This is just an answer – Phil Aug 16 '17 at 09:01