jquery validation ie8 submitHandler not firing - jquery-validate

I have this script:
var pUserName = $('#UserName'), pPassword = $('#Password'), pRememberMe = $('#RememberMe');
$(function () {
Initialize();
$('#logon button').click(function () {
$.event.trigger('AjaxButtonClick', this);
$.event.trigger('AjaxLoader', '#logon .form');
$('form#logon').valid();
});
});
function Initialize() {
returnUrl = getParameterByName('ReturnUrl');
$('form#logon').validate({
submitHandler: function (form) {
logOn(returnUrl);
},
invalidHandler: function (e, validator) {
showAnimatedStatusText($('.message'), 'Please fill in the required fields highlighted below.', 'warning');
$.event.trigger('AjaxButtonError');
$.event.trigger('AjaxLoader');
},
errorPlacement: function (error, element) {
return true;
},
highlight: function (element) {
$(element).parent().addClass("input-validation-error");
},
unhighlight: function (element) {
$(element).parent().removeClass("input-validation-error");
}
});
};
function logOn(returnUrl) {
$.ajax({
url: '/_Account/LogOn',
type: 'POST',
data: '{ "UserName": "' + pUserName.val() + '", "Password": "' + pPassword.val() + '", "RememberMe": ' + pRememberMe.is(':checked') + ', "returnUrl": "' + returnUrl + '" }',
dataType: 'text json',
contentType: 'application/json; charset=utf-8',
success: function (o) {
if (o.success) {
// Success code
$.event.trigger('AjaxButtonSuccess');
} else {
showAnimatedStatusText($('.message'), o.error, 'error');
$.event.trigger('AjaxButtonError');
}
$.event.trigger('AjaxLoader');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
showAnimatedStatusText($('.message'), 'An uncaught error has occurred, please contact your system administrator (Error code: 150).', 'error');
$.event.trigger('AjaxButtonError');
$.event.trigger('AjaxLoader');
}
});
};
this works fine in all browsers except ie8. For some reason the submitHandler is never called. If I enter incorrect data invalidHandler is called fine, but submitHandler never is.
Does anyone know why?
Cheers,
/r3plica

The problem was that using a element in ie8 does not appear to work the same way as an even if you supply . To get this working I had to change my validation script to look like this:
$('#logon').validate({
submitHandler: function () {
// Do not submit
},
invalidHandler: function (e, validator) {
showAnimatedStatusText($('.message'), 'Please fill in the required fields highlighted below.', 'warning');
$.event.trigger('AjaxButtonError');
$.event.trigger('AjaxLoader');
},
errorPlacement: function (error, element) {
return true;
},
highlight: function (element) {
$(element).parent().addClass("input-validation-error");
},
unhighlight: function (element) {
$(element).parent().removeClass("input-validation-error");
}
});
and the calling button click look like this:
$('#logon button').click(function () {
$.event.trigger('AjaxButtonClick', this);
$.event.trigger('AjaxLoader', '#logon .form');
if ($('#logon').valid()) {
logOn(returnUrl);
};
});
doing it this way fixed the issue.

Related

ajaxfileupload problemajaxFileUpload is not a function

I am using ajaxfileupload to upload file , whenever i upload the file it gives me this error . I tried alot to fix it but no luck .
TypeError: $.ajaxFileUpload is not a function
success: function (data, status)
Here is code my code .
$id =$("#id").val();
$.ajaxFileUpload
(
{
type: "POST",
url: "main_page/save_image_data",
secureuri:false,
fileElementId:'userfile'+id,
dataType: 'json',
data: { "image_id":id},
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
},
/*error: function (data, status, e)
{
alert(e);
}*/
}
)
return false;
There is no command $.ajaxFileUpload in the core of jQuery.
So you are probably trying to use an external library and you have not included it in your <head> .
This can be happened if you have include jquery.min.js inside your page.After remove that file problem will be solved.
add this to your file. this method is removed form upper version of jquery.
jQuery.extend({
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error )
s.error( xhr, status, e );
// If we have some XML response text (e.g. from an AJAX call) then log it in the console
else if(xhr.responseText)
console.log(xhr.responseText);
}
});
this is my solution-----Follow the format of the official:
<script type="text/javascript">
$(document).ready(function() {
var interval;
function applyAjaxFileUpload(element) {
$(element).AjaxFileUpload({
action: "MyJsp.jsp",
onChange: function(filename) {
// Create a span element to notify the user of an upload in progress
var $span = $("<span />")
.attr("class", $(this).attr("id"))
.text("Uploading")
.insertAfter($(this));
$(this).remove();
interval = window.setInterval(function() {
var text = $span.text();
if (text.length < 13) {
$span.text(text + ".");
} else {
$span.text("Uploading");
}
}, 200);
},
onSubmit: function(filename) {
// Return false here to cancel the upload
/*var $fileInput = $("<input />")
.attr({
type: "file",
name: $(this).attr("name"),
id: $(this).attr("id")
});
$("span." + $(this).attr("id")).replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
return false;*/
// Return key-value pair to be sent along with the file
return true;
},
onComplete: function(filename, response) {
window.clearInterval(interval);
var $span = $("span." + $(this).attr("id")).text(filename + " "),
$fileInput = $("<input />")
.attr({
type: "file",
name: $(this).attr("name"),
id: $(this).attr("id")
});
if (typeof(response.error) === "string") {
$span.replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
alert(response.error);
return;
}
$("<a />")
.attr("href", "#")
.text("x")
.bind("click", function(e) {
$span.replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
})
.appendTo($span);
}
});
}
applyAjaxFileUpload("#demo1");
});
</script>
at least ,no more this error. And the action will receive the request

