I was working on the 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. When I debugged and checked the code it was successful on the controller side.
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',
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 post method.
The reason was my response was not in the JSON format so there was no need for 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.
Below is the working code after removing dataType: ‘json’
<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',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: function (response) {
console.log(response);
},
error: function () {
console.log('Failed ');
}
});
}
</script>
I hope this will be helpful for you if you face a similar kind of issue.