update javascript variable with ajax in real-time - javascript

I have a javascript function which needs to do a numerical calculation. Some of the numbers used in this calculation are stored in a database, and they will differ depending on how a user fills out an online form. Once the user fills out the form, they will click the CALCULATE button. At this time, in the JS function, I would like to use ajax to get values from a database that correspond to some other value chosen by the user.
For a simple example: there are 3 sizes of t-shirts, with different prices based on each size (stored in database). The user chooses the size, and when they click CALCULATE, I use ajax to get the price associated with the size they chose.
The question is, i want to use ajax to update some variables that I will use later on in the script. The way I am trying to do it now doesn't work, the variable in the script doesn't get updated from ajax, I can only access the value from the database inside the success function of the ajax call. I understand this is because ajax in asynchronous by nature, and it takes some time, waiting for the data to be returned from the server, while the function still continues to run
In the following example, the ajax call returns JSON data, and I have a function called isjson() that tests if the returned string is in fact JSON data.
Example code:
function calculate_cost(){
var price = 0;
var size = $('form#tshirt_form [name="size"] option:selected').val();
$.ajax({
url:'my_script.php',
type:'post',
data:'select=price&table=tshirts.prices&where=size = "' + size + '"',
success:function(data){
if(isjson(data)){
data = $.parseJSON(data);
data = data[0];
price = data['price'];
}else{
//display error getting data
}
}
});
// continue code for calculation
// this alert will display "0", but I want the price from the database in there
alert(price);
//perhaps do other ajax calls for other bits of data
//...
return final_price;
}
Does anyone know how I can accomplish this, updating variables with ajax in real-time??
Thanks a lot!
** EDIT **
Thanks everyone for the help, I understand about ajax being asynchronous. I would really like an answer where I don't have to continue the calculation inside the success function, because my actual problem involves many values from quite a few different tables. I would also like to be able to expand on the calculation in the future without it getting too convoluted. If this is not possible, ever, than i will have to live with that.
;-)
** EDIT 2 **
OK, we got the answer: of course it is right near the top on the docs page, :-/ sorry about that. The async property in jQuery ajax call. http://api.jquery.com/jQuery.ajax/

That is because ajax executes the request asynchronously by default and before the control reaches alert(price); the request has not yet executed and price still holds the old value.
If you want to execute it synchronously then you can set async to false.
$.ajax({
async: false,
.....
.....
});

you need to calculate inside the success function
function calculate_cost(){
var price = 0;
var size = $('form#tshirt_form [name="size"] option:selected').val();
$.ajax({
url:'my_script.php',
type:'post',
data:'query=select price from tshirts.prices where size = "' + size + '"',
success:function(data){
if(isjson(data)){
data = $.parseJSON(data);
data = data[0];
price = data['price'];
// continue code for calculation
// this alert will display "0", but I want the price from the database in there
alert(price);
//perhaps do other ajax calls for other bits of data
//...
}else{
//display error getting data
}
}
});
// return final_price; this function wont be able to return a value
}

ajax is asynchronous and for this reason you should refactor your code so that you do what you need to do in the callback
$.ajax({
url:'my_script.php',
type:'post',
data:'query=select price from tshirts.prices where size = "' + size + '"',
success:function(data){
if(isjson(data)){
data = $.parseJSON(data);
data = data[0];
price = data['price'];
//call another function (maybe make another ajax call) from here
dosomethingwithprice(price);
}else{
//display error getting data
}
}
});

Your ajax code takes time to execute (albeit not much); however the code after the ajax call is executed asynchronously, and most likely before the results of the ajax call come in.
Instead, why don't you try moving alert(price) into the body of the if(isjson(data)) region, and then execute a callback function which returns the price to whatever other utility you need it to be used at?

you have to do your calculation inside callback stack. Ajax work async, that means that, codes outsides callback function run before callback function start. So you should do your calculation in callback.
function calculate_cost(){
var price = 0;
var size = $('form#tshirt_form [name="size"] option:selected').val();
$.ajax({
url:'my_script.php',
type:'post',
data:'query=select price from tshirts.prices where size = "' + size + '"',
success:function(data){
if(isjson(data)){
data = $.parseJSON(data);
data = data[0];
price = data['price'];
}else{
//display error getting data
}
// continue code for calculation
// this alert will display "0", but I want the price from the database in there
alert(price);
//perhaps do other ajax calls for other bits of data
//...
return final_price;
}
});
}

