2

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> 
4
  • Put the javascript code outside of the RestaurantList div....maybe it gots overwritten by the ajax call. Commented Dec 27, 2017 at 15:13
  • try using input type button and execute the above function using Jquery's click(function) and do let me know.. Commented Dec 27, 2017 at 15:18
  • The javascript code is in seperate file , i bundled it with the jquery scripts ( @Scripts.Render .. ) Commented Dec 27, 2017 at 15:19
  • when i put alert in the function , it shows the result evey time i submit , but the update in the view will be done just the first time Commented Dec 27, 2017 at 15:29

1 Answer 1

1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.