0

I have a problem to posting data to WebaPi controller using Jquery ajax in html page .. when i test through fiddler it's coneected and working fine , but when i try to using Ajax it give error only..

here is my sample code ..

var bookData = {
                "CurrentCompany": "BizSight Sample Product Company",
                "CompanyName": CompanyName,
                "LegalName": "Biztech",
                "Address1": Address1,
                "Address2": Address2,
                "City": City,
                "State": State,
                "Phone": Phone,
                "ZipCode": ZipCode,
                "Fax": Fax,
                "Email": Email,
                "Website": Website,
                "CountryID": 1,
                "federalTaxID": 1,
                "CurrentUser": CurrentUser,
                "BusinessType": BusinessType,
                "CurrentFiscalYear": Jsondate
            };
            $.ajax({
                type: "POST",
                cache: false,
                url: "http://77b2130d5c3446eea4e4210c51529230.cloudapp.net:8080/Create/",
                data: JSON.stringify(bookData),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (data, status, jqXHR) {
                        var result = JSON.stringify(data);
                    $("#loading").show();
                    alert("success..." + result);
                },
                error: function (xhr) {
                    $("#loading").show();
                    alert("Test3:" + xhr.statusText);
                }
            });

When i post data from html and check fiddler it give message like below image

enter image description here am i missing anything in this code..? fiddler it self it's working but frmo html page not working .. can you please help me how to resolve and achieve this

My Api class `

public class CreateController : ApiController
{
    public static string CompanyName = " ";
    public static string con;
    public static string sqlConnection;
    public static string DatabaseName;
    string TrustedConnection = "Yes";
    string DBServer = " ";
    string FilePath = null;
    string testFirstline = " ";
    //clsLog objLog = new clsLog();
    bool isSuccess = false;




    public string Post(DatabaseCls cls)
    {
        string ReturnMessage = "Success";

        // ReturnMessage = "Hello  " + id + "_" + parameter1 + "_" + parameter2 + "_" + parameter3 + "_" + parameter4 + "_" + parameter5 + "_" + parameter6 + "_" + parameter7 + "_" + parameter8 + "_" + parameter9 + "_" + parameter10 + "_" + parameter11 + "_" + parameter12 + "_" + parameter13 + "_" + parameter14 + "_" + parameter15;
      return ReturnMessage;
    }}

Thanks Victor .A

9
  • are you sure you need to do this : data : JSON.stringify(bookData), Commented Nov 3, 2015 at 12:48
  • Can you show the error you are getting, the webAPI method and the class you are trying to serialize into? If the method is found when calling it from ajax but you are getting an error then most likely your object will not serialize into the type you have specified or your webAPI has not been set up to allow CORS requests. Commented Nov 3, 2015 at 12:53
  • @timothy , i need to pass json data to my api .. is there any alternate ..? Commented Nov 3, 2015 at 12:56
  • @Stephen , it does not give any message except error string only..... but when i test fiddler post method became Option .. Commented Nov 3, 2015 at 12:59
  • Ok the options error you see is the CORS issue I was referring to, Your API has to be set up to allow cross site requests. Commented Nov 3, 2015 at 13:00

1 Answer 1

1

The OPTIONS error you are seeing is because of CORS. You need to add this to your WebAPI in the Startup.cs to allow cross site requests.

public void Configuration(IAppBuilder app)
{
    app.UseCors(CorsOptions.AllowAll);

    var formatters = configuration.Formatters;

    //-- Disable XML support
    formatters.XmlFormatter.SupportedMediaTypes.Clear();

    var jsonFormatter = formatters.JsonFormatter;
    jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json-patch+json"));
    jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
    jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    jsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
    jsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
}

(edit, suggestion)

[RoutePrefix("api")]
public class CreateController : ApiController
{
    [HttpPost, Route("create")]
    public IHttpActionResult Post([FromBody]DatabaseCls cls)
    {
        try
        {
             return Ok(new { success = true });
        }
        catch
        {
             return InternalServerError();
        }
    }
}

$.ajax({
  type: "POST",
  cache: false,
  url: "http://77b2130d5c3446eea4e4210c51529230.cloudapp.net:8080/api/Create", //note the additional "api" in url
  data: JSON.stringify(bookData),
  dataType: "json",
  success: function (data, status, jqXHR) {
       var result = JSON.stringify(data);
       $("#loading").show();
       alert("success..." + result);
   },
   error: function (xhr) {
       $("#loading").show();
       alert("Test3:" + xhr.statusText);
   }
});
Sign up to request clarification or add additional context in comments.

5 Comments

It's in System.Web.Http, If you can't add it then you can just remove it and change your route to this: [HttpPost, Route("api/create")]
Hi Stephen , This is not helping to me.. i tried same thing what you suggest me .. it gives 415 exception when i check in fiddler...
You may just need to allow json in your webApi. I edited the answer to show this. Also, when using fiddler you need to specify the content type. Content-type: application/json
I would also look into a free app called Postman which is much nicer for testing your api than fiddler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.