dijit.form.ValidationTextBox calls validator function twice onBlur - ajax

I have an AJAX call to check the availability of username using Dojo and PHP. Everything is working great, but there is something huge happening behind. Every time I type a word or during onBlur event, dojo makes AJAX call twice and sometimes thrice. I read this link and they say it is fixed since v1.3, I am using v1.7. I tried putting the AJAX function inside setTimeout() and put a 3 secs delay but still the same thing happens. How can prevent that and do only one AJAX call?
var _username = new dijit.form.ValidationTextBox({
name : "{{ username.name }}",
type : "text",
required : true,
invalidMessage : message.invalid.username
}, "{{ username.id }}");
dijit.byId("{{ username.id }}").validator = fnUsernameAvailable;
function fnUsernameAvailable(a) {
if (a === "" )
return false;
dojo.xhrPost({
url : "{{ site_url() }}/ajax/check_username_availability",
handleAs: "json",
content : {
username : a,
csrf_libtracking : fnCsrf()
},
load : function(data) {
_isAvailable = data.result;
}
});
return _isAvailable;
}

You could use a little trick like :
inside you ValidationTextBox, add a property :
var _username = new dijit.form.ValidationTextBox({
_beingChecked: false,
name : "{{ username.name }}",
type : "text",
required : true,
invalidMessage : message.invalid.username
}, "{{ username.id }}");
function fnUsernameAvailable(a) {
if (a === "" || this._beingChecked)
return false;
this._beingChecked = true;
dojo.xhrPost({
url : "{{ site_url() }}/ajax/check_username_availability",
handleAs: "json",
content : {
username : a,
csrf_libtracking : fnCsrf()
},
load : dojo.hitch(this, function(data) {
// _isAvailable = data.result; <-- is this really useful ?
this._beingChecked = false;
dojo.publish("some/topic/to/tell/widgets/it/is/done", [data.result]);
})
});
}
then somewhere in your code, or in your widget you dojo.subscribe to the topic, so that when something is published, you run a function ?

Thanks for the reply. My original plan was to contact the server, check if username is available, via AJAX, and return the var _isAvailable to trigger the invalidMessage property of the ValidationTextBox if the result is false. This would also trigger the tooltip to appear beside the textbox which I wanted to happen.
Pardon for my little knowledge on dojo as this is my first time using this framework.

Related

Kendo UI Large Parameters Value (414 Request-URI Too Long) error

