Home > Software engineering >  Ajax success not executing after POST action is called ASP.NET MVC
Ajax success not executing after POST action is called ASP.NET MVC

Time:05-13

I have this form:

@{ using (Html.BeginForm(@*"MakeOffer", "Product", FormMethod.Post, *@new { id = "offerForm", productId = Model.ProductId, sellerId = Model.SellerId }))
{
@Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })
@Html.TextBoxFor(modelItem => modelItem.Price, "{0:#.#}", new { placeholder = "Input your price", id = "offerText", name="offerPrice" })
@Html.HiddenFor(modelItem => modelItem.ProductId)
@Html.HiddenFor(modelItem => modelItem.OffererId)
@Html.HiddenFor(modelItem => modelItem.SellerId)
<input id="offersubmit" type="submit"  value="Submit" />
}

This is my Ajax function:

<script>

    $(document).ready(function () {
        $("#offersubmit").click(function (e) {
            if ($(this).valid()true) {
            var valdata = $("#offerForm").serialize();
            alert(valdata);
            $.ajax({
                url: "/Product/MakeOffer",
                type: "POST",
                dataType: 'json',
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                data: valdata,
                success: $(document).ready(function () {
                    $('#offerText').val('');
                })
            })
            }
        });
    });
</script>

Now the form is getting passed to the MakeOffer action, but I'm getting a 500 error and the success function isn't getting called. These are my script tags at the end:

<script src="~/Scripts/jquery-3.6.0.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

CodePudding user response:

You need to remove the $(document).ready(..) portion of the success callback.

It should be

success: function(data)
{
    $('#offerText').val('');
}
  • Related