skip to Main Content

I have this simple ajax method:

$.ajax({
     type: 'POST',
     url: 'http://localhost:1195/widget/postdata',
     datatype: "jsondata",
     async: false,
     success: function (data) {
          alert("ok")
     },
     error: function (data) {
          alert(data.status + ' ' + data.statusText);
     }
});

And this simple method in c#:

[HttpPost]
public JsonResult PostData()
{
     return Json("1");
}

When I check the inspector console I have “1” in response but my ajax method always goes to error function.

Why is it so?

2

Answers


  1. In your AJAX call it should be dataType: "json" and not datatype: "jsondata". You can refer to the docs

    Also use @Url.Action tag in your url call: url: '@Url.Action("postdata", "widget")'

    For a small test, I have used the following AJAX call to the same controller method that you have posted and I am getting the correct result:

        $(document).ready(function () {
            $("#button_1").click(function (e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url:'@Url.Action("PostData", "Home", null, Request.Url.Scheme)',
                datatype: "json",
                async: false,
                success: function (result) {
                    alert(result);
                },
                error: function (error) {
                    alert(error);
                }
            });
          });
        });
    </script>
    
    <button id="button_1" value="val_1" name="but1">Check response</button>
    

    Output:

    enter image description here

    Login or Signup to reply.
  2. Change the Ajax request to the following :

    $.ajax({
     type: 'POST',
     url: '/widget/postdata',
     datatype: "json",
     async: false,
     success: function (data) {
          console.log(data);// to test the response
     },
     error: function (data) {
          alert(data.status + ' ' + data.statusText);
     }
    });
    

    Always use relative URL instead of full URL that contains the domain name, this will make the deployment easier so you don’t have to change the URls when going live

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search