I was working on ASP.NET Core MVC project. I was submitting the form using $.ajax but once the submit response is succeded then it was not going to the Ajax Success event. It was always going to the error event.

Below is my form submit code:

<script type="text/javascript">
    function submitStudent() {
       var data = {
            Id: parseInt($("#studentId").val()),
            Name: $("#name").val(),
            Email: $("#email").val(),
            Phone: $("#phone").val()
        }
        console.log(data);       
        $.ajax({
            type: 'POST',
            url: '/Home/AddStudent',//ApiController call
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(data),
            success: function (response) {
                console.log(response);
            },
            error: function () {
            console.log('Failed ');
           }
        });       
       }
</script>

Below is my Controller code on Submit button click:

 [HttpPost]
        public async Task<IActionResult> AddStudent([FromBody] StudentModel student)
        {
            if (!ModelState.IsValid)
                return BadRequest("Enter required fields");
            //Insert code;
            return this.Ok($"Form Data received!");
        }     

Later on, I have found the solution to this. I need to remove the dataType: ‘json’, line from the $.ajax method.

The reason was my response was not in the json format so there was no need of the dataType: ‘json’ line in the submit method. In my case, the returned response was in text format that’s why it was not going to success event.

Solution: Remove dataType: ‘json’ line.

I hope this will be helpful for you if you face similar kind of issue.

Leave a Reply

Your email address will not be published. Required fields are marked *