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
$.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);
                    }
                });

Open in new window


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);
            
        }

Open in new window


What am I doing wrong?
Lynn CurtDeveloperAsked:
Who is Participating?
 
Miguel OzConnect With a Mentor Software EngineerCommented:
From my previous post "If more help needed please post VS/Web API version If more help needed please post VS/Web API version".

Additionally, I need you the following information:
General
- Post code for your models shown in your code or any any relevant validation.
Alternatives1/2:
 - Error details: console log info
-  Add a break point at if (!ModelState.IsValid) and step your code. My fear is that your code is returning at return BadRequest() if this is the case please replace these two lines with:
 if (!ModelState.IsValid)
        {
            string errordetails = "";
            var errors = new List<string>();
            foreach (var state in ModelState)
            {
                foreach (var error in state.Value.Errors)
                {
                    string p = error.ErrorMessage;
                    errordetails = errordetails + error.ErrorMessage;
                }
            }
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("error", errordetails);
            return Request.CreateResponse(HttpStatusCode.BadRequest, dict); //add a break point here and post errors
        }

Open in new window


Note: I do not think you Ajax code was working at all as you originally stated unless you have added validation to your model afterwards

Form above info, we should be able to determine if validation is your issue if that is the case please try again with proper valid values and if that works it means that you should add some Java script  validation code before making the Ajax call.
0
 
Miguel OzSoftware EngineerCommented:
Your controller shall return a Json result not a URI:
[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 Json(new { simpleEvent = simpleEventDto }, JsonRequestBehavior.AllowGet); 
    
}

Open in new window

and your JS code should be
console.log(data.simpleEvent);

Open in new window


Note: If this is a web api call you should return the object directly:
public SimpleEventDto 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 simpleEventDto;
   
}

If more help needed please post VS/Web API version
0
 
Lynn CurtDeveloperAuthor Commented:
Let me try this and I'll let you know if it was successful.
0
 
Lynn CurtDeveloperAuthor Commented:
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?
0
 
Lynn CurtDeveloperAuthor Commented:
This helped me quite a bit.  Thank you for you time.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.