I suggest having the ajax call return a deferred object. Then, when the final price is completely calculated, resolve the deferred object with that value.
function calculate_cost() {
var price = 0,
size = $('#tshirt_form [name="size"] option:selected').val(),
def = $.Deferred();
$.ajax({
data: {size:size},
url: 'my_script.php',
type: 'post',
dataType: 'json',
}).done(function(data){
data = data[0];
price = data['price'];
def.resolve(price);
}).fail(function(){
// do on error stuff
});
return def.promise();
}
// ...
calculate_cost("large").done(function(price){
alert(price);
}).fail(function(){
alert("Failed to retrieve price");
});

Related

Multiple inputs looping slows down each() and ajax()

I have a large number of inputs on a page, each input is disabled (and hidden) by default unless a checkbox is checked. Checking a related checkbox enables the input for a user to type an amount - that works fine.
After I've typed an amount into a given box and I shift my blur focus to something else (indicating I'm done with this input), I'm looping through every visible input to check if it has an amount in it and then sending an ajax request to update the back-end (this also works but maybe approach is wrong?).
What doesn't work is when I loop through more than 5-10 checkboxes, it seems to be extremely slow or simply doesn't send the ajax requests.
Code the listens for an enabled/visible amount box to change:
$(document).on("blur", ".dollar-amount", function(){
MainPage.amountInputListener('add');
});
Here is the foreach loop, which updates each associated user's backend data with the amount in the visible field:
var MainPage = {
amountInputListener: function (type) {
$(".dollar-amount:visible").each(function () {
//Get the employee being updated
var empID = $(this).data('empid');
//get the amount
var amount = $(this).val();
//Send update request to backend
$.ajax({
type: "POST",
url: "update/amount?empid=" + empID + "&amt=" + amount + '&type=' + type,
dataType: "html"
});
});
},
}
The HTML for the input:
<input type="text" name="dollar_hour_amountX" value="0" class="form-control dollar-amount disabled" data-empid="1" tabindex="-1" disabled>
Note: dollar_hour_amountX, X is a dynamic number related to the row's employee ID. data-empid is the same dynamic number, also used in the for loop.
Things I've tried to ensure the loop works properly:
Adding async: false. This allows it to work 100% of the time, but it's extremely slow the more inputs that are added.
Adding a timeout of 100-1000ms around the entire function, this simply delays the round-trip time of the Ajax call.
I'm open to Vanilla JS suggestions if it aids in making the calls to my back-end much faster and consistent.
// capture the passed in event
$(document).on("blur", ".dollar-amount", function(e){
// give the element to the method
MainPage.amountInputListener(e.target, 'add');
});
var MainPage = {
// accept the element on the arguments
amountInputListener: function (element, type) {
// use the element in place of `this`
//Get the employee being updated
var empID = $(element).data('empid');
//get the amount
var amount = $(element).val();
//Send update request to backend
$.ajax({
type: "POST",
url: "update/amount?empid=" + empID + "&amt=" + amount + '&type=' + type,
dataType: "html"
});
},
}
Does not make sense to update everything, just update what changes.
$('.dollar-amount').on("change", function () {
console.log(this.value, $(this).data('empid'))
// make the one Ajax request
})
Or change your backend to be able to handle multiple things being sent up at once so you are not hammering the backend with a bunch of calls.
"I'm looping through every visible input to check if it has an amount in it and then sending an ajax request to update the back-end (this also works but maybe approach is wrong?)."
I would strongly recommend you change this approach. I suspect it will fix your issues. Don't loop through all of these each time. There is no need. Simply, on blur, just check if this specific input has changed, and then send an ajax call ONLY if that specific one was edited.
Just pass "this" into the amountInputListener as an argument, and then get rid of the above "each" function. The rest would be the same. Instead of $(this), just pass the argument value that represents "this" from the event.
The first and foremost thing is using a get http verb request for update should be avoided.
This is not per standard, usually get requests are used to retrieve data.
And the next thing is instead of making an ajax call for each element with callname .dollar-amount and visible, it is better to declare a global variable above the foreach block of type array of objects and then add each item in the block to that global variable and then finally make an ajax request after the for block execution is done
amountInputListener: function (type) {
var objList = [];
$(".dollar-amount:visible").each(function () {
//Get the employee being updated
var empID = $(this).data('empid');
//get the amount
var amount = $(this).val();
//Send update request to backend
objList.push({
'empId':empId,
'amt':amount,
'type': type
});
});
$.ajax({
type: "post",
url: "update/amount"
dataType: "application/json",
data:{'data':objList}
});
},
}
This way you can send all data in one shot to server and it really helps in the performance.
Note: code is just to give you an idea.

Trying to get the newest innerHTML text of a label

