Isanka Thalagala
Isanka Thalagala

Reputation: 1721

Ajax post request to .NET Core action and getting result not working

I need to implement email sending modal popup and I'm almost done except ajax send request not hit to success or failure

When I click the send button (id:end-email) It successfully hit the .NET Core action and action return status correctly.

But the problem is my ajax call not waiting for the result and automatically closing popup which is not required. I need to show the message instead of closing popup.

<div id="sendemail-window" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="sendemail-window-title">
    <div class="modal-dialog" style="width: 50%;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" style="font-weight:600;" id="sendemail-window-title">Shipment Request Email </h4>
            </div>
            <form  id="InStockPendingShipments" name="InStockPendingShipments">
                <input type="hidden" id="selectedPOIds" name="selectedPOIds" value="" />
                <div class="form-horizontal">
                    <div class="modal-body">
                        <div class="form-group">
                            <div class="col-md-2">
                                <nop-label asp-for="SendEmail.Subject" />
                            </div>
                            <div class="col-md-9">
                                <nop-editor asp-for="SendEmail.Subject" />
                                <span asp-validation-for="SendEmail.Subject"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-md-2">
                                <nop-label asp-for="SendEmail.Message" />
                            </div>
                            <div class="col-md-9">
                                <nop-textarea asp-for="SendEmail.Message" />
                                <span asp-validation-for="SendEmail.Message"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-md-1">
                                &nbsp;
                            </div>
                            <div class="col-md-10">
                                <ul id="selected-po-list" class="selected-po-list">
                                </ul>
                            </div>
                        </div>

                    </div>
                    <div class="modal-footer">

                        <div class="input-group input-group-short">
                            <label id="lblSaveResult" name="lblSaveResult" style="margin-top: 10px;font-weight: 500;"></label>
                        </div>
                        <div class="form-group">
                            <div class="col-md-1">
                                &nbsp;
                            </div>
                            <div class="col-md-10">
                                <button class="btn btn-primary" id="send-email">
                                    Send Email
                                </button>
                            </div>
                        </div>
                    </div>

                    <script type="text/javascript">
                       $(document).ready(function () {
                            $('#send-email').click(function () { 
                                $.ajax({
                                        type: "POST",
                                        url: '@Url.Action("SendInStockRequestEmail","InStockPendingShipments")',
                                       data: emailData(),
                                         success: function (msg) {
                                       
                                             alert("111 success");
                                        },
                                    error: function (req, status, error) {  
                                            alert(22225,error);
                                        }
                                    })
                                    .done(function () {
                                        alert("success");
                                    })
                                    .fail(function () {
                                        alert(44444,"error");
                                    });

                                 });

                        });


                          function emailData() {

                                        var data = {
                                            SelectedPOIds: $("#selectedPOIds").val(),
                                            Message: $('#@Html.IdFor(model => model.SendEmail.Message)').val(),
                                            Subject: $('#@Html.IdFor(model => model.SendEmail.Subject)').val()

                                        };

                                        addAntiForgeryToken(data);
                                        return data;
                                      }


                        $('#sendemail-window').on('show.bs.modal', function () {
                            $('#SendEmail_Message').val('');
                             document.getElementById("SendEmail_Message").innerHTML = "";
                            getInStockProductListByIds($("#selectedPOIds").val());

                        });

                            function getInStockProductListByIds(selectedPOsIds) {
                             var idListData = {
                                Ids:  selectedPOsIds
                             };
                             addAntiForgeryToken(idListData);

                             $.ajax({
                                cache: false,
                                type: "POST",
                                url: "@(Url.Action("getInStockProductListByIds", "InStockPendingShipments"))",
                                data: idListData,
                                 success: function (result) {
                                    if (result.Data != null || result.Data != '') {
                                          $('#selected-po-list').html('');
                                            $('#selected-po-list').delegate('li');
                                         $('#selected-po-list').append('<li class="list-header"><table><tr>' +
                                                    '<td style="width: 10%;font-weight: 600;"> SKU </td>' +
                                                    '<td tyle="font-weight: 600;">ProductNane</td>' +
                                                    '<td style="font-weight: 600;width: 20%;font-weight:600;text-align: right;position: relative;">Quantity</td>' +
                                                    '</tr></table ></li> ');
                                            for (var i = 0; i < result.Data.length; i++) {
                                                console.log('electedPOs', result.Data[i].SKU);
                                                $('#selected-po-list').append('<li><table><tr>' +
                                                    '<td style="width: 10%;"> <a target="_blank"  href="/admin/Product/Edit/' + result.Data[i].ProductId  + '">' + result.Data[i].SKU  + '</a></td>' +
                                                    '<td>' + result.Data[i].ProductNane + '</td>' +
                                                    '<td style="width: 20%;font-weight:600;text-align: right;position: relative;"> <div class="product-count">' + result.Data[i].Quantity + '</div></td>' +
                                                    '</tr></table ></li> ');
                                            }
                                    }
                                },
                                error: function (xhr, ajaxOptions, thrownError) {
                                    alert('Failed to find dispatch information.');
                                    return null;
                                }
                            });
                        }

                    </script>
                    <style>
                        .selected-po-list {
                            list-style: none;
                            padding-left: 0;
                            margin-top: 30px;
                            max-height: 280px;
                            overflow-y: auto;
                        }

                            .selected-po-list li {
                                height: 50px;
                                padding: 10px;
                                margin-bottom: 5px;
                                border: 1px solid #00c0ef47;
                            }

                                .selected-po-list li table {
                                    width: 100%;
                                }


                        .product-count {
                            position: absolute;
                            color: white;
                            height: 25px;
                            top: 0;
                            right: 10px;
                            text-align: center;
                            padding: 2px 0 0 0;
                            width: 25px;
                            border-radius: 50px;
                            background-color: #3c8dbc;
                        }

                        .list-header {
                            background-color: #7cc3ff30 !important;
                            height: 25px !important;
                            padding-top: 0 !important;
                            padding-bottom: 0 !important;
                        }
                    </style>
                </div>
            </form>
        </div>
    </div>
</div>

This is my action and it's working fine it returns string message

public virtual IActionResult SendInStockRequestEmail(string SelectedPOIds, string Message, string Subject)
{
    var inStockIds = new List<int>(Array.ConvertAll(SelectedPOIds.Split(','), Convert.ToInt32));
    string message = _inStockPendingShipmentService.SendInStockShipmentRequestEmail(inStockIds,  Message,  Subject);
    return Json(new DataSourceResult { Data = message });
}

Upvotes: 1

Views: 148

Answers (1)

Nan Yu
Nan Yu

Reputation: 27528

The default type of <button> is submit which submits the form data to the server . You can use input button instead :

<input type="button" class="btn btn-primary" id="send-email" value="Send Email" />

Upvotes: 1

Related Questions