Writing some JavaScript to update some text in a Bootstrap 3 Popover. I'm probably not using Promises right, but I want the text to appear in the popover the first time I click, not when I've clicked it twice.
The Javascript calls a local Proxy written in C#. The JavaScript for the setup of the popover itself looks like this:
$(function () {
$('#session-cookie-showcase').popover({
html: true
});
$('#session-cookie-showcase').on('show.bs.popover', function () {
Promise.resolve(getSessionCookieAsString()).then(function (value) {
$('#session-cookie-showcase').data('bs.popover').config.content = value;
})
})
})
The ajax call looks like this:
async function getSessionCookieAsString(callback) {
return $.ajax({
type: "GET",
url: AppName + '/api/omitted/hentSessionCookieSomTekst',
dataType: "json",
contentType: "application/json",
success: ((result) => function (result) { return result }),
error: ((XMLHttpRequest, textStatus, errorThrown) =>
handleWebserviceCallError(XMLHttpRequest, textStatus, errorThrown, false))
});
}
And finally the C# proxy looks like this:
[HttpGet("hentSessionCookieSomTekst")]
public string HentSessionCookieSomTekst()
{
string userKey = _configuration.GetSection("SessionKeys:User").Value;
if (!string.IsNullOrEmpty(userKey))
{
BrugerObjekt bruger = HttpContext.Session.Get<BrugerObjekt>(userKey);
return JsonConvert.SerializeObject(bruger.ToString('n'));
}
else
{
return JsonConvert.SerializeObject("NULL");
}
}
So to reiterate; The call works. But it only works on the second click of my element, never on the first. Can I somehow make the text load in whenever it is deemed ready instead of having to click again or fix this some other way?
getSessionCookieAsString function is returning a promise itself. can you try below code.
getSessionCookieAsString().done(function (value) {
$('#session-cookie-showcase').data('bs.popover').config.content = value;
});
edited it.
Related
In the below code I am making an API call to my backend node.js app using setTimeout() which calls my AJAX at every 5 seconds. Inside my AJAX success I am displaying divContent1 & divContent2 based on certain condition which should execute at least once. After that only divContent2 should be visible at each setTimeout() calls.
index.html
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "http://localhost:8070/api/route1",
type: 'POST',
dataType:'json',
success: function(res) {
//Some Task
}
});
$("#myButton").click(function(){
const route2 = function() {
$.ajax({
url: "http://localhost:8070/api/route2",
type: "POST",
dataType: "json",
data: { var1: val1 },
success: function (res) {
// Various tasks
if(res.flag){
$("#divContent1").hide();
$("#divContent2").show();
}
else{
$("#divContent1").show();
}
//Functions that handle div content data
},
beforeSend: function() {
$("#divContent1").hide();
$("#divContent2").hide();
},
complete: function() {
setTimeout(route2,5000);
},
});
};
$(function(){
route2();
})
});
});
</script>
The setTimeout() calls the entire route2 function which handles all the display and insertion of div content. However, the ask is to only display divContent2 from the second call.
Looking for a solution for this
The setTimeout() calls the entire route2 function which handles all
the display and insertion of div content. However, the ask is to only
display divContent2 from the second call.
You're calling route2 recursively with setTimeout(route2,5000); under complete. So this will run infinitely as complete occur each time an ajax call is completed (wether success or error). So what you can do is to create a timer and clear it after the second execution, something like this:
var ctr = 0, timer =0;
const route2 = function() {
$.ajax({
...
success: function (res) {
//Write you logic based on ctr
}
complete: function() {
if(ctr>0){
clearTimeout(timer)
}else{
timer = setTimeout(route2,5000);
ctr = ctr+ 1;
}
},
});
};
Will an external variable be enough? Just define it in the outer context and set/check it to choose the behavior:
// before declaring button click handler
var requestDoneAtLeastOnce = false;
// ...
// somewhere in success handler
success: function (res) {
if (!requestDoneAtLeastOnce) {
requestDoneAtLeastOnce = true;
// do something that belongs only to handling the first response
}
else {
// this is at least the second request, the other set of commands belongs here
}
}
ok, I have seen many, many articles about this. But so far I have not got any to work. So this is my take on the issue.
I have a list of employee names with ids held in a select option, and a button that when clicked, calls a routine for each option in the select
$(document).on("click", ".js-button-update-all-drivers", function (e) {
e.preventDefault();
myApplication.busy(true);
$("#modalInfo-body span").text("Starting update ...........");
$('.modalInfo-header .title').text("Information");
var modal = document.getElementById('modalInfo');
myApplication.openModal(modal);
var selected = document.getElementsByClassName('js-dropdown-selector');
for (var i = 0; i < selected[0].options.length; i++) {
var Id = selected[0].options[i].value;
$("#modalInfo-body span").text("Updating - " + Id);
doWork(Id);
}
myApplication.closeModal(modal);
myApplication.busy(false);
});
This calls a function call doWork which is defined as async/wait
async function doWork(employeeId, taxWeek, taxYear) {
try {
const response = await processUpdate(Id);
} catch (err) {
$("#modalInfo-body span").text("Report Error - Thank you.");
}
}
Which in turn calls the following function:
function processUpdate(Id) {
return new Promise((resolve, reject) => {
$.ajax({
url: '/myTest',
async: false,
data: {
Id: Id
},
method: 'post',
dataType: 'json',
success: function(retData) {
if (retData === false) {
resolve('Completed');
} else {
reject('An error has occurred, please send a screen shot');
}
},
error: function(xhr, error) {
reject('An error has occurred, please send a screen shot'); }
});
});
}
Although this code works, the element $("#modalInfo-body span") is not updated as it loops around the doWork function.
I already have a spinner on the screen, but am looking for a more visual aid to how this is progressing.
OK, I am going to start this by saying that I knew the browser is single threaded, and this was not going to be easy.
I did try callbacks and that did not work completely, as I encountered a delay in updating the screen.
So ultimately, I replaced this with a simple spinner.
Thanks to all that took the timer to look at this.
I have the following JavaScript code:
Interface.init = function()
{
$.ajax({
type: "POST",
url: "/Validate",
async: false,
success: function (data) {
if (data.Valid) {
// All good, continue executing JS code
}
else {
// Display error messsage, attempt to stop executing JS code...
return false;
}
},
error: function () {
// Display error message, attempt to stop executing JS code...
return false;
}
});
// More JavaScript functions used to load content, etc...
}
The index page calls Interface.init() on load:
<html>
<script type="text/javascript">
$(document).ready(function () {
Interface.init();
});
</script>
</html>
The ajax function is used to check if the device loading the page is valid. It is run synchronously so the page waits for the validation to complete before continuing. If the validation is successful, the ajax function is exited and the rest of the JavaScript code continues to execute. If the validation fails (or there is an error during the validation), I don't want any of the remaining JavaScript code to be executed.
I'm currently using return false, but I've also tried just return and throwing an error such as throw new Error("Validation failed") (as suggested by numerous other questions).
All these seem to do is exit the ajax function and all remaining JavaScript on the page continues to execute. Outside of the ajax function, these methods work as expected to stop the remaining code from executing, but I was hoping for this to be done from within the ajax function. Is this at all possible?
You can create an outside variable before the function and use it after it, e.g:
Interface.init = function()
{
var error = false;
$.ajax({
type: "POST",
url: "/Validate",
async: false,
success: function (data) {
if (data.Valid) {
// All good, continue executing JS code
}
else {
error = true;
}
},
error: function () {
error = true;
}
});
if (error) return;
// More JavaScript functions used to load content, etc...
}
But in fact, I recommend to not use the async=false, and instead of that, you could wrap the rest of your code in a function, and call it inside the callback, e.g:
Interface.init = function()
{
$.ajax({
type: "POST",
url: "/Validate",
success: function (data) {
if (data.Valid) {
// All good, continue executing JS code
loadAll();
}
},
error: function () {
}
});
function loadAll() {
// More JavaScript functions used to load content, etc...
}
}
I have the following JS function:
function getInfo(s,n) {
$.ajax({
type : 'POST',
url : 'includes/stock_summary.php',
timeout : 10000,
data : {
s : s
}
})
.done(function(data) {
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
alert("Unable to communicate with Yahoo! Finance servers. Please try again later.");
}
return true;
}
$.ajax({
type : 'post',
url : "includes/stock_desc.php",
data : {
s : s
}
})
.done(function(desc) {
$('#desc').html(desc);
})
if(data.change.charAt(0) == '+') {
$('#change').css('color','#090');
$('#puPrc').html('<img src="images/pu_prc_up.png"> ');
}
if(data.change.charAt(0) == '-') {
$('#change').css('color','#D90000');
$('#puPrc').html('<img src="images/pu_prc_dwn.png"> ');
}
var ask = data.ask+" <small>x "+data.askSize+"</small>";
var bid = data.bid+" <small>x "+data.bidSize+"</small>";
var change = data.change+" ("+data.changePc+")";
$('#ask').html(ask);
$('#lt').html(data.lastTrade);
$('#ytd').html(data.ytdReturn);
$('#bid').html(bid);
$('#dayHigh').html(data.dayHigh);
$('#dayLow').html(data.dayLow);
$('#prevClose').html(data.prevClose);
$('#vol').html(data.vol);
$('#yearHigh').html(data.yearHigh);
$('#yearLow').html(data.yearLow);
$('#change').html(change);
$('#stockName').html(n);
$('#sym').html(s.toUpperCase());
$('#open').html(data.sOpen);
})
.fail(function(e) {
alert("Unable to communicate with Yahoo! Finance servers. Please try again later.");
})
$('#chart').html("<img src='http://chart.finance.yahoo.com/z?s="+s+"&t=3m&q=l&l=on&z=m'>");
$('.popUp').bPopup();
}
It is called using onClick().
The function itself does the job correctly but I only want to trigger the line:
$('.popUp').bPopup();
when everything else has finished.
I have used $.ajaxStop(), $(document).ajaxStop(), $.ajaxComplete() and $(document).ajaxComplete()
I have tried them inside, outside, above and below the function but cannot seem to get it to do what I need it to!
The only time it has worked is outside the function but it then runs on page load, which I obviously don't want to happen. I only want it to run when the function completes.
If someone could help me out with this pickle, please help!
If you have just one ajax call you want to add a .always handler that will execute when all the .done and .fail handlers have completed.
.always(function() {
$('.popUp').bPopup();
});
If you have more than one ajax call on your page and you want the code to be fired once all the calls are completed then use the ajaxStop event.
$(function() {
$(document).on('ajaxStop', function() {
$('.popUp').bPopup();
});
});
Note: simplified example..
I've got a page with 1000 table rows. For each row, i need to "do some work" on the server via an AJAX call, then in the callback, update that table row saying done.
Initially i tried just firing off the 1000 ajax requests inside the .each selector, but the browser was locking up.
So i changed it to try and use an internal ajax counter, so only ever fire off 50 at a time.
Here's the code:
$('#do').click(function () {
var maxAjaxRequests = 50;
var ajaxRequests = 0;
var doneCounter = 0;
var toDo = $('#mytable tr').length;
$.each($('#mytable > tr'), function (i, v) {
while (doneCounter < toDo) {
if (ajaxRequests <= maxAjaxRequests) {
ajaxRequests++;
doAsyncStuff($(this), function () {
ajaxRequests--;
doneCounter++;
});
} else {
setTimeout(function() {
}, 1000);
}
}
});
});
function doAsyncStuff(tr, completeCallback) {
$.ajax({
url: '/somewhere',
type: 'POST',
dataType: 'json',
data: null,
contentType: 'application/json; charset=utf-8',
complete: function () {
completeCallback();
},
success: function (json) {
// update ui.
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
// update ui.
}
});
}
But the browser is still being locked up. It never goes into the $.ajax complete callback, even though i can see the request coming back successfully (via Fiddler). Therefore its just sleeping, looping, sleeping, etc because the callback is never returned.
I've got a feeling that the entire doAsyncStuff function needs to be asynchronous?
Any ideas on what i am doing wrong (or how i can do this better)?
You are doing a while loop inside the .each callback function, so there is much more ajax request than 1000, the worst is 1000*1000.
You could delay each ajax request with different time.
$('#do').click(function () {
$('#mytable > tr').each(function (i, v) {
var $this = $(this);
setTimeout(function () {
doAsyncStuff($this, function () {
console.log('complete!');
});
}, i * 10);
});
});
The browser gets locked because of the WHILE... You are creating an endless loop.
The while loops runs over and over waiting for the doneCounter to be increased, but the javascript engine cannot execute the success call of the ajax since it is stuck in the while...
var callQueue = new Array();
$('#mytable > tr').each(function(key,elem){callQueue.push($(this));});
var asyncPageLoad = function(){
var tr = callQueue.splice(0,1);
$.ajax({
url: '/somewhere',
type: 'POST',
dataType: 'json',
data: null,
contentType: 'application/json; charset=utf-8',
complete: function () {
completeCallback();
asyncPageLoad();
},
success: function (json) {
// update ui.
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
// update ui.
}
}
};
asyncPageLoad();
This will call the requests one by one. If you want, simply do a for() loop inside to make maybe 5 calls? And increase the amount if the browser is fine.
Actually, I prefer to send new request when current request is done. I used this method to dump db tables (in this work). Maybe it gives an idea.
See this link, check all check boxes and click Dump! button. And you can find the source codes here (see dumpAll function).