1

I am trying to call a REST web service from JavaScript using jQuery ajax and alert the response. Here is the HTML/JavaScript code

<html>
  <head>
    <script src="js/jquery.min.js"></script>
  </head>
  <body>
     <script>
     $.ajax({ 
             type: "GET",
             dataType: "jsonp",
             url: "https://api.xyz.com/getItem/1013",
             success: function(data){        
                alert(data);
             }
         });
      </script>
    </body>
</html>

I tested the API using CURL and browser, it is working fine. The response is as follows.

{
  "endDate": "2017-04-27 10:03:17", 
  "startDate": "2017-03-28 10:03:17", 
  "status": "active"
}

When I am opening this page, I am getting the following error in the console.

SyntaxError: missing ; before statement

The browser points to the second line as error. I am not able to figure out if there is an issue with the API or client code. I tried in Firefox and Chrome browsers.

Note: I set the dataType attribute in the ajax request as jsonp, because I am using api.xyz.com from app.xyz.com which is a cross origin request. If I specify it as json, I am getting another error.

Ravi Chandra
  • 677
  • 12
  • 24
  • A correct JSONP response would be `callback({ "endDate": "2017-04-27 10:03:17", "startDate": "2017-03-28 10:03:17", "status": "active" })` – mplungjan Mar 30 '17 at 09:13
  • Your response isn't JSONP, it's JSON. They aren't directly interchangeable. I'm assuming you've changed the response type to try and get around the 'No Access Control header' warning, right? – Rory McCrossan Mar 30 '17 at 09:15
  • mplungjan, sorry I did not get what you are trying to say. Do you think I should correct the success function call back? if it is, how can I do it? – Ravi Chandra Mar 30 '17 at 09:15
  • @Rory McCrossan Yes, I tried to get around 'No Access Control header' warning and changed the dataType to jsonp. If this is not the right way, what would be the correct way? – Ravi Chandra Mar 30 '17 at 09:16
  • 1
    Unless you control the server you're calling to be able to add the CORS headers, there's no workaround for the JS code. You will not be able to call that endpoint using JS alone. You'll need to make the call server side instead – Rory McCrossan Mar 30 '17 at 09:17
  • So do I need to make my api server (api.xyz.com/getItem/123) to accept cross origin requests? Yes I control the api.xyz.com server, it is built in Python Flask frame work and deployed on Apache using wsgi. – Ravi Chandra Mar 30 '17 at 09:20
  • Either that OR serve the page with the script from the same server and have `url: "/getItem/1013",` – mplungjan Mar 30 '17 at 09:30
  • Thank you, I have added the 'Access-Control-Allow-Origin: http://app.xyz.com' headers in the API response and changed the data type to json, it started working. – Ravi Chandra Mar 30 '17 at 09:38

0 Answers0