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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
Miguel OzSoftware 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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Lynn CurtDeveloperAuthor Commented:
This helped me quite a bit.  Thank you for you time.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.