Issue in JQuery Confirmation Dialog inside form submit

In a JQuery dialog I have four fields. When I click on Save button I needs to check and validate the following
Validate all required fields ( On submit of form using validate.js and unobstrusive.js )
Check the value of dropdown and if it is of a partcular type ie (Redundant), Show user a confirmation dialog.
If the user confirm by pressing Yes, then close the confirmation dialog and call Ajax
But the problem is when I confirm by clicking Yes button on confirmation dialog, the dialog closes but the execution is not going down.
ie, Serializing the form data and make an Ajax call to call the webservice.
Please can anyone help.
$(function () {
$('form').submit(function () {
$('#result').html(" ");
var redunt = null;
redunt = $(ClientCrud_StatusCodeId).find('option:selected').text();
if ($(ClientCrud_StatusCodeId).find('option:selected').text() == "Redundant") {
$('#clientRedundantMessage2').html("Client once made redundant cannot be reactivated. Are you sure ?");
$("#RedundantMessage2").dialog(
{
autoOpen: false,
height: 170,
width: 420,
modal: true,
resizable: false,
title: "Confirmation for Redundant",
Content: "Fields cannot be left blank.",
buttons: {
"Yes": function () {
redunt = "Active";
$('#RedundantMessage2').dialog('close');
},
"No": function () {
$(this).dialog("close");
return false;
}
}
}) //.dialog("widget").draggable("option", "containment", "none");
$("#RedundantMessage2").dialog("open");
}
if ($(this).valid())
{
debugger;
if (redunt == "Active") {
$.ajax({
url: this.action,
type: this.method,
async: false,
cache: false,
data: $(this).serialize(),
error: function (request) {
$("#result").html(request.responseText);
// event.preventDefault();
},
success: function (result) {
if (result == "success") {
$.ajax({
url: "/Client/ClientGrid",
type: 'POST',
data: { "page": 0 },
datatype: 'json',
success: function (data) {
$('#grid').html(data);
},
error: function () {
alert('Server error');
}
});
$('#myEditClientDialogContainer').dialog('close');
$('#myEditClientDialogContainer').remove()
}
else {
clearValidationSummary();
var a = '<ul><li>' + result + '</li></ul>';
$('#result').html(a);
}
}
});
}
}
$("#griderrormsg1 li").hide().filter(':lt(1)').show();
return false;
});
editallowed = true;
});
I think you have a issue with the sequence of code, when the function $("#RedundantMessage2").dialog( ...... ); execute don't wait for the user response in this case "yes" or "no" so... your flag redunt = "Active" don't make sense.
the buttons option has function that execute when the opcion is choosen, so you must call a function to execute the post
$(function () {
$('form').submit(function () {
$('#result').html(" ");
var redunt = null;
redunt = $(ClientCrud_StatusCodeId).find('option:selected').text();
if ($(ClientCrud_StatusCodeId).find('option:selected').text() == "Redundant") {
$('#clientRedundantMessage2').html("Client once made redundant cannot be reactivated. Are you sure ?");
$("#RedundantMessage2").dialog(
{
autoOpen: false,
height: 170,
width: 420,
modal: true,
resizable: false,
title: "Confirmation for Redundant",
Content: "Fields cannot be left blank.",
buttons: {
"Yes": function () {
redunt = "Active";
trySend();
$('#RedundantMessage2').dialog('close');
},
"No": function () {
$(this).dialog("close");
return false;
}
}
}) //.dialog("widget").draggable("option", "containment", "none");
$("#RedundantMessage2").dialog("open");
}
$("#griderrormsg1 li").hide().filter(':lt(1)').show();
return false;
});
editallowed = true;
});
the other js function
function trySend(){
if ($('#IdOfYourForm').valid())
{
debugger;
if (redunt == "Active") {
$.ajax({
url: this.action,
type: this.method,
async: false,
cache: false,
data: $(this).serialize(),
error: function (request) {
$("#result").html(request.responseText);
// event.preventDefault();
},
success: function (result) {
if (result == "success") {
$.ajax({
url: "/Client/ClientGrid",
type: 'POST',
data: { "page": 0 },
datatype: 'json',
success: function (data) {
$('#grid').html(data);
},
error: function () {
alert('Server error');
}
});
$('#myEditClientDialogContainer').dialog('close');
$('#myEditClientDialogContainer').remove()
}
else {
clearValidationSummary();
var a = '<ul><li>' + result + '</li></ul>';
$('#result').html(a);
}
}
});
}
}
}

