Bootstrap Selectpicker not refreshing - ajax

When a user clicks the edit icon the contents of a selectpicker are updated then refreshed. Then the selectpicker's value is updated, then refreshed again, but for some reason it is not updating with the selected value.
Everything works fine when I manually enter in the the same code in the console.
$('#IncWidgetId').val(864)// the value used when breaking in console
$('#IncWidgetId').selectpicker('refresh')
I have ensured that the selectpicker is updated with the new option values along with confirming the deferred is firing in the proper order.
As a double check, I also have separated the .selectpicker('refresh') to make sure it didn't try to fire before the option was selected due to async, but it is still not updating the selectpicker with the selected value.
$(document).on('click', '[id^=EditWidgetId-]', function () {
var id = $(this).attr('id').split('-')[1];
var mfg = $(this).data('mfg');
var widgetid = $(this).data('widgetid ');
var mfgSelect = $('input[name=mfg][value="' + mfg + '"]');
mfgSelect.prop('checked', true);
$.when(LoadWidgets(mfg)).then(function () {
console.log('then function');
$('#IncWidgetId').val(widgetid );
}).done(function () {
console.log('done function');
$('#IncWidgetId').selectpicker('refresh');
});
$('#modalWidgetNew').modal('show');
});
function LoadWidgets(mfg) {
var r = $.Deferred();
console.log('before ajax');
r.resolve($.ajax({
url: '/Widgets/FilterWidgetsDropdown',
type: 'GET',
cache: false,
data: { mfg: mfg },
success: function (partial) {
$('#IncWidgetDDArea').html(partial);
$('#IncWidgetId').selectpicker('refresh')
},
error: function (x, e) {
if (x.status == 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status == 404) {
alert('Requested URL not found.');
} else if (x.status == 500) {
alert('Internel Server Error.');
} else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
})).done(function () {
console.log('after ajax');
return r.promise();
});
}
What am I missing?

There was such an issue in old versions of this plugin.
Try to destroy it and initialize again. Something like this:
$('#IncWidgetId').selectpicker('destroy');
$('#IncWidgetId').selectpicker();

Related

asp.net mvc not getting value from ajax when converting data into json.stringify

I am using a event handler that checks if the product id or name already exist. But my problem is when I am using JSON.stringify() my C# controller does not receive the data from the ajax call,.
// check if Product name already exist
$('#productName').bind('keyup blur', function () {
// check if input is empty
if ($(this).val().length > 0) {
var data = JSON.stringify({
value: $(this).val(),
fieldName: 'productName'
});
$.ajax({
type: "post",
url: '/Product/ValidateProductDetailsExist',
contenttype: "application/json; charset=utf-8",
datatype: "json",
data: data,
context: this,
success: function (result) {
if (result === true) {
// append error message
// check if error message already exist
if ($('#errorprodcutName').length === 0) {
var errormessage = '<div class="col-md-offset-2"><span id = "errorprodcutName" class="validation-error-message">Product name already exist</span></div >';
$('.form-group:nth-child(2)').append(errormessage);
}
$(this).focus();
//disables the save button
$('#btnSaveProduct').prop('disabled', true);
}
else {
// check if error message already exist
if ($('#errorprodcutName').length > 0) {
$('#errorprodcutName').remove();
}
//enables the save button
$('#btnSaveProduct').prop('disabled', false);
}
},
error: function () {
alert("unable to request from server");
}
});
}
});
When I use debugger to check the value, it is null. I don't see any errors that displays in the console as well. Can anyone please explain to me why it is not working.
public JsonResult ValidateProductDetailsExist(string value, string fieldName)
{
using (POSEntities3 db = new POSEntities3())
{
bool isExist = false;
switch (fieldName)
{
case "productId":
var dataItemProductId = db.Products.Where(product => product.product_id == value).SingleOrDefault();
isExist = (dataItemProductId != null);
break;
case "productName":
var dataItemProductName = db.Products.Where(product => product.name == value).SingleOrDefault();
isExist = (dataItemProductName != null);
break;
}
return Json(isExist, JsonRequestBehavior.AllowGet);
}
}

Kendo pager will not reset back to the first page

I have a made a kendo datasource which makes a call out to my api, I have it limited to make pages of 10's. My problem is that the pager will not set back to the first page. For example, when I make a call and to my api and receive 50 results, I will have 5 pages of 10 items each. I select to go to the fifth page which, I then make another call and only receive 10 items which makes one page. However then the cal completes I am still on the 5th page; it will not reset to the first page.
var dataSource = new kendo.data.DataSource({
page:1, << From what I read this is suppose to do the job
pageSize: 10,
transport: {
read: {
type: "POST",
url: location + "/api/ContentSearch/SearchRequest",
contentType: 'application/json',
beforeSend: function (req) {
req.setRequestHeader("Authorization", "Bearer " + token);
}
},
parameterMap: function (option, operation) {
return JSON.stringify(query);
}
},
change: function (e) {
var data = this.data();
$("#searchButton").prop("disabled", false);
$("#loadingGif").hide();
//kendoPager.page(1); << does not work
switch (data.length) {
case 0:
FeedBackMessage("No result found");
break;
case 500:
FeedBackMessage("Please check or refine the search");
break;
default:
$('#pager').show();
$('#descriptionColumn').show();
$("#listView").show();
$("#keyWordText").val("").data("kendoDropDownList").text("");
$("#searchText").val("");
}
return data;
},
error: function (e) {
$("#loadingGif").hide();
ErrorHandler(e.sender.transport.options.read.url, e.xhr.status, e.xhr.statusText, "Kendo datasource was not binded to the WebApi response", "", true);
}
});
function SubmitSearch(e) {
e.preventDefault();
query = {
SearchText: $("#searchText").val(),
KeywordText: generalContentKeywords.text(),
GlobalSearch: true
};
if (query.SearchText === "" && query.KeywordText === "Select Category") {
FeedBackMessage("Please enter a value");
}
else {
if (query.KeywordText === "Select Category") {
query.KeywordText = "";
}
$.when(TokenForWebApi()).then(function (adalToken) {
token = adalToken;
$('#pager').hide();
$('#descriptionColumn').hide();
$("#listView").hide();
$("#searchButton").prop("disabled", true);
$("#loadingGif").show();
dataSource.read();
});
}
};
var kendoPager = $("#pager").kendoPager({
dataSource: dataSource,
}).data("kendoPager");
I went around this issue, by changing my submit function to see if the datasource has any data, and if it find that it does it reset set the page back to one. I am guessing that my previous code, I was trying to set a page value before the datasource had any values to page.
function SubmitSearch(e) {
e.preventDefault();
query = {
SearchText: $("#searchText").val(),
KeywordText: generalContentKeywords.text(),
GlobalSearch: true
};
if (query.SearchText === "" && query.KeywordText === "Select Category") {
FeedBackMessage("Please enter a value");
}
else {
if (query.KeywordText === "Select Category") {
query.KeywordText = "";
}
$.when(TokenForWebApi()).then(function (adalToken) {
if (dataSource._pristineData.length) {
kendoPager.page(1);
}
token = adalToken;
$('#pager').hide();
$('#descriptionColumn').hide();
$("#listView").hide();
$("#searchButton").prop("disabled", true);
$("#loadingGif").show();
dataSource.read();
});
}
};

Ajax request does not work if i dont write return false at the end

This is my validation function written on button click.
function chk_add_area()
{
var areaCountry=$('#areaCountry').val();
var areaCity=$('#areaCity').val();
var area=$('#area').val();
if(areaCountry.trim()=="")
{
$('#err_areaCountry').fadeIn('slow');
$('#err_areaCountry').html("Please Select Country");
$('#areaCountry').focus();
$('#err_areaCountry').fadeOut(3000);
return false;
}
else //if(areaCountry.trim()!="" && areaCity.trim()!="" && area.trim()!="")
{
$.ajax({
url:'ajax.php?action=duplicatearea&areaCountry='+areaCountry+'&areaCity='+areaCity+'&area='+area,
type:'get',
success:function(res)
{
if(res=="exists")
{
$('#err_div').html("Area already exists");
}
}
});
//return false;
}
/* else
{
return true;
} */
}`
if i uncomment return false,it works properly but then the form does not submit on success & i cant proceed further.
Can anyone tell me why?
You need a return false if the area already exists, otherwise drop through.
You don't need to return true; just exiting from the function works fine.
function chk_add_area() { // onsubmit handler
var areaCountry = $('#areaCountry').val().trim();
var areaCity = $('#areaCity').val().trim();
var area = $('#area').val().trim();
if ( areaCountry == "" ) {
$('#err_areaCountry').fadeIn('slow');
$('#err_areaCountry').html("Please Select Country");
$('#areaCountry').focus();
$('#err_areaCountry').fadeOut(3000);
return false;
}
if ( areaCity == "" || area == "" ) {
$('#err_div').html("Please Select City and Area");
return false;
}
$.ajax({
url: 'ajax.php?action=duplicatearea&areaCountry=' + areaCountry +
'&areaCity=' + areaCity + '&area=' + area,
type: 'get',
async: false, // EDIT: added Dec 30
success: function(res) {
if ( res == "exists" ) {
$('#err_div').html("Area already exists");
return false;
}
}
// allow form submit to proceed
}
Also, I recommend using POST instead of GET because GET is cacheable. Someone might add the same area twice.

Polling jQuery ajax for each. Check if element does not exist, if so prepend to div

I have a div #notification-data which on $(document).ready gets populated with multiple <li></li> from $.post.
The $.post then gets called setTimeout(poll_n,9000); so data is up-to-date.
So im not updating all the data every time, I would like to do check if the <li></li> already exists in #notification-data, if it does not exist then I would like to prepend() it to #notification-data.
The data comes in the form of:
<li id="new_notification_1" class="seen_0 li_notification">blah</li>
<li id="new_notification_2" class="seen_0 li_notification">bleh</li>
As an extra question, is this the correct way of long polling?
Here is my code:
function poll_n(){
$.post('<?php echo $siteUrl ?>notifications.php?x=' + (new Date()).getTime() +'', function(data) {
$(data).find(".li_notification").each(function () {
var li_id = $(this).attr('id');
if ($(li_id).closest('#notification-data').length) {
//do nothing
} else {
$('#notification-data').append(??not_sure_what_goes_here??); // process results here
}
});
setTimeout(poll_n,9000);
});
}
EDIT - After answer I have now got this but it does not work (I get nothing in the console).
success: function(data){
$(data).find(".li_notification").each(function() {
var id = $(this).attr('id'),
notification = $('#notification-data');
console.log(id);
console.log('hello');
if (notification.find('#' + id).length === 0) {
// notification doesn't exists yet then lets prepend it
notification.prepend('#' + id);
}
});
},
You can try this:
function poll_n() {
$.ajax({
type: 'POST',
url: 'your url',
success: function(data){
var notification = $('#notification-data');
$.each($(data), function(){
var id = this.id;
if (notification.find('#' + id).length === 0) {
// notification doesn't exists yet then lets prepend it
notification.prepend(this);
}
});
},
complete: function(jqXHR, status) {
if (status === 'success') {
setTimeout(poll_n, 9000);
}
}
});
}
You must call poll_n() again after the request has been completed.

Backbone collection fetch error with no information

I have a strange problem with the fetch of a backbone collection I am working with. In one particular instance of my code I perform a fetch (exactly how I do it in other areas of the code which all work fine), the fetch never seems to make it to the server and the developer tools shows the request as red with the word (canceled) in the status/text field.
I've walked this through into the backbone sync method and I see the $.ajax being built and everything looks fine. Has anyone run into this problem?
here is my code if it helps, this is a function that calls two .ashx services to first check for a file's existence then to open it. The part that isn't working for me is the "me.collection.fetch().
openDocument: function () {
var me = this,
fileId = me.model.get('id'),
userId = Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
fileRequest = '/genericHandlers/DownloadFile.ashx?id=' + fileId + '&userId=' + userId,
fileCheck = '/genericHandlers/CheckFileExistance.ashx?id=' + fileId + '&userId=' + userId;
//hide tooltip
me.hideButtonTooltips();
// Check for file existance
$.ajax({
url: fileCheck
})
.done(function (data) {
if (data && data === "true") {
document.location.href = fileRequest;
me.collection.fetch();
} else if (!!data && data === "false") {
"This file is no longer available.".notify('error');
}
})
.fail(function (data) {
"Something went wrong during the File Existance check".notify('error');
"Something went wrong during the File Existance check".log(userId, 'error', 'Docs');
});
},
my collection:
// docsCollection.js - The collection of ALL the documents available to a given user
// Document Collection
Dashboard.Collections.DocsCollection = Backbone.Collection.extend({
model: Dashboard.Models.DocumentUploadModel,
url: function () {
return 'apps/docs/Docs/' + this.userId;
},
initialize: function (options) {
this.userId = options.userId;
this.deferredFetch = this.fetch();
},
comparator: function (model) {
return -(new Date(model.get('expirationDate')));
},
getDaysSinceViewedDocuments: function () {
return this.filter(function (model) {
return model.get('daysSinceViewed') !== null;
});
},
getNewDocuments: function () {
return this.filter(function (model) {
return model.get('isNew');
});
},
getExpiredDocuments: function () {
return this.filter(function (model) {
return model.get('isExpired');
});
}
});
and my model:
Dashboard.Models.DocumentUploadModel = Backbone.Model.extend({
defaults: {
fileArray: [],
name: '',
description: '',
accesses: [],
tags: [],
expirationDate: ''
},
initialize: function () {
this.set({
userId: Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
expirationDate: (this.isNew()) ? buildExpirationDate() : this.get('expirationDate')
}, { silent: true });
function buildExpirationDate() {
var date = new Date((new Date()).getTime() + 24 * 60 * 60 * 1000 * 7),
dateString = "{0}/{1}/{2}".format(date.getMonth() + 1, date.getDate(), date.getFullYear());
return dateString;
}
},
firstFile: function () {
return this.get('fileArray')[0];
},
validate: function (attributes) {
var errors = [];
if (attributes.name === '' || attributes.name.length === 0)
errors.push({
input: 'input.txtName',
message: "You must enter a name."
});
if (attributes.description === '' || attributes.description.length === 0)
errors.push({
input: 'textarea.taDescription',
message: "You must enter a description."
});
if (errors.length > 0)
return errors;
return;
},
sync: function (method, model, options) {
var formData = new FormData(),
files = model.get("fileArray"),
$progress = $('progress'),
success = options.success,
error = options.error;
// Nothing other than create or update right now
if (method !== "create" && method !== "update")
return;
// Build formData object
formData.append("name", model.get("name"));
formData.append("description", model.get("description"));
formData.append("accesses", model.get("accesses"));
formData.append("tags", model.get("tags"));
formData.append("expirationDate", model.get("expirationDate"));
formData.append("userId", model.get("userId"));
formData.append("isNew", model.isNew());
// if not new then capture id
if (!model.isNew())
formData.append('id', model.id);
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
xhr = new XMLHttpRequest();
xhr.open('POST', '/genericHandlers/UploadDocsFile.ashx');
xhr.onload = function () {
if (xhr.status === 200) {
if (success)
success();
} else {
if (error)
error();
}
}
if ($progress.length > 0) {
xhr.upload.onprogress = function (evt) {
var complete;
if (evt.lengthComputable) {
// Do the division but if you cant put 0
complete = (evt.loaded / evt.total * 100 | 0);
$progress[0].value = $progress[0].innerHTML = complete;
}
}
}
xhr.send(formData);
},
upload: function (changedAttrs, options) {
this.save("create", changedAttrs, options);
}
});
You're assigning a value to document.location.href before you try to fetch your collection:
document.location.href = fileRequest;
me.collection.fetch();
Changing document.location.href will change the whole page and in the process, any currently running JavaScript will get shutdown so I wouldn't expect your me.collection.fetch() to ever get executed.

Resources