Update JSON with refreshInterval - json

I want to update every 10 seconds json data.
With this function crashes the script.
Is there a better way?
$(function refreshUsers() {
$.getJSON('/api/TrainlocationList/', function (loadscale) {
$(loadscale).each(function (i, item) {
$(item).each(function (i, Type) {
$('#LabelID').html(Type.TrainLocationName);
var refreshInterval = setInterval(refreshUsers, 10 * 1000);
});
});
});
});

Try this...
setInterval(function() {
$.getJSON('/api/TrainlocationList/', function (loadscale) {
$(loadscale).each(function (i, item) {
$(item).each(function (i, Type) {
$('#LabelID').html(Type.TrainLocationName);
});
});
});
}, 10000)

Related

Jquery UI autcomplete with Json data source

I am using jquery UI autocomple with json data source but it's not working but when I used same with fixed data it works. Below is my code.
$(document).ready(function () {
var codes = "";
Admin_BasicFeeSchedule.LoadCPTCodes().done(function (response) {
if (response.status != false) {
if (response.CPTCodeCount > 0) {
var CPTCodeLoadJSONData = JSON.parse(response.CPTCodeLoad_JSON);
$.each(CPTCodeLoadJSONData, function (i, item) {
codes = codes + "'" + item.ShortName + "'";
});
//codes = codes + "]";
alert(codes);
}
}
else {
utility.DisplayMessages(response.Message, 3);
}
});
$.widget("ui.autocomplete", $.ui.autocomplete, {
_renderMenu: function (ul, items) {
var that = this;
$.each(items, function (index, item) {
that._renderItemData(ul, item);
});
$(ul).wrap("<div></div>");
},
});
$("input#ddlCPTCode").autocomplete({
source: [codes],//['Tom', 'Alex', 'Patrick'],
});
});
Based on jQueryUI's API, the source option can either be an array or a String that points to an URL or a Function. Furthermore, your code needs to change few things so that the array is handled in appropriate fashion:
$(document).ready(function () {
var codes = []; // array is created
Admin_BasicFeeSchedule.LoadCPTCodes().done(function (response) {
//alert("LoadCPTCodes works") ;
if (response.status != false) {
//alert("response.status true") ;
if (response.CPTCodeCount > 0) {
//alert("CPTCodeCount > 0") ;
var CPTCodeLoadJSONData = JSON.parse(response.CPTCodeLoad_JSON);
$.each(CPTCodeLoadJSONData, function (i, item) {
codes.push(item.ShortName); //add item to an array
});
//codes = codes + "]";
alert(codes);
}
}
else {
utility.DisplayMessages(response.Message, 3);
}
});
$.widget("ui.autocomplete", $.ui.autocomplete, {
_renderMenu: function (ul, items) {
var that = this;
$.each(items, function (index, item) {
that._renderItemData(ul, item);
});
$(ul).wrap("<div></div>");
},
});
$("input#ddlCPTCode").autocomplete({
source: codes // pass an array (without a comma)
});
});
Finally, if those changes related to the array aren't enough to make it work, then I would check the JSON load part. I have added some alert calls that can be uncommented for JSON testing purposes. As I am not familiar with the details of the JSON load functionality that is used in the sample code, then I'm just going to mention that there are alternative ways of loading JSON data such as jQuery's getJSON method.

jquery toggle function and set a cookie

I have the following function which toggles mouseenter and mouseleave on click:
var flag = true;
$('.aaa').mouseenter(function () {
if(flag) {
$(this).css('background', '#aaaaaa');
}
$(this).css('border', 'solid 1px red');
});
$('.aaa').mouseleave(function () {
if(flag) {
$(this).css('background','blue');
}
$(this).css('border', 'solid transparent 1px');
});
$('#tog').click(function () {
flag = !flag;
});
http://jsfiddle.net/z8KuE/15/
How can chosen preference be "remembered" and loaded on the next page load?
edit: in case that the solution from bellow doesn't work on the site for some reason, just put it here:
(function($){
$(document).ready(function(){
//Scripts go in here!
});
})(jQuery);
I would use the jQuery cookie plugin:
var storedFlag = $.cookie('userSelection'); // read cookie
var flag = 1; //default value
if(storedFlag != undefined){ // some flag was stored
flag = storedFlag;
}
$('.aaa').mouseenter(function () {
if(flag > 0) {
$(this).css('background', '#aaaaaa');
}
$(this).css('border', 'solid 1px red');
});
$('.aaa').mouseleave(function () {
if(flag > 0) {
$(this).css('background','blue');
}
$(this).css('border', 'solid transparent 1px');
});
$('#tog').click(function () {
flag = 1 - flag;
$.cookie('userSelection', flag, { expires: 30 }); // store cookie
});
The problem is that the boolean values are stored as strings, and the string 'false' is a true value, thus i resorted to using numbers and >0 comparison.
See updated fiddle