BlockUI Ajax loading wrong moment

I know there's other post about this. but there's no answer.
Situation, I have an ajax command. It take time because I have somes things to get.
I want to include a loading between the execution of the ajax.
I want to use jquery BlockUI because its simple and good looking.
But I dont know why the visual effect not working until ajax load the entire data(like when "success" begin).
I try multiple way but not working.
here's my last code :
function from http://www.codeproject.com/Articles/382390/An-Example-to-Use-jQuery-Global-AJAX-Event-Handler
var AjaxGlobalHandler = {
Initiate: function(options) {
$.ajaxSetup({ cache: false });
// Ajax events fire in following order
$(document).ajaxStart(function() {
$.blockUI({
message: options.AjaxWait.AjaxWaitMessage,
css: options.AjaxWait.AjaxWaitMessageCss
});
}).ajaxSend(function(e, xhr, opts) {
}).ajaxError(function(e, xhr, opts) {
if (options.SessionOut.StatusCode == xhr.status) {
document.location.replace(options.SessionOut.RedirectUrl);
return;
}
$.colorbox({ html: options.AjaxErrorMessage });
}).ajaxSuccess(function(e, xhr, opts) {
}).ajaxComplete(function(e, xhr, opts) {
}).ajaxStop(function() {
$.unblockUI();
});
}
};
call ready
var options = {
AjaxWait: {
AjaxWaitMessage: '<h1 class="ui-overlay-loading-content"><img class="ui-overlay-loading-image" src="_inc/img/loading3circle1.gif" />Chargement des données ...</h1>',
AjaxWaitMessageCss: { backgroundColor: '#ffffff' }
},
AjaxErrorMessage: "<h6>Erreur!/h6>"
};
AjaxGlobalHandler.Initiate(options);
call execution
$.ajax({
type: "POST",
url: location.href.split('/').pop() + "?action=" + actionName + "&recherche=" + recherche,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
FillDataGridOnSuccess(response, gridId, dataTypeName);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("xhr.status : " + xhr.status);
alert("thrownError : " + thrownError);
}
});
I try also
var ajaxSettings = function(options) {
return $.extend(
{
beforeSubmit: function() {
//beforeSend: function() {
$.blockUI({ overlayCSS: { backgroundColor: '#ffffff' },
message: '<h1 class="ui-overlay-loading-content"><img class="ui-overlay-loading-image" src="_inc/img/loading3circle1.gif" />Chargement des données ...</h1>'
});
},
complete: function() {
$.unblockUI();
}
},
options
);
};
Every test that I did end with a loading who seems to only appear on ajaxSuccess.
I know there's sample on official blockUI site http://jquery.malsup.com/block/#demos
and they working there, but I cant on my own. did anybody see why?
tank you

How to use ajaxStart if $.ajax method is defined in a class?

