jquery ready function not executing - javascript

I have some javascript placed inside of the jquery $(document).ready function. It searches for an anchor in the url, and then runs a separate function to display matching content.
The code executes if I place an alert inside of the if statement somewhere, but wont' run otherwise. I've stored all the anchor names in an array called 'anchorNameList', and am checking to see if the anchor in the URL exists.
I only want the function to run on the initial pageload, so I set the default value of 'currentAnchor' to 1000 and change it on each iteration.
if (currentAnchor == 1000 && document.location.hash.substring(1)) {
var checkForThisAnchor = document.location.hash.substring(1);
for (var j=0; j < anchorNameList.length; j++) {
if (anchorNameList[j] == checkForThisAnchor) {
expandMe(j);
}
}
}

In my experience, when a JavaScript problem magically fixes itself by adding an innocuous alert() somewhere, the source of the problem is typically an asynchronous request.
Under non-alert circumstances the async request hasn't finished yet. But by adding the alert, it has a chance to finish, and therefore allowing your code to travel a different code-path than it would have hit without the response of the complete asynchronous call.

I switched the onload event from jQuery's document.ready to window.ready. It worked properly about 30% of the time, so it was definitely a timing issue. It seemed the main JavaScript function on the page, which is retrieving list items, was running slowly. I just moved this entire expanding function to the end of that list retrieval function, so it just runs linearly.

Related

Behavior of jQuery's append inside a for loop

I'm confused about the behavior of jQuery's .append() method in a for loop.
This code attaches and displays the file names on the div element. It works fine, but I'm reading the code, and I'm in the understanding that the file name gets appended in sequence/one after the other as it loops. But it appears like they get displayed together once the loop finishes. I also tried to intercept it with an alert to check.
Why does it happen this way?
$("#fileInput").on("change", function() {
$(".input-feedback").html('');
for(var i = 0; i < this.files.length; i++) {
var file = this.files[i];
console.log(file.name);
alert('test');
$(".input-feedback").append("<p>"+ file.name +"</p>");
}
});
Files are added one at a time but...
Usually browsers wait until js code run is completelly finished and js is idle waiting for events in order to perform the dom rendering (it depends on browser, the type of event which you are running from and on DOM changes applied).
If you want to see how each item is added for sure, then best way is run code asyncronously with setTimeout or setInterval.

Javascript skips piece of code but works fine when done with debugger

I have a really simple line of code. I have a tabstrip provided by Kendo library
i = 0;
x = 10;
while (i < x) {
var tabStrip = $("#myId").data("kendoTabStrip");
tabStrip.select(i);
i++;
}
When I go step by step using debugger everything is ok - tabStrip.select(i) method is being invoked and works perfectly. But when I run it without debugger it just behaves like there was no this line. I do not understand why, and I don't know how to solve this.
(i and x variables are just sample variables, maybe the information that the method is invoked inside the while loop is important)
var tabGroupObject = $("<div>").attr("id", "myId")
tabGroupObject = $(tabGroupObject).kendoTabStrip({
animation: {
open: {
effects: "fadeIn"
}
}
});
var tabStrip = tabGroupObject.data("kendoTabStrip");
Seems to be a synchronization issue, very common in JavaScript when dealing with Ajax calls or DOM modifications. That's why it works when you execute the code step by step giving enough time for the actions to happen.
My recommendation would be to read a little about Async JavaScript and try to implement a callback function that triggers once the animation finish its task.
Assumption:- I'm assuming you are looking for an ajax trigger event which gets fired in the browser in response to the select of the tabScript.
Solution:- If that's the case please know that browsers combines all the ajax events on an element within a set amount of time into one event to reduce the number of unwanted post calls, what you can do is try adding a delay if you want these events to be called else it would simply trigger the even which gets called on the tabSctrip.select(9) as mentioned by dfsq.

How to make infinite calls for a div reload through Ajax synchronously

I'm kind of new to javascript and seriously, this async thing is driving me crazy.
I'm working on a project for displaying a div (which occupies all the screen) that reloads everytime with a different content and stays on screen for an X amount of time.
For example, I already created some static screens objects inside an array like this:
screenArray[0] = {ID:"987234", Name:"SampleScreen", Time:6000};
screenArray[1] = {ID:"837625", Name:"SampleScreen2", Time:10000};
So this is pretty much what I wanted to do if javascript worked synchronously:
function ScreenEngine(){
reloadScreenContent();// "loads" the first screen (this is just an Ajax div reload function)
for (var i = 0; i == screenArray.length+1; i++){
if (i == screenArray.length){ //when it gets to the latest screen, it goes to the first one
i = 0;
}
setTimeout(reloadScreenContent, screenArray[i].Time); // loads the second screen with the timeout of the first one (i=0)
}
}
(I'm just working on the timey wimey thingy, I'll deal with the content later.)
Saw some other posts about callback functions so javascript would work "synchronously" for the things I want and I even tried some of it and failed miserably doing it.
Even not understanding with details how I would make a callback function, I understand that (at least the way I "tried") it would stack forever because I'm asking javascript to do an infinite job.
I need a brainstorm how to solve this problem, maybe some tips using callback or a similar sample code so I can guide myself.
I think what you need to do is call the reload function inside the callback function itself.
If you're using jQuery for the ajax function, the code could look something like this:
function loadContent(){
$.getJSON("yourURL", callback)
}
function callback(data){
/*do something with the data*/
/*call loadContent at an interval */
window.setTimeout(loadContent, 2000 );
}
loadContent();
This was loadContent will get called 2s after the content has been loaded. Here's an example of a recursive ajax call, you can see in the console it's making the ajax call every 10s http://jsfiddle.net/w66peL7b/1/

