javascript - How to refresh page after all ajax calls finish? - Stack Overflow

Here is my jquery function below. I need to refresh the page so I can display the additional columns af

Here is my jquery function below. I need to refresh the page so I can display the additional columns after they have checked which columns to display. Currently with the code (location.reload()) it refreshes before the ajax calls can finish. I tried .promise after the checkbox loop but it only allows me to submit 1 checkbox.

Jquery

$('.delete-numbers').click(function () {
        $('.number-chkbox').each(function () {   
            if (this.checked) {
                $(this).attr('checked', true);
                alert($(this).val() + " " + this.checked + "I GOT INNNN ADDDDD");
                $.ajax({
                    url: '/PhoneBook/AddNumber',
                    data: {
                        Number: $(this).val(),
                        Name: name,
                        PhoneId: PhoneId
                    },
                    type: "POST",
                    dataType: "html",
                    cache: false
                });
            } else {
                $(this).removeAttr('checked');
                alert($(this).val() + " " + this.checked + "I GOT INNNN REMOVE");
                $.ajax({
                    url: '/PhoneBook/AddNumber',
                    data: {
                        Number: $(this).val(),
                        Name: name,
                        PhoneId: PhoneId
                    },
                    type: "POST",
                    dataType: "html",
                    cache: false
                });
            }
        })
        location.reload();
    });

Html

<div class="modal-body form-group">
                @foreach (var item in Model.PhoneBook.OrderBy(a => a.Number))
                {
                    if (Model.AvailableNumbers.Any())
                    {
                        if (Model.AvailableNumbers.Where(a => a.Number== item.Number).Count() != 0)
                        {
                            <input class="number-chkbox number" type="checkbox" checked="checked" name="@item.Number_Description" value="@item.Number">
                        }
                        else
                        {
                            <input class="number-chkbox number" type="checkbox" name="@item.Number_Description" value="@item.Number">
                        }
                        <label class="non-bold">@String.Format(" {0} - {1}", @item.Number, @item.Number_Description)</label>
                        <br />
                    }
                    else
                    {
                        <input class="number-chkbox number" type="checkbox" name="@item.Number_Description" value="@item.Number">
                        <label class="non-bold">@String.Format(" {0} - {1}", @item.Number, @item.Number_Description)</label>
                        <br />
                    }
                }
            </div>
<div class="modal-footer">
                    <button type="submit" class="btn btn-danger delete-numbers" data-dismiss="modal">Yes</button>
                    <button type="button" class="btn btn-default cancel-number">No</button>
                </div>

Here is my jquery function below. I need to refresh the page so I can display the additional columns after they have checked which columns to display. Currently with the code (location.reload()) it refreshes before the ajax calls can finish. I tried .promise after the checkbox loop but it only allows me to submit 1 checkbox.

Jquery

$('.delete-numbers').click(function () {
        $('.number-chkbox').each(function () {   
            if (this.checked) {
                $(this).attr('checked', true);
                alert($(this).val() + " " + this.checked + "I GOT INNNN ADDDDD");
                $.ajax({
                    url: '/PhoneBook/AddNumber',
                    data: {
                        Number: $(this).val(),
                        Name: name,
                        PhoneId: PhoneId
                    },
                    type: "POST",
                    dataType: "html",
                    cache: false
                });
            } else {
                $(this).removeAttr('checked');
                alert($(this).val() + " " + this.checked + "I GOT INNNN REMOVE");
                $.ajax({
                    url: '/PhoneBook/AddNumber',
                    data: {
                        Number: $(this).val(),
                        Name: name,
                        PhoneId: PhoneId
                    },
                    type: "POST",
                    dataType: "html",
                    cache: false
                });
            }
        })
        location.reload();
    });

Html

<div class="modal-body form-group">
                @foreach (var item in Model.PhoneBook.OrderBy(a => a.Number))
                {
                    if (Model.AvailableNumbers.Any())
                    {
                        if (Model.AvailableNumbers.Where(a => a.Number== item.Number).Count() != 0)
                        {
                            <input class="number-chkbox number" type="checkbox" checked="checked" name="@item.Number_Description" value="@item.Number">
                        }
                        else
                        {
                            <input class="number-chkbox number" type="checkbox" name="@item.Number_Description" value="@item.Number">
                        }
                        <label class="non-bold">@String.Format(" {0} - {1}", @item.Number, @item.Number_Description)</label>
                        <br />
                    }
                    else
                    {
                        <input class="number-chkbox number" type="checkbox" name="@item.Number_Description" value="@item.Number">
                        <label class="non-bold">@String.Format(" {0} - {1}", @item.Number, @item.Number_Description)</label>
                        <br />
                    }
                }
            </div>
