I am trying to fake synchronous JavaScript while doing an AJAX request.
I have an getPagePath(id) function that needs to get the page path of an page by giving it an page ID, it receives the data trough an web API. I thought this was going to be simple, just do an ajax request to the server and receive the page path. But what is happening: when requesting the page path my code keeps running and returns an empty var, after that the ajax call finishes, but to late.
I know my explaining is not much saying so here is my code:
var getPagePath = function() {
// Function to check if this.pagePath is set.
var pagePathReady = function() {
console.log('PAGEPATH: CHECKING');
if (this.pagePath && this.pagePath != null) {
return true;
} else {
return false;
}
};
if (!pagePathReady()) {
// No pagePath defined so lets set it.
this._setPagePath();
while (!pagePathReady())
{
// Not yet defined, check again..
// *** The problem ***
// This while loop is running insanely fast making the browser crash.
// How can I make this wile loop pause for 1 sec?
// *******************
console.log('PAGEPATH: NOT READY -> CHECK AGAIN');
}
// READY
console.log('PAGEPATH: READY -> VALUE: ' + this.pagePath);
return this.pagePath;
} else {
return this.pagePath;
}
};
var _setPagePath = function() {
if (!this.pagePathRequestFired) {
this.pagePathRequestFired = true;
// Fire request.
system.url(
this.getNodeId(),
function(url) {
// Request ready, set pagePath.
this.pagePath = url;
this.pagePathRequestFired = false;
},
this
);
} else {
// Call already running..
}
};
I have set the problem in the more explaining comments.
Thanks in advance!
You can make an ajax call synchronous if you really need to.
xmlhttp.open("GET", "url", false);
Note the 3rd param.
But, I think you just need more practice in writing your code to work with the event/callback concept.
Instead of polling the pagePath (which doesn't seem to be required IMHO) why not just execute a callback when the _setPagePath is ready? If you want to fake a synchronous request, you can just display a loading spinner to the user as an overlay, disabling the UI.
Related
I'm working on a web application project with Flask+Python on the back-end, and Javascript on the front-end. I'd like to take advantage of some of the more modern (ES6/7) styles of things, such as Promises.
I've currently been writing all my javascript using Jquery 3+. Most of the time I'm making single Ajax requests to the server at a time. I've been specifically writing my Ajax requests using $.post and .done() and .fail(), which I know is already promise-based, or promise-like. Most of my code is in the style of
do function setup stuff and checks
make single ajax request
on success
good status, run several success code bits
bad status, run failure code
on failure - run failure code
I always seem to have to account for cases of server failures + cases of server success but it returned the wrong thing, which I usually control with a status argument. I've been looking into the straight Promise syntax with then, catch, resolve, reject, and I have some questions.
Is there any advantage to me switching to this format, from what I currently have, given my simple Ajax requests?
Can it be used to simplify the way I currently write my requests and handle my failure cases?
Here is a simple login example that I have, with a function that is called when a login button is clicked.
$('#loginsubmit').on('click', this, this.login);
// Login function
login() {
const form = $('#loginform').serialize();
$.post(Flask.url_for('index_page.login'), form, 'json')
.done((data)=>{
if (data.result.status < 0) {
// bad submit
this.resetLogin();
} else {
// good submit
if (data.result.message !== ''){
const stat = (data.result.status === 0) ? 'danger' : 'success';
const htmlstr = `<div class='alert alert-${stat}' role='alert'><h4>${data.result.message}</h4></div>`;
$('#loginmessage').html(htmlstr);
}
if (data.result.status === 1){
location.reload(true);
}
}
})
.fail((data)=>{ alert('Bad login attempt'); });
}
And a typical more complex example that I have. In this case, some interactive elements are initialized when a button is toggled on and off.
this.togglediv.on('change', this, this.initDynamic);
// Initialize the Dynamic Interaction upon toggle - makes loading an AJAX request
initDynamic(event) {
let _this = event.data;
if (!_this.togglediv.prop('checked')){
// Turning Off
_this.toggleOff();
} else {
// Turning On
_this.toggleOn();
// check for empty divs
let specempty = _this.graphdiv.is(':empty');
let imageempty = _this.imagediv.is(':empty');
let mapempty = _this.mapdiv.is(':empty');
// send the request if the dynamic divs are empty
if (imageempty) {
// make the form
let keys = ['plateifu', 'toggleon'];
let form = m.utils.buildForm(keys, _this.plateifu, _this.toggleon);
_this.toggleload.show();
$.post(Flask.url_for('galaxy_page.initdynamic'), form, 'json')
.done(function(data) {
let image = data.result.image;
let spaxel = data.result.spectra;
let spectitle = data.result.specmsg;
let maps = data.result.maps;
let mapmsg = data.result.mapmsg;
// Load the Image
_this.initOpenLayers(image);
_this.toggleload.hide();
// Try to load the spaxel
if (data.result.specstatus !== -1) {
_this.loadSpaxel(spaxel, spectitle);
} else {
_this.updateSpecMsg(`Error: ${spectitle}`, data.result.specstatus);
}
// Try to load the Maps
if (data.result.mapstatus !== -1) {
_this.initHeatmap(maps);
} else {
_this.updateMapMsg(`Error: ${mapmsg}`, data.result.mapstatus);
}
})
.fail(function(data) {
_this.updateSpecMsg(`Error: ${data.result.specmsg}`, data.result.specstatus);
_this.updateMapMsg(`Error: ${data.result.mapmsg}`, data.result.mapstatus);
_this.toggleload.hide();
});
}
}
}
I know this is already roughly using promises, but can I make improvements to my code flow by switching to the Promise then catch syntax? As you can see, I end up repeating a lot of the failure case code for real failures and successful failures. Most of my code looks like this, but I've been having a bit of trouble trying to convert these into something that's like
promise_ajax_call
.then(do real success)
.catch(all failure cases)
I always use Bluebird Promises. They have a Promise.resolve function that you can utilize with ajax. One thing to know about Promises, if you throw an error in a then, it will be caught in a chained catch. One way to clean this up a bit might be something like this (keep in mind, this is pseudo)
Promise.resolve($.ajax(...some properties..))
.then((data)=>{
if(data.result.status < 0){
//throw some error
}
// process the data how you need it
})
.catch((error){
// either the ajax failed, or you threw an error in your then. either way, it will end up in this catch
});
I have a page that should load after the initial page load a bit of data trough AJAX that is then used in a few functions.
So far I can only get it to work with loading the AJAX requests separately (which means the same request is called like 30 times)
What I need is the possibility to have a function that can be called multiple times, but only activates the AJAX call once and the other times gives the data back without having again the same AJAX call that already gave the data back running (cause that's redundant and not needed, the data doesn't change).
Now I could do that by simply making a call and store it in a global variable and just check if something is in this variable or not...
BUT! The "but" is the problem, that these around 20 calls that need the information the AJAX delivers happen right after the DOM is loaded, right together with the AJAX call.
And so I cannot do that, because the 20 requests happen before the first AJAX call even finished showing all data.
I tried to do some stuff with JQueries "deferred", but could only manage to do it with one call and not with multiple calls at almost the same time without that it triggers the AJAX call everytime.
But I'm sure that must be possible somehow! Nicely, without some sort of loops and timeout. I really like the idea of loading pages and parts of pages partially. Input field isn't loaded right from the start, but gets delivered as soon as it is ready, etc...
Is it? I really can't wrap my head around this one...
$(function(){
loadme1();
loadme2(); /* loaded from complete different parts in the code, so not possible to start loadme2 only after loadme1 has everything finished */
});
function getData(){
return $.get("/pathtogetthedata", {}, function(data){
});
}
function loadme1(){
getData().done(function(data){
var obj = $.parseJSON(data);
/* do something with obj */
}
}
function loadme2(){
getData().done(function(data){ //please just wait till the first call to the same method finished and give me that data or wait till it's in a global variable and I take it from there. Only make a call if there is no jquery "promise" waiting
var obj = $.parseJSON(data);
/* do something with obj */
}
}
You have to keep all the "callback" and then when the data ready, to call the callback you just saved for example:
var funcs = []
function exampleOfAjaxGetData(callback) {
funcs.push(callback)
if (funcs.length == 1) {
setTimeout(function() {
alert('This is need to be called once1')
while (funcs.length > 0)
funcs.pop()('The data return from ajax')
}, 2000)
}
}
exampleOfAjaxGetData(function(x) {
alert('I got the data:' + x)
})
exampleOfAjaxGetData(function(x) {
alert('I got the data:' + x)
})
jsFiddle: http://jsfiddle.net/yn5ayw30/
In the example I show you a function that takes 2 seconds to complete.
I called the function twice. But the "setTimeout" run only once. When setTimeout complete, it will run all the function that wait for answer.
var getDataCalled = false;
var deferred = $.Deferred();
function getData(){
if(!getDataCalled) {
getDataCalled = true;
return $.get("/", {} , function(data) {
deferred.resolve(data);
});
} else {
console.log("returning deferred");
return deferred;
}
}
How about you save when you first call your "getData" function. When it has already been called you return your own "deferred" object back and resolve it when your first ajax request is finished.
I hope this short code snippet speaks for itself and is easy to understand.
Calling getData() will now first make the ajax request and after that always return a deferred object you created yourself.
getData().done(function(data) {
console.log(data);
});
getData().done(function(data) {
console.log(data);
});
getData().done(function(data) {
console.log(data);
});
You will see there will only be one ajax request.
I can think of one solution here it is :
var adata = -1; // global variable data holder
function getdata()
{
//if ajaxx call is already done and completed then return data
if(adata != -1 && adata != -2)return adata;
if(adata == -1)
{
//function getting called first time
adata = -2; // now we change value of adata to -2
// we will use this -2 to check if ajaxx call is stil running
//do ajaxx $.get call
$.get( "url_goes_here", function( data ) {
adata = data;// assingh received data to adata, so -2 is changed now
});
//now code will move to while loop part even after first call as while loop part doesn't have condition
//thus waiting for ajaxx call to be completed even if its first call
}
while(adata == -2){
//just a loop to delay output until call finishes
}
return adata;
}
Now you can use getdata() function to achieve what you want
I'm just wondering if something like this is possible in Javascript.
var Module = function(){
var _ajaxLoaded = false;
var _property = null;
return {
init : function(){
// starting ajax request here
$.getJSON('requesturl', function(data) {
_property = data.property;
_ajaxLoaded = true;
});
},
property : function(){
if(_ajaxLoaded){
return _property;
}
// stop processing here and wait till ajax request is finished
// loop till ajax is finished
return this.property();
}
}
}();
Module.init();
alert(Module.property());
I know that it is possible to have a callback in the init function and wait for that. But this example would allow me to just ask for the property without knowing if it is even there.
-- EDIT --
I'm pretty sure I just should use a callback in the init function. It simply a better coding structure. But I really wonder if it is even possible to do, if I had no other possibility.
I added following line:
// loop till ajax is finished
return this.property();
Could this somehow work or would I end up in an endless loop because Javascript doesn't even have time to process the ajax call(single threading?)? Haven't tested it yet.
No doubt, it is bad coding and I wouldn't use it, but I'm just curious.
Is there a definitive JavaScript method for checking whether or not a web page has loaded completely? Completely, meaning 100% complete. HTML, scripts, CSS, images, plugins, AJAX, everything!
As user interaction can effect AJAX, let's assume there is no further user interaction with the page, apart from the initial page request.
What you're asking for is pretty much impossible. There is no way to determine whether everything has loaded completely. Here's why:
On a lot of webpages, AJAX only starts once the onload (or DOMReady) event fires, making the method of using the onload event to see if the page has loaded impossible.
You could theoretically tell if the webpage was performing an AJAX request by overriding window.XMLHttpRequest, but you still couldn't tell if plugins like Flash were still loading or not.
On some sites, like Twitter.com, the page only loads once and simply makes AJAX requests to the server every time the user clicks a link. How do you tell if the page has finished loading on a page like that?
In fact, the browser itself can't be completely certain whether the page has completely finished loading, or whether it's about to make more AJAX requests.
The only way to know for sure that everything loaded is to have every single piece of code on the page that loads something tell your code that it has finished once it loads.
A hacky, incomplete solution: You could try overriding XMLHttpRequest with a function that wraps the existing XMLHttpRequest and returns it. That would allow you to tell if a AJAX event is currently taking place. However, that solution wouldn't work for seeing if plugins are loaded, and you wouldn't be able to tell the difference between AJAX events that are triggered at page load and AJAX requests that happen periodically, like the ones on Stack Overflow that change the Stack Exchange icon on the top-left if you have new notifications.
Try something like this:
(function(oldHttpRequest){
// This isn't cross-browser, just a demonstration
// of replacing XMLHttpRequest
// Keep track of requests
var requests_running = 0;
// Override XMLHttpRequest's constructor
window.XMLHttpRequest = function() {
// Create an XMLHttpRequest
var request = new oldHttpRequest();
// Override the send method
var old_send = request.send;
request.send = function () {
requests_running += 1;
old_send.apply(request, arguments);
};
// Wait for it to load
req.addEventListener("load", function() {
requests_running -= 1;
}, false);
// Return our modified XMLHttpRequest
return request;
};
window.addEventListener("load", function() {
// Check every 50 ms to see if no requests are running
setTimeout(function checkLoad() {
if(requests_running === 0)
{
// Load is probably complete
}
else
setTimeout(checkLoad, 50);
}, 50);
}, false);
})(window.XMLHttpRequest)
The:
window.onload
event will fire at this point.
window.onLoad = function(){
//Stuff to do when page has loaded.
}
or
<body onLoad="functionCall()">
Basically ADW and Keith answer the question, but I would suggest not to use window.onload but:
if (window.addEventListener) {
window.addEventListener("load", myfunction, false);
} else {
window.attachEvent("onload", myfunction);
}
function myfunction() {
...
}
Using a combination of window.onload, document.readyState, and callbacks for AJAX requests, you should be able to do what you want. Simply make sure the window has loaded, the DOM is ready for manipulation, and keep track of AJAX requests.
For AJAX in particular, depending on how many requests you make: Increment a variable each time you make a request, and when the variable === the total amount of requests, fire a function. If you don't happen to know the amount of AJAX requests, but know which one would be last, simply have a callback function fire when it finishes.
When all is set and true, fire a final function to do what you want, knowing everything should be loaded.
In regards to Flash and Silverlight applications (not sure if window.onload or document.ready keeps track of those), you could also record the amount of data loaded withing the application, and when the loaded data === the total data, have the application fire a function or increment a variable to the page.
window.onload = function() {
var time = window.setInterval(function() {
if(document.readyState == "interactive") {
increment();
window.clearInterval(time);
}
}, 250);
}
var total = 10, current = 0;
var increment = function() {
current += 1;
if(current === total) { weAreDone(); }
}
function weAreDone() {
// Everything should be done!
}
Here is the non intrusive js function I scripted, using events on load. In this case, I fire events on js script load as this is my js autoloader function, but you can just add event on other items using the same principle. Provided this script looks after js scripts loaded in a dedicated div tag.
function scriptLoaded(e) {
var oLoadedScript = e.target || e.srcElement;
alert ('loaded : ' + oLoadedScript.src);
return false;
}
/**
* Import js lib and fire function ControlData on events
* #param js_librairies
* #returns {Boolean}
*/
function init(){
// lib import
// Locate js in the div
var myscript_location = document.getElementById('js_script_goes_here');
// DEBUG
if (undefined == myscript_location)
alert('div not found');
else
alert('found div : ' + myscript_location);
// to prevent js script from catching in dev mode
var force_js_reload = "?version=1" ;
for (var i=0; i < js_librairies.length ; ++i) {
var my_script = document.createElement('script');
my_script.defer = false;
my_script.src = relative_path + js_librairies[i] + force_js_reload ;
my_script.type = 'text/javascript';
// DEBUG
my_script.onload = scriptLoaded;
myscript_location.appendChild(my_script);
}
return false;
}
/**
* Start non intrusive js
* #param func
*/
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
};
}
}
//ONLOAD
addLoadEvent(init);
function r(f){/in/(document.readyState)?setTimeout(r,9,f):f()}
Courtesy: Smallest DOMReady code, ever - Dustin Diaz
Update: And for IE
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
P.S: window.onload is a very different thing
I have a simple Javascript function:
makeRequest();
It does a bunch of stuff and places a bunch of content into the DOM.
I make a few calls like so:
makeRequest('food');
makeRequest('shopping');
However, they both fire so quickly that they are stepping on each other's toes. Ultimately I need it to have the functionality of.
makeRequest('food');
wait....
makeRequest('shopping'); only if makeRequest('food') has finished
Thoughts on getting these to execute only one at a time?
Thanks!
If these functions actually do an AJAX request, you are better keeping them asynchronous. You can make a synchronous AJAX request but it will stop the browser from responding and lead to bad user experience.
If what you require if that these AJAX requests are made one after the other because they depend on each other, you should investigate your function to see if it provides a callback mechanism.
makeRequest('food', function()
{
// called when food request is done
makeRequest('shopping');
});
Using jQuery, it looks something like that
$.get("/food", function(food)
{
// do something with food
$.get("/shopping", function(shopping)
{
// do something with shopping
});
});
I would recommend that you simply write them asynchronously--for example, call makeRequest('shopping'); from the AJAX completion handler of the first call.
If you do not want to write your code asynchronously, see Javascript Strands
I suppose that you have a callback method that takes care of the response for the request? Once it has done that, let it make the next request.
Declare an array for the queue, and a flag to keep track of the status:
var queue = [], requestRunning = false;
In the makeRequest method:
if (requestRunning) {
queue.push(requestParameter);
} else {
requestRunning = true;
// do the request
}
In the callback method, after taking care of the response:
if (queue.length > 0) {
var requestParameter = queue.splice(0,1)[0];
// do the request
} else {
requestRunning = false;
}