Hy This code is part of my grid.
grid._parameterMap = function (data, type) {
if (type !== "read" && data.models)
return { models: kendo.stringify(data.models) };
var warehouseCodeList = [];
var selectedWarehouse_OnPhysicalCountDefinition = '';
$.each(KendoData('mltWarehouse_OnPhysicalCountDefinition').dataItems(), function (index, value) {
selectedWarehouse_OnPhysicalCountDefinition += value.WarehouseCode + ',';
});
selectedWarehouse_OnPhysicalCountDefinition = selectedWarehouse_OnPhysicalCountDefinition.slice(0, -1);
var parameters = {
warehouseCodeList: selectedWarehouse_OnPhysicalCountDefinition,
periodDateString: $('#dpcPeriodDate_OnPhysicalCountDefinition').val(),
Page: data.page,
PageSize: data.pageSize
}
return kendo.data.transports["odata"].parameterMap(parameters, type);
};
And parameters value is
Page
:
1
PageSize
:
50
periodDateString
:
"17/10/2022"
warehouseCodeList
:
"480176,480172,480003,480166,480109,480025,480090,480089,480002,480088,
480061,480101,480016,480009,480095,480008,480094,480093,480006,480092,480005,480091,480004,
480117,480033,480114,480060,480113,480163,480030,480059,2011,480157,480028,480045,480048,
480039,480029,480120,480046,480156,480049,480072,480063,480062,48006100,480071,480070,480069,
480068,480067,480066,480065,480064,480077,480076,480085,480084,480082,480078,480073,480075,480079,
480074,480083,480127,480128,480057,480129,480058,480081,480080,480141,480132,480131,480130,480140,
480138,480137,480136,480135,480134,480133,480146,480145,480154,480153,480151,480147,480142,480144,
480148,480143,480152,480139,480150,480149,480106,480126,480055,480165,480167,480100,480123,480053,
480096,480168,480162,480159,480158,480038,480102,480017,480013,480122,480047,480116,480032,480034,
480107,480040,480118,480098,480051,480110,480026,480111,480027,480108,480103,480115,480031,480035,
480087,480086,480036,480119,480112,480010,480097,480155,480124,480054,480019,480099,480104,480171,
480164,480041,480042,480121,480043,480044,480014,480052,480170,480037,480050,480012,480105,480169,
480161,480174,480173"
You can see that my data and that large data not going my controller becouse of that large warehouseCodeList.You can see Request below.This request is Send Get Request in Controller.If I can change Post I think gone work bu HOW! =)
Request URL: https://zzzz/Inv/yyy/xxxx/?%24inlinecount=allpages&%24format=json&warehouseCodeList=480176%2C480172%2C480003%2C480166%2C480109%2C480025%2C480090%2C480089%2C480002%2C480088%2C480061%2C480101%2C480016%2C480009%2C480095%2C480008%2C480094%2C480093%2C480006%2C480092%2C480005%2C480091%2C480004%2C480117%2C480033%2C480114%2C480060%2C480113%2C480163%2C480030%2C480059%2C2011%2C480157%2C480028%2C480045%2C480048%2C480039%2C480029%2C480120%2C480046%2C480156%2C480049%2C480072%2C480063%2C480062%2C48006100%2C480071%2C480070%2C480069%2C480068%2C480067%2C480066%2C480065%2C480064%2C480077%2C480076%2C480085%2C480084%2C480082%2C480078%2C480073%2C480075%2C480079%2C480074%2C480083%2C480127%2C480128%2C480057%2C480129%2C480058%2C480081%2C480080%2C480141%2C480132%2C480131%2C480130%2C480140%2C480138%2C480137%2C480136%2C480135%2C480134%2C480133%2C480146%2C480145%2C480154%2C480153%2C480151%2C480147%2C480142%2C480144%2C480148%2C480143%2C480152%2C480139%2C480150%2C480149%2C480106%2C480126%2C480055%2C480165%2C480167%2C480100%2C480123%2C480053%2C480096%2C480168%2C480162%2C480159%2C480158%2C480038%2C480102%2C480017%2C480013%2C480122%2C480047%2C480116%2C480032%2C480034%2C480107%2C480040%2C480118%2C480098%2C480051%2C480110%2C480026%2C480111%2C480027%2C480108%2C480103%2C480115%2C480031%2C480035%2C480087%2C480086%2C480036%2C480119%2C480112%2C480010%2C480097%2C480155%2C480124%2C480054%2C480019%2C480099%2C480104%2C480171%2C480164%2C480041%2C480042%2C480121%2C480043%2C480044%2C480014%2C480052%2C480170%2C480037%2C480050%2C480012%2C480105%2C480169%2C480161%2C480174%2C480173&periodDateString=17%2F10%2F2022&Page=1&PageSize=50
Request Method: GET
Status Code: 200 OK
And Finaly I try the give dataSource remote but not work .But I can give that data ın Ajax call.Can you Help me ?
What can I do in this situation?
There is a type option for the dataSource transport configuration that you can set. It will set the type of request the dataSource would make ("POST", "GET", "PUT" or "DELETE").
Thanks aleksandar.The code I use is below
<script>
var dataSource = new kendo.data.DataSource({
transport: {
read: {
/* omitted for brevity */
type: "POST"
}
}
});
</script>

ajax Preloader is not working in chrome,safari while working in firefox

