I thought I had this mess sorted out in my head but for some odd reason its not working.
If you declare a variable outside of a function / scope and refer to it without the var inside a function then it changes the variable declared previously... right?
however, the first alert returns the correct price, but the second (last) alert returns 0. What am I doing wrong?
//get pricing
var price=0;
var modelid = $("#model_input").val();
var inCode = $("#code_input").val();
$.get("getpricing.php", { 'modelid': modelid ,'code' : inCode }, function(data){
price = data;
alert(price);
});
alert(price);
You are using an Ajax request.
Those, unkess specified otherwise, are Asynchrounous : they are executed in the background, without stopping the execution of the rest of the script.
So, the alert on the last line of code is executed before the Ajax request is finished ; which means price is still 0 at that time.
One way to change that would be to use a synchronous request (see async option) ; but I strongly advise against it ; quoting the doc :
By default, all requests are sent
asynchronous (i.e. this is set to true
by default). If you need synchronous
requests, set this option to false.
Note that synchronous requests may
temporarily lock the browser,
disabling any actions while the
request is active.
And you definitly don't want your application to freeze the whole browser!
You should re-think the way your application is designed, in this case : you can only use the "price" information after the Ajax request is finished -- which probably means you should place more code inside the function called on its success : just placing code after the $.get is not enough.
httprequests using .get are asynchronous, so the first alert (the second declared) will alert the original value as the callback for the request has not triggered yet.
Related
I'm completely new in javascript and I'm trying to understand its asynch nature. For this purpose here is my sample code :
$("#calculate-similarity").click(function(){
// assume input is an array whose length is larger than 0
var requestData={"uris":input,"limit":100};
client=new Ajax(requestData);
alert('inside .click function');
})
Ajax=function(requestData){
alert('inside ajax');
$.ajax({
url: 'http://localhost:8080/',
type:'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(requestData),
xhrFields: {
withCredentials: true
}
}).done(function(data) {
$("#ws-results").children().detach();
$("#ws-results").append('<table id="my-final-table"><thead><th>fname</th><th>furi</th><th>sname</th><th>suri</th><th>similarity</th></thead><tbody></tbody></table>');
$('#my-final-table').dynatable({
dataset: {
records:data
}
});
});
}
Now, above, I'm creating new Ajax() and inside of it, I'm making a ajax request. As far as I know its asynch event. Therefore, I though that, this request should be completed first of all, and then my other javascript lines (alert('inside .click function')) should be executed. In other words, I would expect :
1) alert inside ajax
2) show my datatable on the browser
3) alert inside .click function
However, I got with the following order :
1) alert inside ajax
2) alert inside .click function
3) show table on the browser
So, what do you suggest me to understand these concepts ? I've a solid background with several programming languages like c++ and java but this is my first time with web development and javascript.
EDIT
If I modify my .click function like below, do you say first of all always 10000 times hello will be printed out and then table will be shown ? Or table would be shown somewhere at the middle of logging ? I mean when the response comes, engine should wait first in order to show it ?
Modified code : (Let's remove all of the alert statements)
$("#calculate-similarity").click(function(){
// assume input is an array whose length is larger than 0
var requestData={"uris":input,"limit":100};
client=new Ajax(requestData);
for(var z=0;z<10000;z++){
console.log(z+'hi!');
}
})
As far as I know its asynch event. Therefore, I though that, this request should be completed first of all, and then my other javascript lines should be executed.
That is exactly the opposite of what it means.
The Ajax function will run. It will trigger an HTTP request. The Ajax function will finish. alert will run.
At some point in the future, the HTTP response will arrive and the done event handler will fire.
This is exactly the same principle as:
alert(1);
$("#calculate-similarity").click(function(){ alert(2); });
alert(3);
JavaScript doesn't wait for you to click on calculate-similarity before firing alert(3).
If I modify my .click function like below, do you say first of all always 10000 times hello will be printed out and then table will be shown ? Or table would be shown somewhere at the middle of logging ? I mean when the response comes, engine should wait first in order to show it ?
JavaScript won't interrupt a running function in order to execute a different (event handler) function. It will wait until it isn't busy before it goes looking for events.
new Ajax is object instantiation and it's synchronous. Therefore you get inside ajax as the first result because it happens when your Ajax object is instantiated, not to be confused with when the Ajax request is fired.
alert is executed synchronously, so that's the second thing you get.
$.ajax which wraps around XMLHttpRequest, responsible for firing the actual ajax request, is the only async part in your code and its result, which is encapsulated inside done, is what you get last.
In other words, I think the confusion comes from the fact that you introduce another layer of abstraction called new Ajax() which provide little actual value and a lot of confusion :P. inside ajax signal inside the instantiation of your Ajax object, not the firing of the actual request.
I'll try my best to explain it. Think of this more as an analogy, it's not exactly what's going on but I think it might help you understand:
alert('inside ajax'); - this is a blocking call, it will run and wait for you to click OK.
Then when you call Ajax, what you're essentially doing is saying "go make this web request when you have a chance, and when it finishes call my done method." That's a network operation. It could finish in 1 second, it could take many seconds. Rather than freezing up the whole browser, this is done "in the background." So that makes the UI remains responsive. At some point in the future the network request will finish. When it does, the function you specified in done will get called to let you know it finished. Think of making the Ajax request as adding it to a queue rather than actually connecting to the network. When the browser gets to it it will execute your request and wait for the server to respond. When it does, it will signal you to let you know.
Next you alert('inside .click function'); which displays the alert and blocks.
Like I said, that's not a technically accurate description of what's going on, but I'm hoping it helps you understand the principle of it.
I've been using selenium (with python bindings and through protractor mostly) for a rather long time and every time I needed to execute a javascript code, I've used execute_script() method. For example, for scrolling the page (python):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
Or, for infinite scrolling inside an another element (protractor):
var div = element(by.css('div.table-scroll'));
var lastRow = element(by.css('table#myid tr:last-of-type'));
browser.executeScript("return arguments[0].offsetTop;", lastRow.getWebElement()).then(function (offset) {
browser.executeScript('arguments[0].scrollTop = arguments[1];', div.getWebElement(), offset).then(function() {
// assertions
});
});
Or, for getting a dictionary of all element attributes (python):
driver.execute_script('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', element)
But, WebDriver API also has execute_async_script() which I haven't personally used.
What use cases does it cover? When should I use execute_async_script() instead of the regular execute_script()?
The question is selenium-specific, but language-agnostic.
When should I use execute_async_script() instead of the regular execute_script()?
When it comes to checking conditions on the browser side, all checks you can perform with execute_async_script can be performed with execute_script. Even if what you are checking is asynchronous. I know because once upon a time there was a bug with execute_async_script that made my tests fail if the script returned results too quickly. As far as I can tell, the bug is gone now so I've been using execute_async_script but for months beforehand, I used execute_script for tasks where execute_async_script would have been more natural. For instance, performing a check that requires loading a module with RequireJS to perform the check:
driver.execute_script("""
// Reset in case it's been used already.
window.__selenium_test_check = undefined;
require(["foo"], function (foo) {
window.__selenium_test_check = foo.computeSomething();
});
""")
result = driver.wait(lambda driver:
driver.execute_script("return window.__selenium_test_check;"))
The require call is asynchronous. The problem with this though, besides leaking a variable into the global space, is that it multiplies the network requests. Each execute_script call is a network request. The wait method works by polling: it runs the test until the returned value is true. This means one network request per check that wait performs (in the code above).
When you test locally it is not a big deal. If you have to go through the network because you are having the browsers provisioned by a service like Sauce Labs (which I use, so I'm talking from experience), each network request slows down your test suite. So using execute_async_script not only allows writing a test that looks more natural (call a callback, as we normally do with asynchronous code, rather than leak into the global space) but it also helps the performance of your tests.
result = driver.execute_async_script("""
var done = arguments[0];
require(["foo"], function (foo) {
done(foo.computeSomething());
});
""")
The way I see it now is that if a test is going to hook into asynchronous code on the browser side to get a result, I use execute_async_script. If it is going to do something for which there is no asynchronous method available, I use execute_script.
Here's the reference to the two APIs (well it's Javadoc, but the functions are the same), and here's an excerpt from it that highlights the difference
[executeAsyncScript] Execute an asynchronous piece of JavaScript in
the context of the currently selected frame or window. Unlike
executing synchronous JavaScript, scripts executed with this method
must explicitly signal they are finished by invoking the provided
callback. This callback is always injected into the executed function
as the last argument.
Basically, execSync blocks further actions being performed by the selenium browser, while execAsync does not block and calls on a callback when it's done.
Since you've worked with protractor, I'll use that as example.
Protractor uses executeAsyncScript in both get and waitForAngular
In waitForAngular, protractor needs to wait until angular announces that all events settled. You can't use executeScript because that needs to return a value at the end (although I guess you can implement a busy loop that polls angular constantly until it's done). The way it works is that protractor provides a callback, which Angular calls once all events settled, and that requires executeAsyncScript. Code here
In get, protractor needs to poll the page until the global window.angular is set by Angular. One way to do it is driver.wait(function() {driver.executeScript('return window.angular')}, 5000), but that way protractor would pound at the browser every few ms. Instead, we do this (simplified):
functions.testForAngular = function(attempts, callback) {
var check = function(n) {
if (window.angular) {
callback('good');
} else if (n < 1) {
callback('timedout');
} else {
setTimeout(function() {check(n - 1);}, 1000);
}
};
check(attempts);
};
Again, that requires executeAsyncScript because we don't have a return value immediately. Code here
All in all, use executeAsyncScript when you care about a return value in a calling script, but that return value won't be available immediately. This is especially necessary if you can't poll for the result, but must get the result using a callback or promise (which you must translate to callback yourself).
The problem
I am having is the following code will not update the tow select boxes "select1" and "select2", unless I have an alert immediately preceding the code.
Background info -
I am posting two variables to this page, "sel1val" and "sel2val", and I am assigning them to hidden input boxes with id's "sel1valtry" and "sel2valtry" respectively. I am assigning the values of these input boxes to the variables in the function and have named them "sel1val" and "sel2val". I can post more code if need be, but it is what I call "franken code"...haha! because I am a novice, it is assembled from many different styles of code.
Objective - what I am trying to achieve is to set two select boxes based upon the value of "sel1val" and "sel2val". The correct functionality is only obtained when I have an alert prior to the code.
Methods I have tried - I have left in some commented out code, to illustrate my attempts. I have been through many forums and that is where I got these ideas from. I suspect that the alert "reloads" the javascript part of the page, but I have no real basis for this. I have tried "document ready", variations of "window load", and even tried slowing things down with a delay, in case it was a timing issue. Each of the methods I have tried have resulted in the same outcome, whereby it only works with an alert.
I have achieved much success with my web based projects, and this would not have been possible without the invaluable resource in forums such as this one. I would like to thank anyone that has ever provided input/solutions, as without this I would never have been able to progress.
$(document).ready(function(){
// $(document).ajaxSuccess(function(){
// alert("AJAX request successfully completed");
// });
//$(window).load(function()
//window.onload = function()
//$(function ()
//Code goes here
//alert("got here");
//{
var sel1val = $("#sel1valtry").val()
var sel2val = $("#sel2valtry").val()
if (sel2val)
{
//alert("will not work without this alert"+sel1val);
//$("#select1").delay(2000).val(sel1val);
//$("#select1").val(sel1val);
$("#select1").prop('value',sel1val);
// var element = document.getElementById('select1');
// element.value = sel1val;
dochange('selection2', sel1val)
//var element = document.getElementById('select2');
// element.value = sel2val;
alert("will not work without this alert"+sel2val);
$("#select2").val(sel2val);
}
//}
});
//}
It seems like the dochange function is using some asynchronous API (like an AJAX call for example) which is setting value to the sel2val variable in its success callback. But since AJAX is asynchronous, this function returns immediately, not waiting for the server to return a response. By putting an alert you are blocking the execution of the next line of code and leaving enough time for the AJAX call to complete and assign a value to the sel2val variable.
The proper way to fix your code is to provide a callback to this function where you will perform the necessary actions:
dochange('selection2', sel1val, function(result) {
$("#select2").val(result);
});
And in your dochange function you will invoke this callback in the success event of your AJAX call.
Based on chrome developer tools a breakpoints I think I'm dealing with a scope issue I can figure out. Is it the way I define the function? The script below is an include js file and the array ' timeStamp I want available for use in other functions without having to call my loadData function everytime.
The timeStamp array goes undefined once it leaves the for loop before it even leaves the function.
var timeStamp = []; // Want this array to be global
function loadData (url){
$.getJSON(url, function(json) {
for (var i=0;i<json.length;i++){
timeStamp.push(json[i].TimeStamp);
}
console.log(inputBITS); //returns the value
});
console.log(inputBITS); //undefined
}
Thank you for anyhelp
It looks like the issue is that getJSON is asynchronous. When it executes and finishes and your code continues on, it indicates only the START of the networking operation to retrieve the data. The actual networking operation does not complete until some time later.
When it does complete, the success handler is called (as specified as the second argument to your getJSON() call) and you populate the timeStamp array. ONLY after that success handler has been called is the timeStamp array valid.
As such, you cannot use the timeStamp array in code that immediately follows the getJSON() call (it hasn't been filled in yet). If other code needs the timeStamp array, you should call that code from the success handler or use some other timing mechanism to make sure that the code that uses the timeStamp array doesn't try to use it until AFTER the success handler has been called and the timeStamp array has been populated.
It is possible to make some Ajax calls be synchronous instead of asynchronous, but that is generally a very bad idea because it locks up the browser during the entire networking operation which is very unfriendly to the viewer. It is much better to fix the coding logic to work with asynchronous networking.
A typical design pattern for an ajax call like this is as follows:
function loadData (url){
$.getJSON(url, function(json) {
// this will execute AFTER the ajax networking finishes
var timeStamp = [];
for (var i=0;i<json.length;i++) {
timeStamp.push(json[i].TimeStamp);
}
console.log(timeStamp);
// now call other functions that need timeStamp data
myOtherFunc(timeStamp);
});
// this will execute when the ajax networking has just been started
//
// timeStamp data is NOT valid here because
// the ajax call has not yet completed
// You can only use the ajax data inside the success handler function
// or in any functions that you call from there
}
And here's another person who doesn't understand basic AJAX...
getJSON is asynchronous. Meaning, code keeps running after the function call and before the successful return of the JSON request.
You can "fix" this by forcing the request to be synchronous with an appropriate flag, but that's a really bad idea for many reasons (the least of which is that you're violating the basic idea of AJAX). The best way is to remember how AJAX works and instead put all your code that should be executed when the AJAX returns, in the right place.
I'm creating a website that will feature news articles. These articles will appear in two columns at the bottom of the page. There will be a button at the bottom to load additional news stories. That means that I need to be able to specify what news story to load. Server-side, I'm simply implementing this with a LIMIT clause in my SQL statement, supplying the :first parameter like so:
SELECT *
FROM news
ORDER BY `date` DESC
LIMIT :first, 1
This means that, client-side, I need to keep track of how many news items I've loaded. I've implemented this by having the function to load new information be kept in an object with a property holding the number of items loaded. I'm worried that this is somehow a race condition that I am not seeing, though, where my loadNewInformation() will be called twice before the number is incremented. My code is as follows:
var News = {
newInfoItems: 0,
loadNewInformation: function(side) {
this.newInfoItems += 1;
jQuery.get(
'/api/news/'+ (this.newInfoItems - 1),
function(html) {
jQuery('div.col'+side).append(html);
}
);
}
}
On page load, this is being called in the following fashion:
News.loadNewInformation('left');
News.loadNewInformation('right');
I could have implemented this in such a way that the success handler of a first call made another AJAX request for the second, which clearly would not be a race condition...but this seems like sloppy code. Thoughts?
(Yes, there is a race condition.)
Addressing Just the JavaScript
All JavaScript code on a page (excluding Web-Workers), which includes callbacks, is run "mutually exclusive".
In this case, because newInfoItems is eagerly evaluated, it is not even that complex: both "/api/news/0" and "/api/news/1" are guaranteed to be fetched (or fail in an attempt). Compare it to this:
// eager evaluation: value of url computed BEFORE request
// this is same as in example (with "fixed" increment order ;-)
// and is just to show point
var url = "/api/news/" + this.newInfoItems
this.newInfoItems += 1;
jQuery.get(url,
function(html) {
// only evaluated on AJAX callback - order of callbacks
// not defined, but will still be mutually exclusive.
jQuery('div.col'+side).append(html);
}
);
However, the order in which the AJAX requests complete is not defined and is influenced by both the server and browser. Furthermore, as discussed below, there is no atomic context established between the server and individual AJAX requests.
Addressing the JavaScript in Context
Now, even though it's established that "/api/news/0" and "/api/news/1" will be invoked, imagine this unlikely, but theoretically possible situation:
articles B,A exist in database
browser sends both AJAX requests -- asynchronously or synchronously, it doesn't matter!
an article is added to the database sometime between when
the server processes the news/0 request, and
the server processes the news/1 request
Then, this happens:
news/0 returns article B (articles B,A in database)
article C added
news/1 returns article B (articles C,B,A in database)
Note that article B was returned twice! Oops :)
So, while the race-condition "seems fairly unlikely", it does exist. A similar race condition (with different results) can occur if news/1 is processed before news/0 and (once again) an article is added between the requests: there no atomic guarantee in either case!
(The above race condition would be more likely if executing the AJAX requests in-series as the time for a new article being added is increased.)
Possible Solution
Consider fetching say, n (2 is okay!) articles in a single request (e.g. "/api/latest/n"), and then laying out the articles as appropriate in the callback. For instance, the first half of the articles on the left and the second half on right, or whatever is appropriate.
As well as eliminating the particular race-condition above by making the single request an atomic action -- with respect to article additions -- it will also result in less network traffic and less work for the server.
The fetch for the API might then look like:
SELECT *
FROM news
ORDER BY `date` DESC
LIMIT :n
Happy coding.
Yes, technically, this could create a race condition of sorts. The calls are asynchronous, and if the first got held up for some reason, the second could return first.
However, as you don't have a great deal that goes on in your callback functions that depend on the presence of the other 'side' being populated I don't see where it should cause you too much grief.
Shouldn't be any race conditions, must be something else wrong in your code. The counter is incremented before your .get() call, so prior to each get the counter should be incremented correctly. Short example to demostrate that it works when called sequentially: http://jsfiddle.net/KkpwF/
I reckon you're hinting at the newItemInfo counter?
Observations:
You're calling News.loadNewInformation twice, with a callback function which will be executed on AJAX completion.
The callback method you provide does not alter the News object.
In this case, you don't have to worry. The second call to News.loadNewInformation will only be executed once the first call completes - that is, excluding executing the callback method. Hence your newItemInfo counter will contain the correct value.
Try this:
loadNewInformation: function(side) {
jQuery.get(
'/api/news/'+ (this.newInfoItems++),
function(html) {
jQuery('div.col'+side).append(html);
}
);
}