Reputation: 475
i have the following script in my ASP.NET MVC Project :
$(function () {
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-otf-target"));
var $newHtml = $(data);
$target.replaceWith($newHtml);
});
return false;
};
$("form[data-otf-ajax='true']").submit(ajaxFormSubmit);
});
why this fonction executes just once ? this function is for updating a list of objects , here is the form on the razor view :
<form method="get" action="@Url.Action("Index")" data-otf-ajax ="true"
data-otf-target="#RestaurantList">
<input type="search" name="searchTerm" />
<input type="submit" value="Search By Name" />
</form>
<div id="RestaurantList">
@Html.Partial("_Restaurants")
</div>
Upvotes: 2
Views: 133
Reputation: 4020
Your function is not executed only once. The problem is that when your handler is executed the first time, you are replacing the element whose id is RestaurantList
with the HTML code returned by the ajax call.
So, the next time it is executed, this line
var $target = $($form.attr("data-otf-target"));
won't have the expected behaviour (because there is no element with the id RestaurantList
in your document anymore.
Try updating the content of your RestaurantList
element with the .html() method instead of replaceWith() :
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-otf-target"));
var $newHtml = $(data);
$target.html($newHtml);
});
That way, your element still has the same id. And the next execution of your handler should work fine.
Upvotes: 1