0

I have a form which I am trying to submit with Ajax / without reloading the page.

The Ajax call is hitting the server, but it doesn't seem to be calling the function. I've tried both $.post and $.ajax. Neither seem to work. I had something extremely similar working a few weeks back, but now I can't replicate it. (The end goal is to return the model as a partial view, in order to see the validation.)

Using Firefox, the controller method is immediately hit. Using Chrome, the browser tab seems to lock up. It sometimes hits the controller after a delay. (The model information is coming over accurately.)

What am I doing wrong here?

I have my partial view here:

<% using (Ajax.BeginForm("CreateSimpleReport", "Main", new AjaxOptions { HttpMethod="POST" }, new { id="CreateSimpleReport" })){ %>
   <%: Html.ValidationSummary(false, "Report creation was unsuccessful. Please correct the errors and try again.", new { @class = "validation_summary" })%>
   <% Html.EnableClientValidation(); %>
   <div class="col">
<div class="row">
    <div class="label">
        <%: Html.LabelFor(m => m.Name)%>
    </div>
    <div class="field">
        <%: Html.TextBoxFor(m => m.Name, new { @class = "input texbox" })%>
        <%: Html.ValidationMessageFor(m => m.Name, "*")%>
    </div>
</div>
<div class="row">
    <div class="label">
        <%: Html.LabelFor(m => m.Description)%>
    </div>
    <div class="field">
        <%: Html.TextBoxFor(m => m.Description, new { @class = "input texbox" })%>
        <%: Html.ValidationMessageFor(m => m.Description, "*")%>
    </div>
</div>
<div class="row">
    <div class="label">
        <%: Html.LabelFor(m => m.Quantity)%>
    </div>
    <div class="field">
        <%: Html.TextBoxFor(m => m.Quantity, new { @class = "input texbox" })%>
        <%: Html.ValidationMessageFor(m => m.Quantity, "*")%>
    </div>
</div>
<div class="right"><input type="submit" class="button" value="Create Report" /></div>
</div>
<% } %>

Controller:

[HttpPost]
public string CreateSimpleReport(SimpleReportModel model)
{
    if (ModelState.IsValid)
    {
        // do something
        return "success";
    }
    else
    {
        return "failure";
    }
}

And finally, the jQuery:

        $('#CreateSimpleReport').on('submit', function (e) {
            var $this = $(this);
            $.post((this), (this), function(data) {
                alert('finish');
            });
//            $.ajax({
//                type: 'POST',
//                url: (this),
//                data: (this),
//                success: function () {
//                    alert('success');
//                },
//                error: function (jqXHR, textStatus, errorThrown) {
//                    alert('error');
//                }
//            }); // end ajax call
        });
Joakim
  • 2,217
  • 15
  • 20
Cody
  • 8,686
  • 18
  • 71
  • 126

4 Answers4

1

You should not be mixing Ajax.* helpers with jQuery.ajax. If you use the Ajax.BeginForm helper then simply include the jquery.unobtrusive-ajax.js script (ASP.NET MVC 3) or the MicrosoftAjax.js and MicrosoftMvcAjax.js scripts (ASP.NET MVC 2) and subscribe to a success callback in the AjaxOptions.

If you decide to use jQuery.ajax manually then use a standard Html.BeginForm:

<% using (Html.BeginForm("CreateSimpleReport", "Main", FormMethod.Post, new { id = "CreateSimpleReport" })) { %>

and then:

$(function() {
    $('#CreateSimpleReport').on('submit', function() {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function(result) {
                alert('AJAX success');
            }
        });

        // make sure you return false to cancel the default event
        return false;
    });
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Is there any reason why this would switch to new page with the result as the contents? I am returning false.. – Cody May 07 '12 at 16:06
  • No idea. one possible cause is javascript error on your page which prevents the script from executing and reaching the return false line. – Darin Dimitrov May 07 '12 at 16:11
0
$.post((this), (this)

This (no pun intended) makes no sense. You cannot POST to a DOM element with the arguments being a DOM element, too. Besides that you need to e.preventDefault(); (or return false;) to avoid a regular form submission. So when your callback would fire, the page has already been reloaded.

The easiest way to submit a form via AJAX is by using the jQuery form plugin.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • It didn't make sense to me either, but I used it before (I had seen it in an example), and the model comes through with the proper values. – Cody Apr 25 '12 at 22:12
  • You should change it anyway. And probably stay away from that example (sounds a bit like something you'd find on w3schools dot com) – ThiefMaster Apr 26 '12 at 05:38
0

You are already using Ajax.BeginForm, why do you need jQuery script to do ajax?

Have you included jquery.unobtrusive-ajax.js ?

Binz
  • 36
  • 4
0

Regarding mixing microsoft ajax and validation with custom jquery ajax I have a similar thread here: Mixing Microsoft MVC ajax and validation helpers with native jquery ajax

Community
  • 1
  • 1