H. Pauwelyn
H. Pauwelyn

Reputation: 14300

get the html code of a div from a variable

After when a radiobutton is checked, I do an ajax request to the server. when it returns, I have the full html page with the new data. I need only a part of the code. How can I replace the old data (form before the ajax request) with the new data after the request? Here is my code:

$(".do-ajax").change(function () {
    $.ajax({
        url: "",
        data: { id: this.id },
        type: "POST",
        success: function (data) { //data contains the full new html page.
            console.log($(data)($(".ajax-form").html())); // wrong code and only needed to
                                                          // see what I get
            $(".ajax-form").replaceWith($(data).get(".ajax-form").html()); 
                                                          // $(".ajax-form") must be 
                                                          // replaced
        },
        error: function (data) {
            console.log("probleempje oplossen...");
            console.log(data);
        }
    });
});

The thing I will renew is the .ajax-form class which is a form-attribute.

Here is also my server code (language behind C#):

@using (Html.BeginForm("Nieuw", "Topic", FormMethod.Post, new { @class = "form-horizontal ajax-form", role = "form" }))
{
    @Html.AntiForgeryToken()

    <div class="col-md-4 hfdstk">
        @foreach (var item in Model.Hoofdstukken)
        {
            string jsonid = JsonConvert.SerializeObject(new TopicIdOrde(item.ID, 'h'));
            @Html.RadioButtonFor(m => m.DeHoofdstuk, item.Naam, new { @class = "do-ajax", id = jsonid });
            <label for="@jsonid">@item.Naam</label><br />
        }
    </div>

    <div class="col-md-4 cat">
        @if (Model.Categorien.Count != 0)
        {
            foreach (var item in Model.Categorien)
            {
                @Html.RadioButtonFor(m => m.DeCategorie, item.Naam, new { @class = "do-ajax", id = "c_" + item.ID, value = item.ID.ToString() });
                <label for="[email protected]">@item.Naam</label><br />
            }
        }
    </div>
    <div class="col-md-4 items"><!--not implemented--></div>
}

Or (I don't know) is it better to send only the things I need after the ajax request and not the full html page?

Upvotes: 0

Views: 72

Answers (2)

ahPo
ahPo

Reputation: 384

Try this in your ajax success call back function: $('.ajax-form').html($(data).find('.ajax-form').html())

Upvotes: 1

Guffa
Guffa

Reputation: 700362

Use the find method to find elements within the jQuery object:

$(".do-ajax").change(function () {
  $.ajax({
    url: "",
    data: { id: this.id },
    type: "POST",
    success: function (data) {
      $(".ajax-form").replaceWith($(data).find(".ajax-form"));
    },
    error: function (data) {
      console.log("probleempje oplossen...");
      console.log(data);
    }
  });
});

Upvotes: 3

Related Questions