0

I'm not sure how to refresh data after I use AJAX. Here's what I already have:

Frontend:

@model TFU.Model.DB_USER

    <div id="listTelNumbers">
        @foreach (var item in Model.DB_USER_PHONES)
        {
            <dl class="dl-horizontal">
                <dt>
                    @item.PHONE
                </dt>
                <dd>
                    <button id="removeButton" class="btn btn-default" onclick="sendRequestToRemove('@item.USER_ID', '@item.PHONE')">Usuń</button>
                </dd>
            </dl>
        }
    </div>

Script - fadeOut works fine but I don't know what should I fadeIn. So I guess is missing a small part of code there. Also how can I fadeOut only the record which I currently removing instead all list.

 <script>
        function sendRequestToRemove(id, phone) {
            var data = {
                "USER_ID": id,
                "PHONE": phone
            }


            $.ajax({
                url: '/User/RemoveTelNumber',
                data: JSON.stringify(data),
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                error: function (err) {
                    alert('Error: ' + err.statusText);
                },
                success: function (result) {
                    $('#listTelNumbers').fadeOut(800, function () {
                        form.html('#listTelNumbers').fadeIn().delay(2000);
                    });
                },
                async: true,
                processData: false
            });
        }      
    </script>

Backend:

public bool RemoveTelNumber(DB_USER_PHONES model)
{
    var user = db.DB_USER_PHONES.First(x => x.USER_ID == model.USER_ID && x.PHONE == model.PHONE);
    db.DB_USER_PHONES.Remove(user);
    db.SaveChanges();
    return true;
}
4
  • Are you wanting to remove <dl> element containing the button you clicked from the <div id="listTelNumbers"> element after the ajax call? Commented Jun 11, 2016 at 11:38
  • @StephenMuecke, exactly. Button and Phone number from <dt>. In this example (prntscr.com/bf25u1) after i'll click Remove then in div listTelNumbers will left 3 elements. Commented Jun 11, 2016 at 12:25
  • OK, Will add answer shortly - there are a few changes you need to make. Commented Jun 11, 2016 at 12:26
  • Ok, thank you. I will wait. Commented Jun 11, 2016 at 12:26

3 Answers 3

1

Firstly, your loop is generating duplicating invalid html because of the duplicate id attributes. And you should not be polluting your markup with behavior - use Unobtrusive JavaScript. Change the html to remove the id attribute, add a class name for selection and add data-* attributes for the values to be posted

@foreach (var item in Model.DB_USER_PHONES)
{
    <dl class="dl-horizontal">
        <dt>@item.PHONE</dt>
        <dd><button class="btn btn-default delete" data-id="@item.USER_ID" data-phone="@item.PHONE">Usuń</button></dd>
    </dl>
}

Then change the script to

var url = '@Url.Action("RemoveTelNumber", "User")'; // always use Url.Action()
$('.delete').click(function() {
    var container = $(this).closest('dl');
    var data = { user_Id: $(this).data('id'), phone: $(this).data('phone') };
    $.post(url, data, function(response) {
        if (response) {
            // fadeout, then remove
            container.fadeOut(800, function() { $(this).remove(); })
        } else {
            // Oops - display an error message?
        }
    }).fail(function() {
        // Oops
    });
});

And finally, change the action method to return a JsonResult indicating success or otherwise

[HttpPost]
public JsonResult RemoveTelNumber(DB_USER_PHONES model)
{
    var user = db.DB_USER_PHONES.First(x => x.USER_ID == model.USER_ID && x.PHONE == model.PHONE);
    db.DB_USER_PHONES.Remove(user);
    db.SaveChanges();
    return Json(true);
    // or if something went wrong, return Json(null);
}

I also recommend you rename you classes and properties to follow conventional naming practices - UserPhone, not DB_USER_PHONES, UserId, not USER_ID etc.

Sign up to request clarification or add additional context in comments.

1 Comment

If you have time, again I have similary problem here. stackoverflow.com/questions/37854410/…
1

Partially reload that div

$("#listTelNumbers").load(location.href + " #dl-horizontal");

Or reload the entire page w/o refreshing it

$(document.body).load(location.href);

For a complete reference I found a demo here Partially load a div without refreshing page in javascript and php.

2 Comments

First example doesn't work, second example refresh entire page, but i'd like to refresh only div="listTelNumbers"
If there is any parent element above #listTelNumbers then try this $("#parentelement").load(location.href + "#listTelNumbers");
0

You can use jQuery to find the <dt> element which was marked for deletion and fade it out(or remove it completely from the DOM):

  $.ajax({
    url: '/User/RemoveTelNumber',
    data: JSON.stringify(data),
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    error: function (err) {
        alert('Error: ' + err.statusText);
    },
    success: function (result) {
        var dtCollection = $("dt");

        for (var i = 0; i < dtCollection.length; i++) {
            var text = $(dtCollection[i]).text();
            text = text.trim();

            if (text == phone) {
                $(dtCollection[i]).parent().fadeOut('slow');
                //$(dtCollection[i]).parent().remove();
            }
        }
    },
    async: true,
    processData: false
});

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.