I have created ajax method in one class in my js file. Below is enclosed for the reference
var ajaxcall =
{
SitePath: '',
data: '',
url: '',
callbackfunction: '',
fileElementId: '',
AjaxRequest: false,
callback: true,
async: false,
folder: '',
filename: '',
Call: function () {
if (ajaxcall.AjaxRequest == true) {
alert(ajaxcall.AjaxRequest);
return;
}
else {
try {
ajaxcall.AjaxRequest == true;
alert('b');
$.ajax({
type: "POST",
url: ajaxcall.url,
data: ajaxcall.data,
contentType: "application/json; Characterset=utf-8",
dataType: "json",
async: false,
success: function (data) {
if (ajaxcall.callback == true) {
ajaxcall.callbackfunction(data);
}
},
error: function (request, status, error) {
//alert("Exception Handling : \n" + request.responseText);
alert('Unable to process the request at this moment! Please try again later.');
},
complete: function () {
ajaxcall.AjaxRequest = false;
}
});
}
catch (e) {
ajaxcall.AjaxRequest == false;
// alert("Error Catch : " + e.Description + '\n' + 'Message: ' + e.Message);
}
}
},
AjaxFileUpload: function () {
$.ajaxFileUpload({
type: "POST",
url: "../GenericHandlers/FileUploader.ashx?path=" + ajaxcall.folder,
dataType: 'json',
async: false,
secureuri: false,
fileElementClass: ajaxcall.fileElementClass,
success: function (data) {
var data = data.toString();
ajaxcall.filename = data.substring(6, data.length - 7);
alert(ajaxcall.filename);
return true;
}
});
}
};
Now i want to show a div when ajax call starts and hide after finish.
So for that i have used
$(document).ready(function(
$('#Loading').ajaxStart(function () {
alert('a');
$('#Loading').show();
}).ajaxStop(function () {
$('#Loading').hide();
});
});
But when i call the ajax method (defined above in the class), control goes into ajax method first then in ajaxStart.
I don't know why it is happening. Please help.
Use the recommended global for these:
$.ajaxStart(function() {
$("#Loading").show();
});
$.ajaxComplete(function() {
$("#Loading").hide();
});
Try it this way attached to your Loading id element:
$("#Loading").ajaxStart(function() {
$(this).show();
});
$("#Loading").ajaxComplete(function() {
$(this).hide();
});
AjaxStart called when the http request start, not when the ajax method executes.

JSON, jQueryUI Autocomplete, AJAX - Cannot get data when array is not local

I have searched stackoverflow, as well as the web for some insight into how to get the jQueryUI Autocomplete plugin working with my JSON data, and I'm at a loss. I had it working like a charm with a local data array. I was able to pull values and build html.
I ran into a problem when I had to pull JSON form this source:
/Search/AjaxFindPeopleProperties2
?txtSearch=ca pulls up the test data that I am trying to loop through, when I type in 'ca' to populate the autocomplete list. One of the problems is that ?term=ca is appended to the url instead of ?txtSearch=ca and I'm not sure how to change it.
This is an example of the data:
{
"MatchedProperties": [
{
"Id": 201,
"Name": "Carlyle Center",
"Description": "Comfort, convenience and style are just a few of the features you'll ...",
"ImageUrl": "/Photos/n/225/4989/PU__ThumbnailRS.jpg"
}
]
}
...and here is the ajax call I'm trying to implement:
$(document).ready(function () {
val = $("#txtSearch").val();
$.ajax({
type: "POST",
url: "/Search/AjaxFindPeopleProperties2",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#txtSearch').autocomplete({
minLength: 0,
source: data.d, //not sure what this is or if it's correct
focus: function (event, ui) {
$('#txtSearch').val(ui.item.MatchedProperties.Name);
$.widget("custom.catcomplete", $.ui.autocomplete, {
//customize menu item html here
_renderItem: function (ul, item) {
return $("<li class='suggested-search-item" + " " + currentCategory + "'></li>")
.data("item.autocomplete", item)
.append($("<a><img src='" + item.MatchedProperties.ImageUrl + "' /><span class='name'>" + item.MatchedProperties.Name + "</span><span class='location'>" + "item.location" + "</span><span class='description'>" + item.MatchedProperties.Description + "</span></a>"))
.appendTo(ul);
},
_renderMenu: function (ul, items) {
var self = this,
currentCategory = "Properties Static Test Category";
$.each(items, function (index, item) {
if (item.category != currentCategory) {
ul.append("<li class='suggested-search-category ui-autocomplete-category'>" + currentCategory + "</li>");
//currentCategory = item.category;
}
self._renderItem(ul, item);
});
}
}//END: widget
//return false;
},
select: function (event, ui) {
$('#txtSearch').val(ui.item.MatchedProperties.Name);
//$('#selectedValue').text("Selected value:" + ui.item.Abbreviation);
return false;
}
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
}); //END ajax
}); //END: doc ready
and I'm initializing here:
<script type="text/javascript">
//initialize autocomplete
$("#txtSearch").autocomplete({ //autocomplete with category support
/*basic settings*/
delay: 0,
source: "/Search/AjaxFindPeopleProperties2",
autoFocus: true,
minLength: 2 //can adjust this to determine how many characters need to be entered before autocomplete will kick in
});
//set auto fucus
$("#txtSearch").autocomplete("option", "autoFocus", true);
</script>
any help would be great...
Thanks!

Resources