Sarah Ward
asked on
AJAX request returns 200 OK... but also fails
I have an ASP.NET MVC Web API project using an AJAX script that POST data to my database. This script includes a simple "success" and "error" function that returns a console.log message so I know if the script worked.
This AjAX call works and the data from the form is being Posted (Inserted) into the database. Great!
However... The AJAX code executes the "error" function even when the post is successful for some reason and I cannot figure out why.
Here's my code...
AJAX
Here's my controller.
What am I doing wrong?
This AjAX call works and the data from the form is being Posted (Inserted) into the database. Great!
However... The AJAX code executes the "error" function even when the post is successful for some reason and I cannot figure out why.
Here's my code...
AJAX
$.ajax({
url: "/api/simpleEvents",
method: "post",
data: formData,
success: function (data) {
console.log("Yeah! It worked.");
console.log(data);
},
error: function (result) {
console.log("Something unexpected happened.");
console.log(result.status + ' ' + result.statusText);
}
});
Here's my controller.
// POST /api/SimpleEvents
[HttpPost]
public IHttpActionResult CreateNewSimpleEvent(SimpleEventDto simpleEventDto)
{
if (!ModelState.IsValid)
return BadRequest();
var newSimpleEvent = Mapper.Map<SimpleEventDto, SimpleEvent>(simpleEventDto);
_context.SimpleEvents.Add(newSimpleEvent);
_context.SaveChanges();
simpleEventDto.Id = newSimpleEvent.Id;
return Created(new Uri(Request.RequestUri + "/" + newSimpleEvent.Id), simpleEventDto);
}
What am I doing wrong?
ASKER
Let me try this and I'll let you know if it was successful.
ASKER
Hi Miguel Oz - I've tried to implement both of your suggestion and in each case the result was.
1.) The data never posted to the database
2.) the (.error) of the AJAX fired.
Any other thoughts on how I can fix this?
1.) The data never posted to the database
2.) the (.error) of the AJAX fired.
Any other thoughts on how I can fix this?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
This helped me quite a bit. Thank you for you time.
Open in new window
and your JS code should beOpen in new window
Note: If this is a web api call you should return the object directly:
public SimpleEventDto CreateNewSimpleEvent(Simpl
{
if (!ModelState.IsValid)
return BadRequest();
var newSimpleEvent = Mapper.Map<SimpleEventDto,
_context.SimpleEvents.Add(
_context.SaveChanges();
simpleEventDto.Id = newSimpleEvent.Id;
return simpleEventDto;
}
If more help needed please post VS/Web API version