jQuery UI Dialog Validation - asp.net-mvc-3

I know this is a common problem. I've been looking at the various solutions proposed on this site and elsewhere but cannot hit upon something that works in my situation.
Here is my script:
$(function () {
$('a.editPersonLink').live("click", function (event) {
loadDialog(this, event, '#personList');
$.validator.unobtrusive.parse('#editPersonContainer');
});
$(".deleteButton").live("click", function(e) {
e.preventDefault();
var $btn = $(this);
var $msg = $(this).attr("title");
confirmDelete($msg,
function() {
deleteRow($btn, $target);
});
});
});
function loadDialog(tag, event, target) {
event.preventDefault();
var $loading = $('<img src="../../Content/images/ajaxLoading.gif" alt="loading" class="ui-loading-icon">');
var $url = $(tag).attr('href');
var $title = $(tag).attr('title');
var $dialog = $('<div></div>');
$dialog.empty();
$dialog
.append($loading)
.load($url)
.dialog({
autoOpen: false
,title: $title
,width: 800
,modal: true
,minHeight: 200
,show: 'slide'
,hide: 'clip'
});
$dialog.dialog( "option", "buttons", {
"Save": function () {
var dlg = $(this);
$.ajax({
url: $url,
type: 'POST',
data: $("#formData").serialize(),
success: function (response) {
$(target).html(response);
dlg.dialog('close');
dlg.empty();
$("#ajaxResult").hide().html('Record saved').fadeIn(300, function () {
var e = this;
setTimeout(function () { $(e).fadeOut(400); }, 2500);
});
},
error: function (xhr) {
if (xhr.status == 400)
dlg.html(xhr.responseText, xhr.status); /* display validation errors in edit dialog */
else
displayError(xhr.responseText, xhr.status); /* display other errors in separate dialog */
}
});
},
"Cancel": function() {
$(this).dialog("close");
$(this).empty();
}
});
$dialog.dialog('open');
};
Right up near the top I am trying to cause the form to recognise the validation from the partial view on the dialog via the statement:
$.validator.unobtrusive.parse('#editPersonContainer');
editPersonContainer is the name of the div containing the data in the partial view loaded into the dialog.
The bottom line is that the validation is not recognised. Am I making the call to validator.unobtrusive.parse in the wrong place, or am I missing something else here?

I ended up changing my script to use the techniques described here
Validation now works on my jQuery UI dialogs.

Hi I came up to your question as I was looking for the same.
I include this before the ajax call to validate on client side:
if (ModelState.IsValid) {}
I make an article with the full project on
Validation client/Server JqueryUI Dialog

Related

Borwser's back button state update after ajax call

I am trying to sort out back and forward browser buttons in my ajax page load setup.
This is my ajax code that calls page content:
jQuery(document).ready(function () {
$ = jQuery;
$("body").on("click", ".menuAjax a", function (e) {
//On click on body for ajax calls
e.preventDefault();
var pageID = $(this).data("id");
var catType = $(this).data("type");
var pageTitle = $(this).data("title");
var footerAdSwitch = $("#overFooter").data("footeradswitch");
var homePageSet = parseInt($("#homePageSet").val());
var $this = $(this);
//console.log($this);
var res;
var payload = JSON.stringify({
action: "router_loader",
pageid: pageID,
footeradswitch: footerAdSwitch,
homepage: homePageSet,
cattype: catType,
pagetitle: pageTitle,
});
XHR = $.ajax({
type: "get",
url: my_ajax_object.ajax_url + '/' + payload + '/view_' + (pageID || catType),
beforeSend: function () {
$("#ajaxPageLoader").show();
},
complete: function () {
$("#ajaxPageLoader").hide();
},
success: function (res) {
if (res != "") {
$("#ajaxpageLoad").html(res);
setTimeout(function () {
$("#ajaxPageLoader").hide();
}, 600);
$(".nav li.menu-item").removeClass(
"current-menu-item current_page_item"
);
$($this).parent().addClass("current-menu-item current_page_item");
const nextURL = $this[0].href;
history.pushState(res, pageTitle, nextURL);
document.title = pageTitle + " - company name";
$.getScript("/wp-content/themes/customTpl/js/functions.js");
var lazyLoadInstance = new LazyLoad({
threshold: 200,
});
$("html, body").animate({ scrollTop: 0 }, 0);
} else {
$("#ajaxPageLoader").hide();
}
},
error: function (req, status, error) {},
});
});
//Exclude expander btn from ajax call
$("body").on("click", ".btnNoBorder, .mobileMenueBtn, .closeBtn", function (e) {
e.stopPropagation();
});
window.addEventListener('popstate', function(e) {
$("#ajaxpageLoad").html(res);
updateContent(e.state);
});
});
Right now I ma stuck with popstate function, which I would like to pass urls of current position, so they are remembered once a users presses back button.
Can someone suggest me direction as to how to update history navigation with the browser buttons ?

