Search code examples
javascriptjqueryajaxapicloudsight

Jquery Ajax API Error: 400 Bad Request


I am trying to make an Ajax POST request to an image recognition API called Cloudsight using Jquery. So far my code is:

$.ajax({
  type: "POST",
  url: "http://api.cloudsightapi.com/image_requests",
  Authorization: "CloudSight [key]",
  data: {
    remote_image_url: "https://www.google.co.uk/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png",
    locale: "en-US"
  },
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

When I try to run it I get the Error: 400 (Bad Request) What am I doing wrong? As far as I can see the code seems to be alright...


Solution

  • In case anyone else looks at this, managed to solve the problem with this code:

    $.ajax({
      method: "POST",
      url: "https://api.cloudsightapi.com/image_requests",
      beforeSend: function(xhr) {
        xhr.setRequestHeader("Authorization", "CloudSight [key]");
      },
      data: {
        "image_request[remote_image_url]": "https://www.google.co.uk/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png",
        "image_request[locale]": "en-US"
      },
      success: function(msg) {
        console.log("It worked! :D Good POST request.");
        console.log(msg);
        console.log(msg.token);
        console.log(msg.url);
        console.log(msg.responseText);
    
        token = msg.token;
      },
      error: function(msg) {
        console.log("Sorry...");
        console.log(msg);
        console.log(msg.responseText);
      }
    });

    Thanks to Mario Cezar for his help with the authorization!