Search code examples
javascriptajaxasp.net-web-apifiddler

email AJAX POST to web api


I have client side function such as:

        var sendEmail = function (msgData) {
            jQuery.support.cors = true;
            var test = msgData;
            $.ajax({
                url         : "Api/EmailData/Send/{}",
                type        : "POST",
                data        : JSON.stringify(msgData),
                contentType : "application/json; charset=utf-8",
                success     : function (data) {

                },
                error: function (error) {

                }
            });
    };

Web controller method like so:

        [Route("Api/EmailData/Send/{clientEmail}"), HttpPost]
        public HttpResponseMessage ContactUs(string clientEmail)
        {
            EmailBody emailbody = JsonConvert.DeserializeObject<EmailBody>    (clientEmail);

            var result = MyDataRepository.ContactUs(emailbody);
            return Request.CreateResponse(result == false ?     HttpStatusCode.ExpectationFailed : HttpStatusCode.OK);
        }

My data matches the email class expected I have checked. However i still get a 404 not found. If i run in FIDDLER i get a Response Status as 204 No Content.I also include in my Fiddler header:

Content-type:application/json

How can i make it work both from my JS client side and fiddler. Any pointers appreciated. Note i have included "Allow-Access-Control-Origin" for my Client on the Data Site in IIS. I have also tried removing JSON.stringify from my JS Client as suggested somewhere esle. Not sure what I am missing. Any help. Thanks


Solution

  • It looks like you may have a malformed url. If my suspicions are correct the "/{}" at the end of url may be the source of your problems.

    Here the {} are fine as you are declaring this on api controller end

        [Route("api/stuff/data/{id:int}")]
        public Data GetDataById(int id)
        {
            // your code here
    
            return data;
        }
    

    But in your ajax call just pass the url without the curly braces

           $.ajax({
                type: 'POST',
                url: "Api/EmailData/Send",
                data: JSON.stringify(actionData),
                traditional: true,
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) { },
                error: function (e) {  }
            });