Not able to submit a form via Ajax

EDIT
the code below seems to works as long as the form is valid.
but when it is not the case (clean method in django form) h1 text of form is removed (????) and the error messages are not displayed...
I guess that an empty popup.html is return via ajax and as there is no button to interact with nothing happen but why h1 text is removed...???
var prevent_edit = false;
var prevent = false;
// popup d'informations indiquant que la levée d'insue a déjà été faite
// pour ce patient
$("#form_unblind_edit").submit(function (event) {
console.log('form_unblind_edit click - first')
console.log('prevent_edit - first', prevent_edit)
if (!prevent_edit) {
event.preventDefault();
}
});
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
// affichage des informations sur le patient sélectionné pour la ré-allocation
$("#unblind_edit").on("click", function (event) {
console.log('click unblind edit');
var csrftoken = getCookie('csrftoken');
var patient = $("#id_pat").val();
$.ajax({
type: "POST",
url: '/unblind/already_unblind/',
data: {
csrfmiddlewaretoken: csrftoken,
'patient': patient,
},
dataType: 'html',
success: function (data) {
console.log('success');
// var prevent_edit = false;
$("#can_unblind").html(data);
$('#unblindconfirm').modal('show');
$('body').on('click', '#edit_button_OK', function (event) {
console.log('edit_button_OK')
$('#edit_button_OK').attr("disabled", "disabled");
prevent_edit = true;
console.log('prevent_edit', prevent_edit);
$("#form_unblind_edit").submit();
})
},
error: function (resultat, statut, erreur) {
console.log('error');
}
});
});
i need some help for popup with ajax
User complete the form and submit the form by clicking a button
I prevent submit with event.preventDefault(); to display a popup.
But I need to ask database for informations to display on popup, so I use an ajax query
when ajax success, popup is displayed with informations from database and I want the form t be submited by clicking on "OK" button of the popup
but it failed, I think, because event (submit) is attached to a button that is not present in DOM when page load...
JS
$(document).ready(function () {
var prevent_edit = false;
// prevent submission
$("#form_unblind_edit").submit(function (event) {
if (!prevent_edit) {
event.preventDefault();
}
});
// ajax query that display popup
$("#unblind_edit").on("click", function (event) {
var csrftoken = getCookie('csrftoken');
var patient = $("#id_pat").val();
$.ajax({
type: "POST",
url: '/unblind/already_unblind/',
data: {
csrfmiddlewaretoken: csrftoken,
'patient': patient,
},
dataType: 'html',
success: function (data) {
$("#can_unblind").html(data); //popup html attach to DOM
$('#unblindconfirm').modal('show'); //popup displayed
$('body').on('click', '#edit_button_OK', function (event) {
console.log('edit_button_OK'); // WORKING
prevent_edit = true;
$("#form_unblind_edit").trigger('submit'); //form submission = NOT WORKING
})
}
});
});
Maybe change the type of the submit button in the form to "button"
<button type="button">Submit</button>
This way the submit action is not executed when the user clicks submit and instead you display the popup. Then you should be able to submit the form using JQuery.
$("#form_unblind_edit").trigger('submit');

jquery datatables fnAddData from dialog form ajax not working

I have a datatable defined at document ready as follows
$(document).ready(function() {
var oTable = $('#systemgoals').dataTable({});
I have a dialog with form and a button with the following function
buttons: {
"Add System Goal": function() {
var formfilled = true;
$("form#add_systemgoal :text, form#add_systemgoal :file, form#add_systemgoal :checkbox, form#add_systemgoal select, form#add_systemgoal textarea").each(function() {
if($(this).val() === "")
formfilled = false;
});
if(formfilled === true){
$('form#add_systemgoal .error').remove();
var formdata = $('form#add_systemgoal').serialize();
$.ajaxSetup({async: false});
$.ajax({
type: "POST",
url: '/admin/systemgoals/systemgoalupdate?format=html',
data: formdata,
success: function (data) {
var obj = $.parseJSON(data);
if(obj.success){
$(oTable).dataTable().fnAddData( [
obj.inserted.goal_id,
obj.inserted.value,
obj.inserted.status,
obj.inserted.points_per_action,
obj.inserted.created,
obj.inserted.due,
obj.inserted.expires ]);
}
}
});
}
the ajax is fine the form posts the correct values respond but the fnAddData returns error
ReferenceError: oTable is not defined
Any advice appreciated
thank you
You didn't set your oTable as a global variable that why oTable on your dialog is not define, if you want to define it on your script do something like:
var oTable;
$(document).ready(function() {
oTable = $('#systemgoals').dataTable({});
And on your dialog
oTable.fnAddData( [
obj.inserted.goal_id,
obj.inserted.value,
obj.inserted.status,
obj.inserted.points_per_action,
obj.inserted.created,
obj.inserted.due,
obj.inserted.expires ]);
}
or just simply do
var oTable = $('#systemgoals').dataTable().fnAddData...
Best Regards

subpage loaded through ajax is killing jquery functionality

I'm working on a site, http://teneo.telegraphbranding.com/, and I am hoping to load the pages via ajax so that the sidebar and its animation remain consistent.
When the 'About' link is clicked I need it to load about2.php via a jquery ajax function. But I'm not having any luck. When I can get the page to load via ajax it kills all the jquery functionality on the page. From what I've read I think I need to call the jquery upon successful completion of the ajax call.
I've tried everything it seems and can't get it work. What I need is about2.php to load when the link is clicked and the jquery to dynamically size the divs, like it does on the homepage.
I tried this, but it won't even load the page:
//Dropdown
$(document).ready(function () {
var dropDown = $('.dropdown');
$('h3.about').on('click', function() {
dropDown.slideDown('fast', function() {
var url = 'about2.php'
$.get(url, function(data) {
//anything in this block runs after the ajax call
var missionWrap = $('#mission-wrap');
var w = $(window);
w.on('load resize',function() {
missionWrap.css({ width:w.width(), height:w.height()});
});
var missionContent = $('#mission-content');
var w = $(window);
w.on('load resize',function() {
missionContent.css({ width:w.width() - 205 });
});
});
});
});
});
And then this loads the page, but kills all the jQuery associated with it:
var dropDown = $('.dropdown');
$('h3.about').on('click', function() {
dropDown.slideDown('fast', function() {
$('#index-wrap').load('/about2.php');
});
});
Thank you very much.
I also tried this and it just broke everything:
$(document).ready(function () {
var dropDown = $('.dropdown');
$('h3.about').on('click', function () {
dropDown.slideDown('fast', function () {
$.ajax({
type: 'GET',
url: 'about2.php',
success: function () {
var missionWrap = $('#mission-wrap');
var w = $(window);
w.on('load resize', function () {
missionWrap.css({
width: w.width(),
height: w.height()
});
});
var missionContent = $('#mission-content');
var w = $(window);
w.on('load resize', function () {
missionContent.css({
width: w.width() - 205
});
});
};
});
});
});
});
This should work.
function resize_me () {
var w = $(window);
var missionWrap = $('#mission-wrap');
var missionContent = $('#mission-content');
missionWrap.css({ width:w.width(), height:w.height()});
missionContent.css({ width:w.width() - 205 });
}
//Dropdown
$(document).ready(function () {
$(window).on('load resize', function () {
resize_me();
});
var dropDown = $('.dropdown');
$('h3.about').on('click', function() {
dropDown.slideDown('fast', function() {
var url = 'about2.php'
$.get(url, function(data) {
resize_me();
});
});
});
}
I believe that the problem was that the load event that you were attaching to the window object was not being triggered by the successful load of the $.get.
This is a rough outline of how to structure your application to handle this correctly.
Assuming your HTML looks something like this:
<html>
...
<div id="index-wrap">
<!-- this is the reloadable part -->
...
</div>
...
</html>
You need to refactor all the jQuery enhancements to the elements inside #index-wrap to be in a function you can call after a reload:
function enhance(root) {
$('#some-button-or-whatever', root).on('click', ...);
}
(I.e. look up all the elements under the root element that was loaded using AJAX.)
You need to call this function when the page is first loaded, as well as after the AJAX call in the completion callback:
$('#index-wrap').load('/foo.php', function() {
enhance(this);
});
You can also potentially get rid of some of this using delegated ("live") events, but it's best to hit the jQuery documentation on how those work.
As for events bound to window or DOM elements which aren't loaded dynamically, you shouldn't need to rebind them at all based on which subpage is loaded, just check which of your elements loaded is in a handler that you set up once:
$(window).on('load resize', function() {
var $missionContent = $('#missionContent');
if ($missionContent.length) {
$missionContent.css(...);
}
});

jQuery dialog for a partial view is not opening modal

I have built a jquery dialog to show a partial view for entering data.
I have built the action link:
#Html.ActionLink("Add New Service Provider", "PartialNewCust", "Customer", null, new { #class = "addServiceProviderLink" })
I have the controller action:
public ActionResult PartialNewCust()
{
return PartialView();
}
And the div / jQuery code:
<div id="AddServiceProvDialog" title="Add Service Provider"></div>
<script type="text/javascript">
var linkObj;
$(function () {
$(".addServiceProviderLink").button();
$('#AddServiceProvDialog').dialog(
{
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons:
{
"Add": function () {
$("#addProviderForm").submit();
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".addServiceProviderLink").click(function () {
linkObj = $(this);
var dialogDiv = $('#AddServiceProvDialog');
var viewUrl = linkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
//validation
var $form = $("#addProviderForm");
// Unbind existing validation
$form.unbind();
$form.data("validator", null);
// Check document for changes
$.validator.unobtrusive.parse(document);
// Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);
//open dialog
dialogDiv.dialog('open');
return false;
});
});
});
The partial view renders fine but opens a new page and does not come up as a modal dialog.
What am I doing wrong.
On a side note: my autocomplete code is also not working by my jQuery datetime picker is...
$(document).ready(function()
{
$(".date").datepicker();
}
);
$(document).ready(function () {
$("#CustByName").autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
}
});
},
minLength: 3
});
});
My guess is that you misplaced the return false statement in the button's click handler, thus the default behavior is not prevented as you expect, and the link is simply followed:
$(".addServiceProviderLink").click(function () {
...
$.get(viewUrl, function (data) {
dialogDiv.html(data);
...
dialogDiv.dialog('open');
// this return statement should be in the "click" handler,
// not in success callback of the .get() method !
return false;
});
});
Your code should then be:
$(".addServiceProviderLink").click(function () {
...
$.get(viewUrl, function (data) {
...
});
// return here to prevent default click behavior
return false;
});

Resources