Firefox html5 drag and drop not working

I know there are a lot of similar questions on here, but, when putting them to action, I still resolve in the same problem.
I have 2 angular directives (drag and drop) and one angular factory (dndAPI). This is all based off of fisshy's Angular Drag and Drop on github.
I finally got firefox to accept and drag movement by adding data to the event, however I can't seem to keep it from doing it's default behavior (and loading that data as a url). I also apologize I couldn't get it to work at all on jsfiddle...at all. I'll try again if someone can't see if I'm doing something outrageously wrong.
angular.module('dragAndDrop', [])
.directive('drag',function (dndApi) {
var drags = [],
dragging = new RegExp('(\\s|^)dragging(\\s|$)');
return {
restrict: 'A',
scope: {
item: '=drag',
whenStart: '&',
whenEnd: '&',
dropzones: '='
},
link: function (scope, elem, attr, ctrl) {
elem.bind('dragstart', function (e) {
angular.element('query-tool-tip').removeClass('active');
//if ( drags.length === 0 ) {
drags = document.querySelectorAll('.drop');
//}
angular.forEach(drags, function (value, key) {
if (scope.dropzones.indexOf(value.getAttribute('drop')) >= 0) {
value.className = value.className + ' dragging';
}
});
elem.addClass('dragging');
dndApi.setData(scope.item, scope.dropzones);
e.originalEvent.dataTransfer.effectAllowed = 'move';
//KEEPS FIREFOX FROM CRAPPING OUT:
e.originalEvent.dataTransfer.setData( 'text/plain', 'stop' );
scope.$apply(function () {
scope.whenStart({ data: dndApi.getData() });
});
});
elem.bind('dragleave', function(e){});
elem.bind('dragend', function (e) {
elem.removeClass('dragging');
angular.forEach(drags, function (value, key) {
value.className = value.className.replace(dragging, '');
});
scope.$apply(function () {
scope.whenEnd({ data: dndApi.getData() });
});
dndApi.removeData();
e.preventDefault();
});
elem[0].draggable = true;
elem[0].className = elem[0].className + ' drag';
}
};
}).directive('drop',function (dndApi) {
var drags = [],
dragging = new RegExp('(\\s|^)dragging(\\s|$)');
return {
scope: {
drop: '=drop',
whenDrop: '&',
whenEnter: '&',
whenLeave: '&',
queryIndex: "=queryIndex",
hideElem: '='
},
link: function (scope, elem, attr, ctrl) {
var left = elem[0].offsetLeft,
right = left + elem[0].offsetWidth,
top = elem[0].offsetTop,
bottom = top + elem[0].offsetHeight;
elem.bind('drop', function (e) {
// e.originalEvent.preventDefault();
//if (e.stopPropagation()) {
// e.stopPropagation();
//e.originalEvent.stopPropagation();
//e.preventDefault();
//e.originalEvent.preventDefault();
//}
e.originalEvent.dataTransfer.clearData();
if (dndApi.getDropZones().indexOf(scope.drop) >= 0) {
scope.$apply(function () {
scope.whenDrop({ data: dndApi.getData(), queryI: scope.queryIndex });
});
}
if (drags.length === 0) {
drags = document.querySelectorAll('.drop');
}
angular.forEach(drags, function (value, key) {
value.className = value.className.replace(dragging, '');
});
dndApi.removeData();
e.stopPropagation();
e.originalEvent.stopPropagation();
e.preventDefault();
e.originalEvent.preventDefault();
});
elem.bind('dragenter', function (e) {
e.preventDefault();
e.originalEvent.preventDefault();
if (elem[0] == e.target) {
scope.$apply(function () {
scope.whenEnter({ data: dndApi.getData() });
});
}
return false;
});
elem.bind('dragleave', function (e) {
e.preventDefault();
e.originalEvent.preventDefault();
if ((e.x < left || e.x > right) ||
(e.y < top || e.y > bottom)) {
scope.$apply(function () {
scope.whenLeave({ data: dndApi.getData() });
});
}
return false;
});
elem.bind('dragover', function (e) {
//if (e.preventDefault) {
e.preventDefault();
e.originalEvent.preventDefault();
//}
return false;
});
elem[0].className = elem[0].className + ' drop';
scope.$watch('hideElem', function () {
if (scope.hideElem === true) {
elem.hide();
} else {
elem.show();
}
});
}
};
}).factory('dndApi', function () {
var dnd = {
dragObject: {},
dropzones: []
};
return {
setData: function (data, areas) {
dnd.dragObject = data;
dnd.dropzones = areas;
},
removeData: function () {
dnd.dragObject = null;
dnd.dropZones = [];
},
getData: function () {
return dnd.dragObject;
},
getDropZones: function () {
return dnd.dropzones;
}
};
});
I've done a lot of what's recommended on other questions. I've added event.preventDefault() to the dragenter and dragleave spots. And then when that didn't work I added them everywhere. I have a feeling it has to do with my drop method. If i put event.prevendDefault() at the beginning of the binding, the rest of my code isn't executed.
Any advice, even if it's something small that I might've overlooked, will be helpful.
Thanks!
You are calling e.originalEvent.dataTransfer.clearData(); in the drop event handler which will cause an exception to be thrown (you won't have permission to alter the original dataTransfer object). This is preventing e.originalEvent.preventDefault(); from being called.

knockout js polling not working

I am having difficulty with knockout refreshing.
Here's my viewModel;
$(document).ready(function () {
ko.applyBindings(new Task(), document.getElementById('taskSummary'));
setInterval(Task, 2000);
});
function task(name, description, project) {
var self = this;
self.name= ko.observable(name);
self.description = ko.observable(description);
self.project = ko.observable(project);
}
function Task() {
var self = this;
self.tasks = ko.observableArray([]);
self.tasks.removeAll;
$.getJSON("/api/tasks/5", function (data) {
$.each(data, function (key, val) {
self.tasks.push(new task(val.Name, val.Description, val.Project));
});
});
}
It returns data to the view but does not update when I change the data in the back end database.
any help appreciated. Im sure its something small that I'm missing.
For knockout, it might be better if you apply your model to a new Task instance, save that instance, then set up a setInterval loop that can modify the Task's "tasks" observableArray values.
$(document).ready(function () {
var oTask = new Task();
ko.applyBindings(oTask, document.getElementById('taskSummary'));
function onLoop() {
var self = oTask;
$.getJSON("/api/tasks/5", function (data) {
self.tasks.removeAll(); // not sure if you need this...
$.each(data, function (key, val) {
self.tasks.push(new task(val.Name, val.Description, val.Project));
});
});
}
setInterval(onLoop, 2000);
});

Ajax, Json, selectors that are depending on each other

Hi
I have 3 selectors, where Products depends on type and number of products depends on Products.
Type --> Products --> Number Of Products
Im loading everything from a mySQL server and extract the data with $.getJSON. So when you load the types it automaticly fills the products with names and so on.
The problem I have now is that I want the number of products to change when the product change, but if you look at the example further down, you will see that's not the case.
Initially when you load the page the third selector wont even show any options, and when you change the "type" it wont update either.
It's only when you change the productname that this will happend.
I want this to automaticly change, how do I do this?
Thanks in advance!
This is the code I'm using,
<form>
Type:
<select name="name" id="lensType">
<option selected>Endagslins</option>
<option>Dygnet-runt-lins</option>
<option>2-veckorslins</option>
<option>Manadslins</option>
</select>
Product:
<select name="productName" id="products">
</select>
Number of products:
<select name="numberOfLenses" id="numberOfLenses">
</select>
</form>
<script type="text/javascript">
function getProducts() {
$.getJSON('getProducts.php', {lensType:$('#lensType').val()}, function(data) {
var select = $('#products');
var options = select.attr('options');
$('option', select).remove();
$.each(data, function(index, array) {
options[options.length] = new Option(array['productName']);
});
});
}
$(document).ready(function() {
getProducts();
$('#lensType').change(function() {
getProducts();
});
});
function getNumberOfLenses() {
$.getJSON('getNumberOfLenses.php', {productName:$('#products').val()}, function(data) {
var select = $('#numberOfLenses');
var options = select.attr('options');
$('option', select).remove();
$.each(data, function(index, array) {
options[options.length] = new Option(array['numberOfLenses']);
});
});
}
$(document).ready(function() {
getNumberOfLenses();
$('#products').change(function() {
getNumberOfLenses();
});
});
</script>
I figured it out myself :)
I used this code
function getProducts() {
$.getJSON('getProducts.php', {lensType:$('#lensType').val()}, function(data) {
var select = $('#products');
var options = select.attr('options');
$('option', select).remove();
$.each(data, function(index, array) {
options[options.length] = new Option(array['productName']);
});
getNumberOfLenses();
});
}
function getNumberOfLenses() {
$.getJSON('getNumberOfLenses.php', {productName:$('#products').val()}, function(data) {
var select = $('#numberOfLenses');
var options = select.attr('options');
$('option', select).remove();
$.each(data, function(index, array) {
options[options.length] = new Option(array['numberOfLenses']);
});
});
}
$(document).ready(function() {
getProducts();
$('#lensType').change(function() {
getProducts();
});
$('#products').change(function() {
getNumberOfLenses();
});
});