Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

Response from AJAX request is only displayed once

I've got some code that sends an ajax request when a form is being submitted. This works the first time the form is submitted (it's a search module), but only once. I've added an effect to highlight the table when data is returned, and you can only see it once (the data changes only once as well).

When I look at the response in the chrome dev tools, I can see it contains the data of the new search query but this isn't shown. Why can I only display results once?

JS:

$(function () {
// Creates an ajax request upon search form submit
 var ajaxFormSubmit = function () {
    var $form = $(this);

    var options = {
        url: $form.attr("action"),
        type: $form.attr("method"),
        data: $form.serialize()
    };

    $.ajax(options).done(function (data) {
        var $target = $($form.attr("data-nn-target"));
        var $newHtml = $(data);
        $target.replaceWith($newHtml);
        $newHtml.effect("highlight");
    });

    // Prevent default action
    return false;
 };

 $("form[data-nn-ajax='true']").submit(ajaxFormSubmit);
});

HTML:

<form method="GET" action="@Url.Action("Index", "Show")" data-nn-ajax="true" data-nn-target="#contentlist" class="form-search">
    <div class="input-append mysearch">
        <input type="search" class="span5 search-query" name="query" data-nn-autocomplete="@Url.Action("AutoComplete")" />
        <input type="submit" class="btn" value="Search" />
    </div>
</form>

<div id="contentlist">
    @Html.Partial("_Shows", Model)
</div>

Upvotes: 2

Views: 224

Answers (2)

Dennis
Dennis

Reputation: 14455

just an idea... try

$target.html(data);

instead of

$target.replaceWith($newHtml);

By replaceWith, you might actually remove the div that you want to fill your content in. Then, the second time, it doesnt find the div to insert the content into.

Upvotes: 2

A. Wolff
A. Wolff

Reputation: 74420

I think you should use html() instead of replaceWith() method:

$target.html($newHtml);

Upvotes: 4

Related Questions