Block ui when Loading Page - javascript

i want to block my ui until values in my drop down not loaded
my js file code is as follows
$(document).ready(function() {
// Load All Toll Plazas
FillInCascadeDropdown({ userType: -1 }, "#ddlTollPlazas", "/Home/GetTollPlazas/" + -1);
}
function FillInCascadeDropdown(map, dropdown, action) {
$(dropdown).empty();
$.blockUI({ message: '<img src="/Content/images/ajax-loader.gif"/>' });
$.post(action, map, function(data) {
$.each(data, function() {
$(dropdown).append("<option value=" + this.Value + ">" + this.Text + "</option>");
});
}, "json");
$.unblockUI();
}
above code not working on page load.

I think you're problem is you are unblocking as soon as you call blockUI. You need to move the unblock call to a "Success" callback function. The concept of Callbacks are a little tricky. Basically this is the code that runs once the post is successful. I'm sure you've seen this page but refer to the jQuery post page to see where you need to put your callback and here to learn more about callbacks if you need to. Good luck!
Here is how it should look:
function FillInCascadeDropdown(map, dropdown, action) {
$(dropdown).empty();
$.blockUI({ message: '<img src="/Content/images/ajax-loader.gif"/>' });
$.post(action, map, function(data) {
$.each(data, function() {
$(dropdown).append("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$.unblockUI();
}, "json");

Related

not firing event in jquery

I have a list that page load, loads items. and when click checkbox in page load items with json.
$('.content-items:checkbox').on('change',
function () {
$.get(newUrl, function (data) {
$("#ProductsPartialView").empty();
$("#ProductsPartialView").append(data);
$('#loadingModal').modal('hide');
}).fail(function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
});
});
when click items element run a function.
$('.compare-items:checkbox').on('change',
function() {
$('#loadingModal').modal('show');
var value = $(this).data('id');
$.getJSON("/store/AddToCompare", {
id: value, add: true
}, function (result) {
$(".compare-footer").show();
$(".compare-count").html(result);
$('#loadingModal').modal('hide');
});
}
});
when load items in page load, fire this jquery, but when load items with json in first code, don't fire second function.
for that you need $(document).on(event,selector, cb{}); when you want to do action on dynamic generated data
$(document).on('change','.compare-items:checkbox',
function() {...

How to set interval for get data from API (jQuery)

I have a simple question: I am using this function for getting prices from CryptoCompare and now I would like set interval for refreshing data without refreshing page. So I have tried this code:
<script>
getData('dash', 'https://min-api.cryptocompare.com/data/price?fsym=DASH&tsyms=USD');
function getData(prefix, url) {
$.getJSON(url, function(data) {
$.each(data, function(key, val) {
$('.' + prefix + '-' + key.toLowerCase()).html(val);
});
});
}
setInterval(getData, 3000);
$(function() {
getData();
});
</script>
But it is not working for me. Can you help me, please?
Edit:
Used on website https://investplus.cz/
You have some convoluted code. I think what you are intending is for your fetch to be called every 3 seconds.
function getData(prefix, url) {
$.getJSON(url, function(data) {
$.each(data, function(key, val) {
$('.' + prefix + '-' + key.toLowerCase()).html(val);
});
});
}
This defines you get function. You have a sample call as
getData('dash', 'https://min-api.cryptocompare.com/data/price?fsym=DASH&tsyms=USD');
You are using setInterval incorrectly though, see https://www.w3schools.com/jsref/met_win_setinterval.asp
You have 2 lines here
setInterval(getData, 3000);
$(function() { getData(); });
This is incorrect, getData is only a name for your function. The setInterval function should take your anonymous function with defined parameters like
setInterval($(function() {
getData('dash', 'https://min-api.cryptocompare.com/data/price?fsym=DASH&tsyms=USD');
}), 3000);
Per your JS fiddle, this works for me (removed jquery function and replaced with regular js lambda)
function getData(prefix, url) {
$.getJSON(url, function(data) {
$.each(data, function(key, val) {
$('.' + prefix + '-' + key.toLowerCase()).html(val);
});
});
}
setInterval(function() {
getData('btc', 'https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD');
}, 3000);

Making async jquery calls

$(document).ready(function(){
$.getJSON("https://api.deckbrew.com/mtg/sets", function(sets) {
$(sets).each(function() {
$('<div id="' + this.name + '" class="set"/>')
.text(this.name)
.appendTo("#collection");
});
});
$.getJSON("https://api.deckbrew.com/mtg/cards", function(cards) {
$(cards).each(function(){
$('<div id="' + this.name + '" class="card"/>')
.text(this.name)
.appendTo("#" + this.editions[0].set);
});
});
});
I was wondering how I might (without using ajax and sticking to the "getJSON" method) make the two calls happen asynchronously. I can't make anything useful happen with the second jQuery object; I believe that's because of the synchronous nature of the calls. How can I make them work in order?
If you want these to happen in order, then you need to specifically serialize them and using the built-in promises that getJSON() returns is a simple way to do that:
$(document).ready(function () {
$.getJSON("https://api.deckbrew.com/mtg/sets").then(function (sets) {
$(sets).each(function () {
$('<div id="' + this.name + '" class="set"/>')
.text(this.name)
.appendTo("#collection");
});
}).then(function () {
$.getJSON("https://api.deckbrew.com/mtg/cards").then(function (cards) {
$(cards).each(function () {
$('<div id="' + this.name + '" class="card"/>')
.text(this.name)
.appendTo("#" + this.editions[0].set);
});
});
});
});
Or, a little faster (end to end time) would be to launch both requests at the same time and then process the results in order. Again using jQuery promises to manage this:
$(document).ready(function(){
$.when(
$.getJSON("https://api.deckbrew.com/mtg/sets"),
$.getJSON("https://api.deckbrew.com/mtg/cards")
).then(function(r1, r2) {
// process sets
var sets = r1[0];
$(sets).each(function() {
$('<div id="' + this.name + '" class="set"/>')
.text(this.name)
.appendTo("#collection");
});
// process cards
var cards = r2[0];
$(cards).each(function(){
$('<div id="' + this.name + '" class="card"/>')
.text(this.name)
.appendTo("#" + this.editions[0].set);
});
});
});
This last scheme uses $.when() to tell us when both ajax calls are done and it also sequences the results for us, regardless of which one actually finished first.
To run the getJSONS's in sequence, run the second in the callback of the first
like so
$(document).ready(function() {
$.getJSON("https://api.deckbrew.com/mtg/sets", function(sets) {
$(sets).each(function() {
$('<div id="' + this.name + '" class="set"/>')
.text(this.name)
.appendTo("#collection");
});
$.getJSON("https://api.deckbrew.com/mtg/cards", function(cards) {
$(cards).each(function() {
$('<div id="' + this.name + '" class="card"/>')
.text(this.name)
.appendTo("#" + this.editions[0].set);
});
});
});
});
personally, I would go with #jfriend00's promise method - I was going to add that to this answer, but he answered in the meantime, so, go with that more flexible method
EDIT
Since you said you were trying to use call both getJSON methods in order, then you can make the second call work after the first by using the DOMNodeInserted event
Well maybe a solution would be to use DOMNodeInserted event since you are appending to #collection
so:
$("#collection").on('DOMNodeInserted',function(){
$.getJSON...
});
According to DOCS
DOMNodeInserted
Fired when a node has been added as a child of another node. This
event is dispatched after the insertion has taken place. The target of
this event is the node being inserted.

Elements created by getJSON don't react to the rest of the javascript loaded on the page

I am using getJSON to access Vimeo's Simple API, and any objects created on the page by the call, do not react to the rest of the javascript that is on the page. It is probably something simple that I am missing. Here is my getJSON code:
$.getJSON("http://vimeo.com/api/v2/album/1822727/videos.json", function(data){
$.each(data, function (index, value) {
var videoID = value.id;
var videoThm = value.thumbnail_large;
$('#galThms').prepend('<li id="thm' + videoID + '" style="background-image:url(' + videoThm + ');"></li>');
console.log(videoThm);
});
});
Here you go: http://jsfiddle.net/8t3Xq/1/
This demonstrates loading your <li> thumbs just as your question does, then I show how to easily change one of them. How to "change" them is endless, this is just a simple example of changing the content and background. So you must not have your selectors right.
This is just a snippet, see fiddle for everything...
$.getJSON("http://vimeo.com/api/v2/album/1822727/videos.json", function(data){
$.each(data, function (index, value) {
var videoID = value.id;
var videoThm = value.thumbnail_large;
$('#galThms').prepend('<li id="thm' + videoID + '" style="background-image:url(' + videoThm + ');"></li>');
console.log(videoThm);
});
});
window.changeIt=function()
{
$('li').first().html("I'm changed!");
$('li').first().css("background-image","");
}
Just make sure the <li>s are present first before your code that changes them is present. Would need to see more of you code to understand when/how that happens.
$.getJSON("http://vimeo.com/api/v2/album/1822727/videos.json", function(data){
$.each(data, function (index, value) {
var videoID = value.id;
var videoThm = value.thumbnail_large;
$('#galThms').append('<li id="thm' + videoID + '" style="background-image:url(' + videoThm + ');"></li>');
console.log(videoThm);
$( "#galThms li" ).click(function() {
$(this).hide();
});
});
});
try this
there is no way that my answer is so far removed from the problem statement. my guess is that either I somehow errantly posted this answer or the problem was edited. apologies
you could also use:
$(document).on('click','li .playVideo',function(){
//do something
});
i would probably change your #playVideo to a class, if you will have multiple li's

Problems on .append() and .empty()

i have the following code that, if the #test button is click, a content will be generated in #currentActivities. There is another #hide button which simple hide the content of #currentActivities. My problem is if the first time i click #test, i can get the content. When i click #hide, the content of #currentActivities can be hidden as expected. However, if i click #test again, the content cannot be generated. I have tried to add $('#currentActivities').empty(); at the beginning, but seems not work. Can anyone help me and point out my problems?
$("#test").click(function() {
$('#currentActivities').empty();
$.ajax({
type: "GET",
dataType: "jsonp",
jsonpCallback: "jsoncallback",
data: {
//some data here
},
url: "http://mydomain.com/check.php?jsoncallback=?",
success: function(data) {
$.each(data, function(index, student) {
$('#currentActivities').append(
'<li><a href="tutor_student_detail.html" data-name="' + data[index].data.NameA + '">' +
'<h4>' + data[index].data.NameA + '</h4>' +
'<p>' + data[index].data.NameA + '</p>' +
'</a></li>');
$("li a").click(function() {
window.localStorage["view"] = $(this).data('name');
window.localStorage["Request"] = "true";
}); //end of li a
});
$('#load2').hide();
$('#filter').show();
$('#currentActivities').listview('refresh');
},
error: function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
});
return false;
});
You need to use delegate event (aka live event). Cause you're working with a dynamically loaded DOM elements.
Something like:
$('body').on('click', '#test', function() {
// all code belong to click handler
});
For more on delegate event binding using .on() see here.
NOTE:
Instead of body user any static-container of all those newly loaded and appended element.
As your question is on jquery mobile so I think for live evnet delegation you can try something like:
$('#test').live('click', function() {
// all codes belong to click hander
});
and another way is :
$(document).delegate('#test', 'click', function() {
// codes
});

Categories

Resources