<div class="modal-footer">
                    <button type="submit" class="btn btn-danger delete-numbers" data-dismiss="modal">Yes</button>
                    <button type="button" class="btn btn-default cancel-number">No</button>
                </div>
Share Improve this question asked Jul 14, 2016 at 0:47 cxwilsoncxwilson 1071 gold badge5 silver badges15 bronze badges 1
  • I add a solution please take a look on it – Teocci Commented May 31, 2017 at 5:10
Add a ment  | 

4 Answers 4

Reset to default 3
$.ajax({
  ...,
  ...,
  success: function() {location.reload();}
})

JQuery AJAX

I think you should relocate your location.reload() call when an ajaxComplete event occurs.

The easiest way is adding done or success methods into your code. These methods will help you to manage the callbacks when a ajax event occurs.

Using done:

$.ajax({
  url: '/PhoneBook/AddNumber',
  data:
  ...,
  ...,
}).done(function( data ) {
     location.reload();
  });

Also, you can add success:

$.ajax({
  url: '/PhoneBook/AddNumber',
  data: {
  ...,
  ...,
  success: function(data, status, xhr) {
    location.reload();
  }
})

Finally, a more plicated way will be using ajaxComplete events, this is useful Whenever you want to verify if an Ajax request is pleted. Therefore, any and all handlers that have been registered with the .ajaxComplete() method are executed at this time.

To observe this method in action, set up a basic Ajax load request:

<div class="delete-numbers">Yes</div>
<div class="result"></div>
<div class="log"></div>

Attach the event handler to the document:

$( document ).ajaxComplete(function() {
  $( ".log" ).text( "Triggered ajaxComplete handler." );
});

Now, make an Ajax request using any jQuery method:

$( ".delete-numbers" ).click(function() {
  $( ".result" ).load( "ajax/test.html" );
});

When the user clicks the element with class delete-numbers and the Ajax request pletes, the log message is displayed.

All ajaxComplete handlers are invoked, regardless of what Ajax request was pleted. If you must differentiate between the requests, use the parameters passed to the handler. Each time an ajaxComplete handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request. For example, you can restrict the callback to only handling events dealing with a particular URL:

$( document ).ajaxComplete(function( event, xhr, settings ) {
  if ( settings.url === "ajax/test.html" ) {
    $( ".log" ).text( "Triggered ajaxComplete handler. The result is " +
      xhr.responseText );
  }
});

Note: You can get the returned Ajax contents just by looking at xhr.responseText.

Now you can show a message when an Ajax request pletes.

$( document ).ajaxComplete(function( event,request, settings ) {
  $( "#msg" ).append( "<li>Request Complete.</li>" );
});

If you don't have anything else to do but reload onSuccess, you can put location.reload() under success, else you can put it under the plete function.

$.ajax({
    url: '/PhoneBook/AddNumber',
    data: {
        Number: $(this).val(),
        Name: name,
        PhoneId: PhoneId
    },
    type: "POST",
    dataType: "html",
    cache: false,
    success: function(response){
       ... do what you need here
    },
    plete: function() {
        location.reload();
    }
});

Try something like this:

$('.delete-numbers').click(function () {
    var total = $('.number-chkbox').length; // what to wait for
    var cnt = 0; //Nothing done yet
    $('.number-chkbox').each(function () {   
        if (this.checked) {
            $(this).attr('checked', true);
            alert($(this).val() + " " + this.checked + "I GOT INNNN ADDDDD");
            $.ajax({
                url: '/PhoneBook/AddNumber',
                data: {
                    Number: $(this).val(),
                    Name: name,
                    PhoneId: PhoneId
                },
                type: "POST",
                dataType: "html",
                //cache: false //no need POST is never cached
                success: function(data, status, xhr){
                   //all you need to do
                   cnt++; 
                   // It is safe. Javascript is single-thread so no concurrency issue may be expected
                   if(cnt == total)location.reload();
                }//success
                error: function(xhr){
                   cnt++;
                   if(cnt == total)location.reload();
                }//error
            });
        } else {
            $(this).removeAttr('checked');
            alert($(this).val() + " " + this.checked + "I GOT INNNN REMOVE");
            $.ajax({
                url: '/PhoneBook/AddNumber',
                data: {
                    Number: $(this).val(),
                    Name: name,
                    PhoneId: PhoneId
                },
                type: "POST",
                dataType: "html",
                //cache: false //see above
                success: function(data, status, xhr){
                   //all you need to do
                   cnt++;
                   if(cnt == total)location.reload();
                }//success
                error: function(xhr){
                   cnt++;
                   if(cnt == total)location.reload();
                }//error
            });
        }
    })
    //location.reload(); //never mix synch and asynch
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744405438a4572606.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信