Web-sql event not completed when combined with either form-submit or window.location

Heyo,
Basic workflow:
Form submit button is clicked
Submit event is captured
Capture function runs a callback script
If the script returns false e.preventDefault() is called
ELSE Form submits
The above is all working fine. I have just provided it for context. The issue I am having is that as part of the callback script, a series of SQL UPDATE events are fired off. The script for this is below:
function writeNewProductDetails() {
for(var i = 0; i < $('#productForm').children('input').length; i++) {
var input = $('#productForm').children('input')[i];
var inputType = $(input).attr('id').split('---');
var inputVal = $(input).val();
switch(inputType[1]) {
case 'quantity' :
localDB.webdb.runSQL('UPDATE orderLines SET "collected" = "'+inputVal+'" WHERE orderLineID = '+inputType[0])
break;
case 'code' :
localDB.webdb.runSQL('UPDATE orderLines SET "code" = "'+inputVal+'" WHERE orderLineID = '+inputType[0])
break;
}
}
window.location(history(-1));
return false;
}
Now a lot of this code is irrelevant to the question, the key part is the switch statement and the following two lines. The window.location and return false commands are used to avoid actually submitting the form (as the processing is already done).
Here is the crux of the issue. If I comment out the window.location(history(-1)) command and just have the function return false (ie stop the page submitting), the web-sql commands kick off and run as expected. If I leave it in, then the window seems to shift away before the sql commands have finished processing. This means that the database doesn't update.
Is this sort of issue a known problem, and is there a 'best-practice' to deal with it? I can't imagine that using the web-sql backend on form submit is a completely foreign concept?
---EDIT---
In the end I went with the following solution, its not the prettiest one in the world but it works.
Firstly I defined a global variable var queryCountWNPD = 0; the wnpd stands for writeNewProductDetails.
I then incremented the variable whenever a query was sent ie queryCountWNPD++; \\ localDB.webdb.runSQL('UPDATE orderLines...
After that I added a callback function to the sql command detailsWritten
This function (below) decrements the queryCountWNPD then checks if it is equal to 0. If it is then it runs the original window.history.go(-1) command.
function detailsWritten() {
queryCountWNPD--;
if(queryCountWNPD == 0) {
window.history.go(-1);
}
}
The answer below was credited because it pointed me in the right direction.
Interesting problem. It looks like you're having a concurrency issue. It appears as if the JS parser is not waiting for runSQL to finish before moving on to the next statement. At which point, JS continues to execute, until you hit window.location, which instantly loads a page from the history, and you lose your context. This also means, I don't think you ever hit your return false, because window.location acts like an interrupt, it fires immediately.
Also note that control statements (for, switch, if, etc.) do not increment the stack in JavaScript. I'm not sure how this applies, but I have a funny feeling that it might matter.
See if you can put the window.location outside of this function, higher in the stack so to speak. So let this function return false, then in the caller, if false, window.location(history(-1)). Functions DO increment the stack, so the parser might wait until all calls finish before "closing off" that stack level.

Javascript window.location calls getting lost?

I am having some trouble with a bit of code. I have a function that does some stuff to some data, calls a remote system (activating a script on that system and passing in the data), and then makes another call to the same system to activate a different script (which acts on the data saved above). The problem is that the 1st call to the remote system appears to get lost in the execution.
This is being run in Safari, uses jquery; the function is tied to a button click, which is defined in the javascript code with an onclick function (i.e. it is not defined in the html button definition).
Here's a rough breakdown of the function (cleaned out for viewing purposes - I hope I left enough to make it clear):
function compareJSON() {
// loop through the objects, testing and changing data
// ...
dataSession=({ //build object for output });
$.each( dataSession.chapters , function( indexC, value ) {
//compare objects to some others, testing and changing data
});
// ...
//Call remote script on other system
urlString="url://blah.dee.com/Blar?script=SaveJSON&$JSONobject=";
window.location= urlString + JSON.stringify(dataSession);
//Call remote script on other system
window.location="url://blah.dee.com/Blar?script=EditJSON";
}
The last three lines of code are the two calls. It uses the window.location to actually trigger the remote system, passing the data through the URL. But I need BOTH scripts to get called and run. It appears that only the LAST script in the sequence ever gets run. If I switch them around it remains whatever is in last place.
Is there something about the window.location that doesn't actually process until the end of the function?
This script actually used to be a series of separate function calls, but I figured I was running into asynchronous execution that was causing the various script calls to not register. But once I put the code into this single function, it was still happening.
Any clues would be helpful.
Thanks,
J
Modifing the value of window.location is reserved exclusively for instances in which you'd like to cause a browser redirect.
It looks like you want to trigger a page request instead. You say you already have jQuery loaded, if so, you can trigger such a request using jQuery.get or a similar function.
For example:
// Loads the myscript.php page in the background
$.get('myscript.php');
// You can also pass data (in the form of an object as the second argument)
$.get('myscript.php', { name: "John", time: "2pm" });

Categories