The AJAX call does not affect the Web API method

advertisements

I am using one WebAPI method which needs to be called through jQuery AJAX. Below is the jQuery code used for the AJAX call:

var BlogAndStoryComment = new Object();
BlogAndStoryComment.CommentID = 0;
BlogAndStoryComment.CommentUserName = userName;
BlogAndStoryComment.CommentText = commentText;
BlogAndStoryComment.CommentApprovedByUserID = 0;
BlogAndStoryComment.CommentDate = "date";
BlogAndStoryComment.HtmlComment = commentHtml;
BlogAndStoryComment.CommentIsSpam = 0;
BlogAndStoryComment.CommentIsApproved = 0;
BlogAndStoryComment.CommentEmail = email;
BlogAndStoryComment.CommentCount = 0;
BlogAndStoryComment.OnCommentID = 0;
BlogAndStoryComment.BlogID = blogID;
BlogAndStoryComment.SiteID = siteID;
BlogAndStoryComment.RowCount = 0;

$.ajax({
  url: "http://localhost:55052/API/comments/GetAndPostBlogComments",
  type: "POST",
  data: JSON.stringify(BlogAndStoryComment),
  contentType: 'application/json; charset=utf-8',
  dataType: "json",
  success: function(response) {},
  error: function(jqXHR, textStatus, errorThrown) {},
  failure: function(response) {}
});

This is my WebAPI method:

[Route("api/comments/GetAndPostBlogComments")]
[VersionedRoute("", 1)]
[ResponseType(typeof(HttpResponseMessage))]
[HttpPost]
public IHttpActionResult GetAndPostBlogComments([FromBody] BlogAndStoryComment comment)
{
}

When I call this method from the AJAX call it is hitting the error function which gives me a statustext or "error". However when I call through Postman then method is working correctly. What is the issue?


You can try doing something like this and use the jquery param method

    var postData = {
        name : 'name'
    }

    $('#testPostMethod').bind("click", GeneralPost);
    function GeneralPost() {
        $.ajax({
            type: 'POST',
            url: '../api/comments/GetAndPostBlogComments',
            //url: '~/api/comments/GetAndPostBlogComments',
            data: $.param(postData,true),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json'
        });
    }