I have a problem in "Ajax Loader image". On Firefox it is working fine but on chrome that ajax loader image does not seems.
I have a some attributes on sidebar when I check any attribute Products changes according with it and a Preloader image generated before ajax completed.What I am doing is when I check on any attribute first I insert a gif image in div html and show it using .show() method and after success of ajax I set div html null and hide it.
You can see that div in firebug (<div id="ajax_loader_div" style="display:none;"></div>)
Code is really complicated that's why I am not posting code here.Really very Sorry for that.You can see it on http://vcompare4u.com/wpcompare/products/laptops/
I need help.Please
Thanks!!!
I've seen your code
It is well known a synchronous requests will lock the UI. So not surprisingly on chrome and safari, (it does in Firefox interestingly)
can you try something like this
jQuery('#customtag_widget-2 .compare_attribute').bind('change',
jQuery.filterProductsCompare2 = function () {
$.ajaxSetup({async:false});
jQuery('#ajax_loader_div').css('display', 'block');
jQuery('#ajax_loader_div').html('<img src="http://vcompare4u.com/wpcompare/wp-content/themes/compare/_assets/img/ajax-loader.gif" / >');
jQuery('#customtag_widget-2 .compare_attribute_group').each(function () {
jQuery(this).children().each(function () {
if (jQuery(this).children('.compare_attribute').attr('checked')) {
if (jQuery(this).children('.compare_attribute').attr('name').indexOf('b[') != -1) {
brands.push(jQuery(this).children('.compare_attribute').attr('value'));
}
if (jQuery(this).children('.compare_attribute').attr('name').indexOf('c[') != -1) {
categories.push(jQuery(this).children('.compare_attribute').attr('value'));
}
}
})
} else {
minmaxarr = jQuery(this).attr('value').split(';');
minPrice = minmaxarr[0];
maxPrice = minmaxarr[1];
}
if (!jQuery.support.placeholder) {
if (isEmptyPlaceholder == 1) {
jQuery(this).val('Search...');
}
}
})
if (jQuery('#dont_change_price').is(':checked')) {
minPrice = jQuery('#overall_min').val();
maxPrice = jQuery('#overall_max').val();
} else {}
jQuery.ajax({
url : file_url,
data : {
ajaxsearch : '1',
s : 'compare',
ki : keywords_comparei,
product : '',
c : categories,
b : brands,
checked_id : checked_string,
dont_change_price : dont_change_price,
min : minPrice,
max : maxPrice,
product_category : product_category
},
success : function (data) {
// Do stuff here
}
});
jQuery.ajax({
url : bracket_file_url,
data : {
ajaxsearch : '1',
s : 'compare',
ki : keywords_comparei,
product : '',
c : categories,
b : brands,
checked_id : checked_string,
min : minPrice,
max : maxPrice,
product_category : product_category
},
success : function (bracket_data) {
// DO stuff here
}
});
if (!jQuery('#dont_change_price').is(':checked')) {
jQuery.ajax({
url : price_file_url,
data : {
ajaxsearch : '1',
s : 'compare',
ki : keywords_comparei,
product : '',
c : categories,
b : brands,
checked_id : checked_string,
min : minPrice,
max : maxPrice,
product_category : product_category
},
success : function (price_data) {
// DO stuff here
}
});
}
jQuery('#ajax_loader_div').hide();
jQuery('#ajax_loader_div').html('');
$.ajaxSetup({async:true});
});
What I am trying to do is to do synchronous request for each ajax request and instead of using success functions I am using ajax request separately. Due to synchronous nature each request will be processed one after another.
Inspecting your code in chrome console I've seen ajax loader for very little moment get hided immediately.
here is reference problem same like yours
Force UI repaint in Webkit (Safari & Chrome) right before Synchronous "Ajax" request
<div id="#ajax_loader_css" style="display:none;"></div>
should be
<div id="ajax_loader_css" style="display:none;"></div>
Based on the accepted answer here valid values for an id element are
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Firefox is obviously trying to fix it by removing the invalid character making the #ajax_loader_css css selector match something where as chrome is ignoring it so your selector matches nothing.

jqGrid: add loadonce as parameter to the AJAX-request

I have a PHP-script to handle the AJAX-Requests of many different jqGrid's.
I generate the "ORDER BY" statement with the 'sidx' and 'sord' parameters and the "LIMIT" statement with the 'page' and 'rows' parameters.
Similar to the PHP-example here.
The problem is, that in the PHP-script I can not determine if the loadonce-parameter of the current jqGrid is set or not.
But only if it is not set, I have to filter the returned data (LIMIT by page and rows).
How can I force jqGrid to send an additional parameter?
I dont want to change all my Grids. Is there a global way of doing it?
------ EDIT ------
With the help from this answers (here and here) i got this now.
$.extend($.jgrid.defaults, {
postData: {
loadingType: function() {
var isLoadonce = $("#list1").jqGrid('getGridParam', 'loadonce');
console.log('isLoadonce: ' + isLoadonce);
return isLoadonce ? 'loadAll' : 'loadChunk';
},
},
});
This works, if the Grid has the ID "list1". How can I reference the current Grid without ID?
------ EDIT 2 ------
This seems to work. It looks to me a bit like a hack. Is there a better way?
$.extend($.jgrid.defaults, {
serializeGridData: function(postData) {
var isLoadonce = $(this).jqGrid('getGridParam', 'loadonce');
var newPostData = $.extend(postData, {
loadingType: isLoadonce ? 'loadAll' : 'loadChunk'
});
return $.param(newPostData);
},
});
To pass in an extra parameter you can add:
postData: { ExtraDataName: ExtraDataValue },
then whenever jqGrid goes to get data it will pass that name pair to your controller.
With serializeGridData, jqGrid provides an event to modify the data sent with the Request. The event is called in the context of the current Grid, so we can access the current Grid with this.
By exdending $.jgrid.defaults we can make all Grids sending their loadonce parameter as additional requestparameter without changing any Grid.
$.extend($.jgrid.defaults, {
serializeGridData: function(postData) {
var isLoadonce = $(this).jqGrid('getGridParam', 'loadonce');
var newPostData = $.extend(postData, {
loadingType: isLoadonce ? 'loadAll' : 'loadChunk'
});
return $.param(newPostData);
},
});

