Shukhrat Raimov
Shukhrat Raimov

Reputation: 2267

AJAX calls to a controller action are not consistent

I have a simple form in ASP.NET MVC4 with one textbox and two buttons.

@using (Html.BeginForm("Steps", "Technique", new 
                      { step = ViewBag.step + 1, 
                         techniqueId = @Model.Krok.TechniqueId
                      },
                      FormMethod.Post,
                      new { id = "theForm" })
       )
 { 
    <label>@Model.Krok.Text</label>

    @Html.HiddenFor(model => model.Krok.Id)
    @Html.HiddenFor(model => model.Krok.Poradi)
    @Html.HiddenFor(model => model.Krok.TechniqueId)
    @Html.TextBoxFor(m => m.Text)
    if (@Model.Krok.HasMultipleAnswers)

    <input type="button" value="Add One More" id="AddButton" />

    <input type="submit" value="Next Step" id="submit_btn" />
}
<input type="button" value="Add One More" id="add_btn" />
<input type="submit" value="Next Step" id="submit_btn" />

The first button creates one more textbox using jQuery and the second button processes all the textboxes and stores the data to SQL.

$("#add_btn").click(function () {
        $("#theForm").append("<br /><label> one more attribute</label>")
                     .append("<input type = 'Text' id='_addText' />");
    });

As soon as the button that processes the form is clicked, jQuery handles this event and send the data to a controller action.

$("#submit_btn").click(function () {
        alert("clicked!")
        var options = {};
        options.url = "/Technique/AjaxTest";
        options.type = "POST";
        options.data = JSON.stringify(
        {
            answer: $("#_addText").val()
        });
        options.contentType = "application/json";
        options.dataType = "json";
        options.error = function (jqXHR, status, err) { alert(status); };
        $.ajax(options);
    });

But this controller action is not rendering consistently, meaning that sometimes the action is fired and processes as it has to process, but another time the action is not even called (I was using debugger). Why it is not working consistently?

Upvotes: 0

Views: 179

Answers (1)

dyson
dyson

Reputation: 896

It doesn't appear that the default action of the button click i.e. the HTTP POST submission of the form, is being suppressed, and this is possibly occurring before the jQuery acts.

If you have

$("#submit_btn").click(handleSubmit);

function handleSubmit(e) {
    e.preventDefault();
    e.stopPropagation();

    alert("clicked");
    ......
}

you will then have the HTTP POST out of the way.

Upvotes: 3

Related Questions