Crystal
Crystal

Reputation: 29448

dataType and contentType needed in ajax call?

I was wondering if when doing an ajax call, if you need the dataType and contentType. I'm pretty new to web and am getting confused. On the server-side, there's a servicestack endpoint that is expecting an object with two parameters,

[DataMember(IsRequired = true)]
        public long Id { get; set; }  

        [DataMember]
        public IEnumerable<long> Libraries { get; set; }

So on my ajax call, I try this:

$.ajax({
                url: 'bookshelf/' + Id + '/libraries',
                type: "POST",
                crossDomain: $.support.cors,
                data: JSON.stringify(libraryIds),
                xhrFields: {
                    withCredentials: $.support.cors
                },
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    console.log("success");

When I try to hit this endpoint, I get a 400 Bad Request. But then if I comment out the dataType and contentType:, I get a 500 Internal server error. I'm trying to understand why that is and what's happening in order to debug why my endpoint is not being hit. Thanks in advance.

Upvotes: 0

Views: 593

Answers (1)

stefan2410
stefan2410

Reputation: 2051

I am not sure, if I can help you. I use the following code ( based on your example)

In Client Model

      public class BookRequest
      {
        public int Id { get; set; }
        public string  name { get; set; }
        public string author { get; set; }
     }
       public class LibraryResponse
      {
       public bool TitleExists{ get; set; }
       public int Quantity { get; set; }
      }

then in the AppHost.Configure, I add the Route

           Routes.Add<BookRequest>("/bookshelf/{Id}/libraries", "POST,  OPTIONS");

the javascript code

           jQuery.support.cors = true;

        function BookRequestCall() {
              var  BookRequest = new Object();
               BookRequest.name = "Harry Potter";
              var Id = 33;

              var LibraryResponse;

          $.ajax({
              type: 'Post',
              contentType: 'application/json',         
              url: serverIP +'/bookshelf/' + Id + '/libraries',
              data: JSON.stringify( BookRequest ),
              dataType: "json",
              success: function (response, status, xhr) {

                      LibraryResponse = response;

               },
               error: function (xhr, err) {
                  alert(err);
               }
          });
       }

The Service side

       public LibraryResponse Post(BookRequest request)
      {
        //    request.Id =33 - request.name="Harry Potter" - request.author=null

        LibraryResponse response = new LibraryResponse();
          response.TitleExists=true;
          response.Quantity=10;
            return response;

      }

Upvotes: 1

Related Questions