2

I use the public dog API: https://dog.ceo/dog-api/ .It is working with postman, curl and on browser but not able to call it using AJAX. Anyone please provide inputs what I am doing wrong here:

$.ajax({
    url: "https://dog.ceo/api/breeds/image/random",
    type: "GET",
    dataType: 'script',
    success: function(data){console.log(data)},
  });
Rehan Umar
  • 179
  • 1
  • 12
M Kumar
  • 33
  • 4

2 Answers2

2

The issue is because the response type is JSON, hence you need to set dataType: 'json', not script:

$.ajax({
  url: "https://dog.ceo/api/breeds/image/random",
  type: "GET",
  dataType: 'json',
  success: function(data) {
    console.log(data)
  },
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • That's because that domain does not return CORS headers in the response, so you will not be able to make the call to it from client-side JS. – Rory McCrossan Jun 07 '18 at 09:15
  • can i pass in ajaxx `Access-Control-Allow-Origin: *` – M Kumar Jun 07 '18 at 09:18
  • No, that header has to come *from* the server. There is absolutely nothing that can be done in JS to fix this issue. – Rory McCrossan Jun 07 '18 at 09:19
  • See [this question](https://stackoverflow.com/questions/20035101/why-does-my-javascript-get-a-no-access-control-allow-origin-header-is-present) for more information – Rory McCrossan Jun 07 '18 at 09:20
1

You have dataType: 'script' change it to json because api is returning response in json

$.ajax({
    url: "https://dog.ceo/api/breeds/image/random",
    type: "GET",
    dataType: 'json',
    success: function(data){console.log(data)},
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Albert Einstein
  • 7,472
  • 8
  • 36
  • 71