Ajax.ActionLink and jquery execution in PartialView after Ajax request - ajax

I load some PartialView in page as response to Ajax form post. This partial contains two Ajax.ActionLink by self. After response load ActionLinks doesn't work properly - it send request to server but doesn't updates UpdateTarget with returned content.
Seems like jquery-ui provided widgets (like draggable) can't bind to elements in way like this (code placed in partial view):
$(function(){ $('#target').draggable();});
I would appreciate for any solutions.
PS> ActionLinks starts work after target id correction, but jquery ui steel don't work

seems #target is not avilable when your code is binding the handler..
try using live(), or delegate(), or .on()

Solved by add named function in PartialView and call it in OnSuccess for Ajax.BeginForm. As I discover document.ready fires for ajax-loaded content before page is really updated.

Related

Reload javascript after thymeleaf fragment render

I have javascript files defined in the <head> of both my layout decorator template and my individual pages which are decorated. When I update a thymeleaf fragment in one of my pages the javascript defined in the head of the parent page no longer works. Is there a standard way to 'refresh' these js files?
Thanks.
Additional clarification :
I have a form submitted by an ajax call which updates a table in the page. I have a Jquery onClick function targeting a button in the updated table. The javascript doesn't seem able to bind to the returned elements in the updated part of the page. I select by element class and can see that the selection works prior to the partial fragment render.
For me it is unclear what you mean by
javascript defined in the head of the parent page no longer works.
The page is created on the server. Normally it contains urls of the javascript files
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
In this case 'refreshing' the javascript files can happen only in the client.
Check the html of the page in the client.
Are the tags as expected ?
Are there tags for all expected javascript files ?
With the browser tools (for example Google Chrom developer tools ) check that all script files are actually loaded.
If this doesnt help, it could be that the order of the script tags has changed between the first and second load. This could cause a different behaviour of the javascript executed in the browser.
EDIT :
With the initial load you bind javascript callbacks to dom elements.
You do this directly or through Jquery or other libraries.
When a new dom element is loaded, it has no callbacks bound to it, even if it has the same id as a replaced dom element.
So after the load you have to bind your callbacks again.
If you bound them 'by hand', just bind it again.
If you are using a JQuery plugin, that made the bindings, look into the code or documentation, many of them have a function for that or you can call initialization again.
Once you added new content to the DOM you need to bind again the new content.
Let's say I have a button with some class, the event in binded to the class:
<button class="someclass">Button 1</button>
<script>
var something = function() {
// do something
};
$(".someclass").on("click", something);
</script>
If I add more buttons from the same class to the DOM, they will have not have the click event binded. So once you load the new content via ajax, also remove all binding and add again (you need to remove or you will have buttons with 2 events).
$(".someclass").off("click");
$(".someclass").on("click" , something);

How to get the raw markup from a jquery mobile pageload request?

How can you get the raw HTML markup from an AJAX request that loads a page in jquery mobile?
My page has a menu outside of the page container element (data-role="page") and I need to update it on each page load but jquery-mobile only gives me the page markup from the request not the entire document.
I've even tried using the global ajaxSuccess callback for jquery; apparently jquery-mobile feels the need to filter this to just the page element also.
Can't you just assign an id to the menu page and access it directly?
$('#myMenu').html(newContent);
Found the http request object in the pageload event.
$(document).bind("pageload", function (e, data) {
console.log(data.xhr.responseText);
});

Wiring up Ajax.BeginForm that didn't exist during doc.ready?

