1

I'm using a ajax request for calling a REST service and I'm using post method to pass parameters. I get the response from the REST service when I pass the parameters in the REST URL, but when I send the parameters through data object I dont get any response. Am I doing anything wrong?

$.ajax({
  type: "POST",
  url: "myURL?ID=5087&name=hello",
     data:{
        'id':'5087',
        'name':'hello',

    },
  success: function(msg){
      alert('wow' + msg);
  }

});

In the above request If i remove the parameters from the URL and keep the data object as it is, I'm not getting any response

Nikhil Bharadwaj
  • 867
  • 4
  • 24
  • 42

1 Answers1

0

You're not doing anything wrong, the issue is that the API is not following semantic rules.

When receiving a POST request the data should be sent through the body of the request except for possibly an identifier which can be in the URL. For this reason, when you specify type: 'POST' and provide an object to data, that's where jQuery puts the information you send.

However, the API you're calling is retrieving the data you send in the POST request via the URL, when that should in fact be done with a GET request.

Due to this you will have to manually append the data to the URL in application/x-www-form-urlencoded format, as you are doing in the working example.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Could also be that post is expecting json contentType – charlietfl Jul 19 '17 at 10:34
  • Possible, but either way none of the values should be read from the querystring, so the request to `myURL?ID=5087&name=hello` should fail – Rory McCrossan Jul 19 '17 at 10:34
  • 1
    Because if you set `type: 'post'` and use `data` jQuery will put the values in the body of the request, not the querystring – Rory McCrossan Jul 19 '17 at 10:36
  • @RoryMcCrossan, Using the GET method with queryString doesn't return anything either. Is there any way I can use the POST method and date object to call the service apart from doing through appending? – Nikhil Bharadwaj Jul 19 '17 at 10:38
  • That's my point - because of the bad design of the API you will have to use POST yet still manually build the querystring (or append the result of `serialize()` if you're using a `form` element) – Rory McCrossan Jul 19 '17 at 10:40
  • @RoryMcCrossan, Thanks. That was a great insight to APIs. – Nikhil Bharadwaj Jul 19 '17 at 10:41