3

I'm doing a jQuery AJAX post like this:

  var form = $("#formid");
  form.submit(function()
  {      
    $.ajax(
    {
      type: "POST",
      url: form.attr("action"), // points to NewClient
      data: form.serialize(),
      success: function(msg) { alert('ok ' + msg); },
      error: function(req, status, err) { alert('err=' + err + ' status=' + status); }
    });
    return false;
  });

On the ASP.MVC side I have something like this:

[AcceptVerbs(HttpVerbs.Post)]
public virtual ActionResult NewClient()
{
  // just a test...
  return null;
}

What's the right result type for the NewClient function for jQuery to work right? As is right now it works in FF and Chrome, but fails in IE8 (works in IE7) -- i.e. in IE8 I get the error alert (edit: the error was because of a "debugger;" call in the JS call). In any case, what's the recommended way to:

  • Pass a form to ASP.NET MVC via jQuery (the $().serialize() seems to work fine, is this the recommended way?)
  • From the server side to return either Success or Failure, and if it fails some kind of message I could display to the client. How do I tell jQuery that the method / call failed or not?

Thanks.

EDIT:

The html looks like this:

<form id="formid" action="/client/newclient">
   ... input fields ...
</form>

1 Answer 1

4

form.serialize() is the correct way to post a form in jQuery.

In terms of error handling, you've got the gist of it. jQuery will only consider the request as failed if the server returns a failure HTTP code. If you want to determine a "logical failure", i.e. your application failed somehow, and wants to return an html/json response indicating what went wrong (which would have a valid HTTP code), then you need to add an error flag to your response, and check for it in the "success" handler.

I always liked Ben Nadel's approach to it.

I've also answered a similar question before with a pretty detailed code example.

Before restructuring all your jQuery code though, I would look at what's going on in IE8 with a tool like Fiddler.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm looking at it right now trying to figure out why it won't work with IE8.
It seems I got the error message because I had a "debugger" in the JavaScript code; for some reason it doesn't like that. If I take it out it works fine.
I like the solution in your post. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.