I have a function that queries a database for info, when a button is clicked. This info gets written to innerHTML of a label. When this function returns, I read the innerHTML of this label. Problem is, it always returns the old value, not the new value that was pulled from the database. The label on the scree is displaying the correct value, though. When I click the button again, the value that I was expecting on the previous click, is now given. Seems like a timing issue but can't seem to figure it out.
example:
SQL Data - cost = 10
I expect to see 10 alerted to me when I click the button. I get a blank alerted to me, even though 10 is now in the label. When I click the button again, 10 is alerted, but 20 is now in the label.
function getInfo() {
var ctlMonthly = document.getElementById("cellMonthlyCost")
getSQLData(ctlMonthly);
alert(ctlMonthly.innerHTML);
}
function getSQLData(ctlCell){
...
var my_ctlCell = document.getElementById(ctlCell);
$.each(objData.items, function() {
my_ctlCell.innerHTML = this.Param1
});
...
}
Thanks.
you need to add the alert after the data is received from the database. I am assuming that you're sending an ajax request to fetch data. You will be able to get the new value in the callback of you're ajax request function.
Currently what is happening in your code is that
1. getSQLData(ctlMonthly);
// This sends a request to the data base to fetch data
2. alert(ctlMonthly.innerHTML);
// This shows the current value in an alert
3. data is received and shown in the label
This process happens so fast that you don't notice the difference between step 2 and 3.
Is this what you want?
I used a callback function
function getInfo() {
var ctlMonthly = document.getElementById("cellMonthlyCost")
getSQLData(ctlMonthly,alertInfo);
}
function alertInfo(info){
alert(info);
}
function getSQLDate(ctlCell,callbackFn){
...
var my_ctlCell = document.getElementById(ctlCell);
$.each(objData.items, function() {
my_ctlCell.innerHTML = this.Param1;
callbackFn(this.Param1);
});
...
}
to piggyback on Himanshu's answer, your request to your server is async. Meaning javascript will execute the GET request and continue on with the script, when the requests comes back from the server it will run whatever callback you give it. ( i.e. update label tag )
assuming getSQLData is a ajax call or something promised based, something like:
function getSQLData(ctlCell){
return $.get('/sql/data').done(function () {
var my_ctlCell = document.getElementById(ctlCell);
$.each(objData.items, function() {
my_ctlCell.innerHTML = this.Param1
});
});
}
you can change your code to:
function getInfo() {
var ctlMonthly = document.getElementById("cellMonthlyCost")
getSQLData(ctlMonthly)
.done(function () {
alert(ctlMonthly.innerHTML);
});
}
Basically the difference is your telling javascript to alert the innerHTML after the requests comes back from the server.
The more correct answer would be to alert the data straight from the response instead of reading from the DOM.

storing AJAX response into variable for use later in script?

here is the gist of my code: https://gist.github.com/tconroy/e52e0e7402face8f048e
Basically, my program is broken down into several steps:
retrieve user input from N number of inputs (user can add/remove)
perform AJAX query on each input, retrieving JSON formatted weather data for each.
on successful AJAX, pass the data to dataReady() function.
dataReady() function stores the data into a global Array[]
The problem is the AJAX data is not storing in the global array. how can I save the JSON response for use later in the program? I need to store all my weather data in one array, so I can iterate through it to create my graph later in the program.
The part causing issues in particular:
function getWeatherData(){
// set up query strings.
var queryBase = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=",
queryEnd = "&format=json&num_of_days=5&key="+weatherAPIKey;
// iterate through each address input
$('.inp').each(function(){
// setup query
var inp = this;
var addr = encodeURIComponent( inp.value );
var query = queryBase + addr + queryEnd;
// perform query
$.ajax({
url: query,
async: false,
dataType: 'jsonp',
success: function(json){
// format our response data into object, push it into container array.
var objName = String(decodeURIComponent(addr));
var objVals = json.data.weather;
dataReady(objName, objVals);
},
error: function(){
alert(errMsg);
}
});
}); // end $('.inp').each();
// setup the graph
setupGraph();
} // end getWeatherData();
function dataReady(objName, objVals) {
console.log('dataReady() called.');
responseValues[objName] = objVals;
}
From what I understand (see comments) you are dealing with a typical problem with asynchronous calls. You call AJAX, then you call setupGraph() but the ajax response will arrive after that call, because it is asynchronous.
First of all, doing async: false is bad, wrong and the source of all evil. Don't use it never ever. In your case it won't even work, because you can't force JSONP to be synchronous. But even if you could let me repeat my self, because this is important: don't ever use async: false.
Now back to your problem. What you should is to use deferred callbacks instead:
var reqs = [];
$('.inp').each(function(){
// some code
reqs.push(
$.ajax({
// some settings
})
);
});
$.when.apply($, reqs).then(function() {
setupGraph();
});
Read more about $.when here: https://api.jquery.com/jQuery.when/

