0

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

0

2 Answers 2

2

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
                }
            }
        });
});
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.