AJAX call each() and find() application

The message alert does not appear after the post call under ajax.
Given the following ajax call:
var val= 1;
$.post("ajax.php", { information: val }, function(result)
{
$(result).find("div").each(function()
{
if($(this).text()=="OK")
{
alert("OK");
}
});
});
and the ajax.php file:
<?php
if($_POST['information']==1)
{
?><div>You must fill all the fields</div><?php
?><div>The title must be between 10 and 30 characters</div><?php
?><div>Please insert your email in the field</div><?php
?><div id="answer">OK</div><?php
}
?>
Thanks for your help!
EDIT: corrected errors found by Benny. corrected post syntax and $(result) syntax
In your example you have faulty $.post syntax.
$.post("ajax.php"), { information: $val }, function(result){
// Callback code
});
The correct syntax would be.
$.post("ajax.php", { information: $val }, function(result){
// Callback code
});
Also using $ as part of the $val variable name is confusing. It can trick developers into thinking that it has something to do with the jQuery variable, even though it's just part a local variable name. I would recommend doing just...
var val = 1;

jqGrid display default "loading" message when updating a table / on custom update

I have a case where I need to update a jqgrid based on some search criteria which the user selects. I can get the data to update , but I would want the loading message to show while the new data is being fetched. Can someone please let me know how to get that working ?
Current code follows
var ob_gridContents = $.ajax( {
url : '/DisplayObAnalysisResults.action?getCustomAnalysisResults',
data : "portfolioCategory="+ $('#portfolioCategory').val()
+"&subPortfolioCategory="+ $('#subPortfolioCategory').val()
+ "&subportfolio=" + $('#subportfolio').val(),
async : false
}).responseText;
var ob_Grid = jQuery('#OBGrid')[0];
var ob_GridJsonContents = eval('(' + ob_gridContents + ')');
$('#ob_Grid').trigger("reloadGrid");
ob_Grid.addJSONData(ob_GridJsonContents);
ob_Grid = null;
ob_GridJsonContents = null;
}
If I correct understand what you will, I can recommend you to use jQuery blockUI plugin (http://malsup.com/jquery/block/). Then you don’t need more to use "async : false" parameter of $.ajax function and do something like following:
var WaitMsg = function () {
jQuery('#main').block({ message: '<h1>Die Daten werden vom Server geladen...</h1>' });
};
var StopWaiting = function () {
jQuery('#main').unblock();
};
WaitMsg();
$.ajax({url : '/DisplayObAnalysisResults.action?getCustomAnalysisResults',
data: jQuery.param({portfolioCategory: $('#portfolioCategory').val(),
subPortfolioCategory: $('#subPortfolioCategory').val(),
subportfolio: $('#subportfolio').val()}),
complete: function (data, status) {
if (status === "success" || status === "notmodified") {
var ob_GridJsonContents = jQuery.parseJSON(data.responseText);
...
}
StopWaiting();
},
error: function (xhr, st, err) {
// display error information
StopWaiting();
}
});
I recommend you don’t build parameters with the way like
"portfolioCategory="+ $('#portfolioCategory').val()
+"&subPortfolioCategory="+ $('#subPortfolioCategory').val()
+ "&subportfolio=" + $('#subportfolio').val()
because you can receive encoding problems, if data returned by .val() have some special characters. You could use JavaScript function encodeURIComponent in such cases (like encodeURIComponent($('#portfolioCategory').val()))
or jQuery.param function if you construct a string like p1=val1&p2=val2&...pN=valN.
Best regards
Oleg

Resources