Updating a third field after getting ajax updates to two others

I have a form with 3 elements (Qty, UnitCost, and TotalPrice) that are calculated based on the results of other data earlier in the form.
Qty and UnitCost are filling in properly based on a jquery Get, however the Total Price, which I am just using plain old javascript doesn't update unless I make a change in earlier fields (after which it does update correctly).
I am still VERY new to jquery and am teaching myself as I go, so I am likely missing something.
The Form looks like this
A (Text), B (Dropdown), C(dropdown), Qty, UnitCost, TotalPrice
//Get the unit cost
$.get("calcCost.php", {item:item}, function(data) {
document.getElementById(unitCostField).value = data;
});
unitCost = document.getElementById(unitCostFiled).value;
The code for Qty is essentially the same - just the fields and php script are alerted. Both are working correctly.
However, when I try to calculate the TotalPrice (which is just Qty*UnitCost) it's not updating right away. It starts out as 0 - which is expected when either Qty or Unit Cost is not filled in yet.
//Total Cost
cost = unitCost * qty
document.getElementById(costField).value = cost;
(The variables inside document.getElementById are already defined elsewhere);
Any ideas?
You need to remember that A in AJAX stands for asynchronous which means that the result of an AJAX request will not be available immediately for you to use. Instead, the browser will execute the request, finish everything else that you have on your call stack and only then, providing your request returned a response by that time, will your ajax success execute.
The example you have provided is even more interesting because your cost calculation routine needs to run after both Qty and UnitCost requests finish, and only if both of them were successful. I believe the best solution to a problem like this, especially that you are already using jquery, are Deferred objects.
The jquery docs for $.when (which is the method you might want to consider using) show a solution to an almost exactly the same problem as yours.
However, for the sake of convenience (error handlers omitted for brevity):
var calcCostReq = $.get("calcCost.php", {item:item}).done(function(data) {
document.getElementById(unitCostField).value = data;
unitCost = document.getElementById(unitCostFiled).value;
});
var qtyReq = $.get("qty.php").done(function(data) {
//whatever you need to do when qty was successful
});
$.when(calcCostReq, qtyReq).done(function() {
cost = unitCost * qty
document.getElementById(costField).value = cost;
}
You are retrieving the unitCostField value before it has been populated by the AJAX request. Even though the unitCost assignment is below the $.get method, it will still execute before the AJAX request has finished.
Code that relies on a AJAX request must be handled inside the callback function.
var qty;
function calcCost() {
var unitCost = document.getElementById(unitCostField).value,
cost = unitCost * qty;
document.getElementById(costField).value = cost;
}
$.get("calcCost.php", {item:item}, function(data) {
document.getElementById(unitCostField).value = data;
calcCost();
});

jQuery to load text file data

I'm trying to load data from a text file on my server using the $.get() function in an external script file. My code is as follows:
/*
* Load sample date
*/
var stringData;
$.get("http://localhost/webpath/graphing/sample_data.txt", function(data){
stringData = data;
//alert("Data Loaded: " + stringData);
});
//Split values of string data
var stringArray = stringData.split(",");
alert("Data Loaded: " + stringData);
When I'm inside the $.get() function I can see stringData var get peopulated just fine and the call to alert confirms that it contains data from the sample text file. However, when I get outside the $.get() function, the stringData var no longer shows. I don't know enough about how the function works to know why it is not doing as I expected. All I want it to do is load the text data into a variable so I can work with it. Any help is appreciated.
get is asynchronous meaning it makes a call to the server and continues executing the rest of the code. This is why you have callback methods. Whatever you intend to do with the return data do it inside the callback method(where you have put the alert).
get, post are all asynchronous. You can make a synchronous call by using
using $.ajaxSetup({ async: false }); anywhere in your code. This will affect all ajax calls in your code, so be careful.
$.ajax with async: false e.g. shown below.
Look at the below code and the API docs link mentioned above to fix your problem.
/*
* Load sample date
*/
var stringData = $.ajax({
url: "http://localhost/webpath/graphing/sample_data.txt",
async: false
}).responseText;
//Split values of string data
var stringArray = stringData.split(",");
alert("Data Loaded: " + stringData);
The $.get function is asynchronous. You'll need to do any work on the returned data in the callback function. You can move that function to not be inline to clean up the code as well.
function parseData(data){
//do something with the data
alert("data is: " + data);
}
$.get("http://localhost/webpath/graphing/sample_data.txt",parseData);

Categories

Resources