pbz
pbz

Reputation: 9085

Post with jQuery AJAX to ASP.NET MVC 1.0

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:

Thanks.

EDIT:

The html looks like this:

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

Upvotes: 3

Views: 7655

Answers (1)

womp
womp

Reputation: 116977

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.

Upvotes: 4

Related Questions