I have a MVC page that loads a Partial via a Ajax.ActionLink, which works, and then the loaded Partial contains a form that has Ajax.BeginForm. This form is not getting wired up to unobtrusive ajax, and instead is performing a page refresh(I verified this in the Network log of the browser that shows the initiator when I click submit is the browser instead of jquery).
What I believe is the issue is that since the form didn't exist when the page is loaded(but later is added via the Ajax.ActionLink), then unobtrusive ajax didn't see the data-ajax attributes on the newly added form and wire up the necessary events. I'm assuming that only happens at document.ready, and the ajax form didn't exist then.
Is there something I can do to say "hey Unobstrusive Ajax, please look at my page again now that I have some new elements that are marked with data-ajax and wire them up"?
Thanks.
Looking at the unobtrusive ajax source, it has this:
$("form[data-ajax=true]").live("submit", function (evt) {
var clickInfo = $(this).data(data_click) || [];
evt.preventDefault();
...
The form tag generated looks like this:
<form action="/Path/Create" class="form-horizontal" data-ajax="true" data-ajax-method="post" data-ajax-mode="replace" data-ajax-update="#ParentContainer" id="PathForm" method="post" novalidate="novalidate">
As far as I can tell the selector on the .live event should be picking up on the new form when it's loaded onto the page. The form is inside a bootstrap modal however, so I don't know if that would be preventing the event from bubbling up somehow.
I can even run this in Chrome console:
$("form[data-ajax=true]").live("submit", function (evt) {
var clickInfo = $(this).data(data_click) || [];
evt.preventDefault(); });
And it returns the form element successfully, but when I click submit it still does a full page refresh. I would expect it to at least do nothign since I wired it up to preventDefault.
To answer my own question regarding unobtrusive ajax and dynamically loaded content, it should work fine out of the box. The way it wires up to events with .live(deprecated, still works currently) should detect forms that are loaded dynamically onto the page. So apparently it doesn't suffer the same problem that unobtrusive validation does.
Our problem was unrelated to that. We were using bootstrap modal which spawned a modal div from inside a form. Since the modal then loaded another page containing a form, we realized we had a form within a form (even though it didn't really look that way since the other form was in a modal).
To solve this we moved the declaration of the modal div in the first form outside of the form. We could still have a link that referenced the modal to show it, but not the modal's inner form wouldn't be nested in the first form.
I believe the reason this caused both the .live and .on methods to not catch the event was because they depend on the event to bubble up to the document, and it bubbled up only as far as the outer form which was not an ajax form, thus did not match the selector.
Another solution would have been to write .on more like this so that the event would be caught when it bubbled up to the container of the inner form, instead of scoping it to the document where the event would reach the outer form first.
$('#innerModalId').on("submit", "form[data-ajax=true]", function (evt) {
evt.preventDefault();
...
return false
});
However since this was part of a library, that's not an ideal solution as I would have needed to repeat their code. We didn't get as far as updating unobtrusive ajax:
http://nuget.org/packages/jQuery.Ajax.Unobtrusive
But I think we would have still had the problem since even with .on it still didn't work due to our page structure problem.

Manually bind JQuery validation after Ajax request

I'm requesting an ASP.net MVC view into a live box and the view contains form fields that have been marked up with attributes to be used by JQuery's unobtrusive validators plug-in.
The client script is not however working and my theory is that its because the validation framework is only being triggered on page load which has long since passed by the time the MVC view has been loaded into the live box.
Thus how can I let the validation framework know that it has new form fields to fix up?
Cheers, Ian.
var $form = $("form");
$form.unbind();
$form.data("validator", null);
$.validator.unobtrusive.parse(document);
// Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);
You may take a look at the following blog post. And here's another one.
Another option, rather trick, which worked for me. Just add following line in the beginning of the partial view which is being returned by ajax call
this.ViewContext.FormContext = new FormContext();
Reference
For some reason I had to combine bjan and dfortun's answers...
So I put this in my view:
#{
this.ViewContext.FormContext = new FormContext();
}
And this execute this after the ajax call finishes:
var form = $("#EnrollmentForm");
form.unbind();
form.data("validator", null);
$.validator.unobtrusive.parse(document);
form.validate(form.data("unobtrusiveValidation").options);
I had a similar issue. I had a form that was using Ajax requests to re-display a part of the form with different form fields. I used unobtrusive validation by manually doing it on the client side using the
#Html.TextBoxFor
for my text boxes. For some reason the validation works when attempting to submit with invalid fields (i.e., the text boxes get outlined in red and the appropriate error messages display with the content I put in the
data_val_required
attribute, for example.
However, after I click a button that makes an Ajax request to modify the form with different fields and then submit again, only the red outline on the invalid fields display, but no error messages are rendered.
bjan's trick worked for me, but I still can't see what was causing the issue. All the HTML necessary to carry out the client-side validation was there I just can't figure out why the error message attribute values wouldn't display.
All I can think of is that the jQuery validation code doesn't make a second attempt to check the form fields after a submit was made.

JQuery - Ajax return HTML wont allow further Jquery functions?

Kinda New to Jquery and hit an issue regarding returned HTML. I am using the .load() function to load HTML returned from a jsp file - its all working grand except the returned HTML doesnt seem to allow further Jquery functions to be called on it.
i have a click and toggle combination running for "#showgame" - this id is in the returned HTML but clicking on it does nothing when it should. Do i have to update anything to tell jquery that this id now exists on the page after load() call?
Regards,
Cormac
You need to use the live() function to bind the click event.
$("#myelement").live("click", function() { });
Live binds the event to current and future elements that match the selector.
Read more at http://api.jquery.com/live .

Resources