Jack Marchetti
Jack Marchetti

Reputation: 15754

jQuery not submitting my form to an asp.net mvc controller

I'm trying to submit a form via ajax to an MVC controller.

HTML

<% using (Html.BeginForm("AskQuestion", "Home", FormMethod.Post, new { id="submitquestion"})) {%>

jQuery

$("#submitquestion").submit(function(event) {
    event.preventDefault();
    var form = $(this);
    $.ajax({
        url: '<%= Url.Action("AskQuestion", "Home") %>',
        type: "Post",
        data: form.serialize(),
        success: function(result) {
            if (result.success) {
                //success method
            }
        }
    });

I'm getting no javascript errors, and my controller is not getting hit when I set a breakpoint. However, if I just set this:

$("#submitquestion").submit(); 

The form submits.

What am I doing wrong? I want to submit the form via .ajax

Upvotes: 0

Views: 2083

Answers (2)

mehul9595
mehul9595

Reputation: 1955

for submitting via ajax. add a button to html form

<input type="button" name="button" value="Test" id="test" />

And your jquery script should be like this,

$('#test').click(function () {
           var formCollection = $(this).parents('form').serialize();
          $.post('your url', formCollection, function (result) {
                alert(result);
       }); 
});

Hope this helps.

Upvotes: 0

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

Add new html button to submit and wirte your ajax submit in the click event like this,

    $("#yourButton").click(function(event) {
        event.preventDefault();
        var form = $('#submitquestion');
        $.ajax({
            url: '<%= Url.Action("AskQuestion", "Home") %>',
            type: "Post",
            data: form.serialize(),
            success: function(result) {
                if (result.success) {
                    //success method
                }
            }
        });
});

Upvotes: 2

Related Questions