Await ajax call in JavaScript - javascript

I know that there's many questions and answers about this but I'm new to JavaScript and I'm facing problem with async/ await function. I have two function : getInvoices() where I have a ajax call to get the needed data, and loadBarChart(data) that renders a bar chart. For the chart I'm using ApexCharts. So I first call getInvoices() function to get the data and then I call loadBarChart(data) passing the data like this:
$(document).ready(function () {
var data = getInvoices();
console.log(data); // data is undefined
loadBarChart(data);
});
The data is always undefined probably because the ajax call is not done jet.
Here is getInvoices() function code:
function getInvoices() {
var url = "#Url.Action("GetInvoiceCustum");
$.ajax({
type: "GET",
dataType: "json",
url: url,
success: function (data) {
return data;
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
}
Following this I changed the code, but at the end I don't know how to pass the data from getInvoices() to loadBarChart(data);
So far this is what I have :
$(document).ready(function () {
var url = "#Url.Action("GetInvoiceCustum");
var ajax1 = new Promise((resolve, reject) => {
$.ajax({
type: "GET",
url: url,
success: function (data) {
resolve("OK");
result = data;
},
error: function () {
reject(" ERROR");
},
});
});
//At this point how can I acces the result from ajax call, and call the loadBarChart(data)
ajax1.then(values => {
console.log(values)
}, reason => {
console.log("Errors: " + reason)
});
ajax1.then(function (data1) {
var data = data1.result;
console.log(a);
return data1.result;
//loadBarChart(data);
})
});
Doing this how can I access the data that returns getInvoices() and then call loadBarChart(data), or there are other ways to make this posible?

You can call the second function in success of the first function like
$.ajax({
type: "GET",
url: url,
success: function (data) {
loadBarChart(data);
},
error: function () {
reject(" ERROR");
},
});

Related

Handing value into Success function from AJAX Call

G'day all,
I'm trying to pass a value through to a Success var from the original AJAX call.
Here's some code :
function isJobComplete(jobGUID) {
var data = { "pJobGUID": jobGUID };
var url = '/DataService.asmx/isJobComplete';
var success = function (response, jobGUID) {
if (response.d) {
//The job is complete. Update to complete
setJobComplete(jobGUID);
}
};
var error = function (response) {
jAlert('isJobComplete failed.\n' + response.d);
};
sendAjax(data, url, success, error);
}
function sendAjax(data, url, success, error) {
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: success,
error: error || function (response) {
jAlert(response.d);
}
});
}
When the isJobComplete function runs, it has the correct value for jobGUID on the first pass through, but on the return to Success after the AJAX call, jobGUID changes to the word "success", with the double quotes.
How can I pass through that jobGUID to the Success function so I can use it to do more work depending on the AJAX response?
Thanks in advance....

show() overwritten multiple ajax calls

I have one html element (elem1) and 2 JS functions (func1, func2) that hides and shows elem1 respectively. These JS functions make individual ajax calls and func2 is calling func1 internally.
Problem: I need to call func2, which internally calls func1. Calling func1 hides elem1. After calling func1, I want to show elem1. But this show is not working.
JSFiddle: https://jsfiddle.net/46o93od2/21/
HTML:
<div id="elem">
Save ME
</div>
<br/>
<button onclick="func1()" id="func1">Try Func1</button>
<button onclick="func2()" id="func2">Try Func2</button>
JS:
function func1() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
$('#elem').hide();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}
function func2() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
func1();
$('#elem').show();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}
Make func1 take a callback function that tells it what to do after it gets the response. func2 can pass a function that shows the element.
function func1(callback) {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {
json: ''
}, // send in your data
success: function(data) {
if (callback) {
callback();
} else {
$('#elem').hide();
}
},
error: function(xhr, errmsg, err) {
alert('error');
}
});
}
function func2() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {
json: ''
}, // send in your data
success: function(data) {
func1(function() {
$('#elem').show();
});
},
error: function(xhr, errmsg, err) {
alert('error');
}
});
}
DEMO

Return value from nested success-function in jQuery's $.ajax?

I found this question which is almost exactly the same: Return value from nested function in Javascript
The problem is that the function is passed to jQuery's $.ajax function. Here's what i have:
function doSomething() {
// Do some stuff here
console.log(getCartInfo());
}
function getCartInfo() {
var url = blog_location + '?reqCartData=1';
$.ajax({
url: url,
type: 'get',
success: function(data) {
return data; <------------- This
}
});
}
I need to return data to the doSomething function, if that makes sense. I tried to return the entire $.ajax function but that returned the whole object. Any ideas?
Send a callback function:
function getCartInfo(onSuccess) {
var url = blog_location + '?reqCartData=1';
$.ajax({
url: url,
type: 'get',
success: function(data) {
onSuccess(data);
}
});
}
getCartInfo(function(data) {
console.log(data);
});
try this
function doSomething(date) {
........your data
}
function getCartInfo() {
var url = blog_location + '?reqCartData=1';
$.ajax({
url: url,
type: 'get',
success: function(data) {
doSomething(data);
}
});
}

Piping Value: Ajax + JQuery

I have a function in which I execute an ajax request and wait till I get a response and return a value but the value returned is undefined. What is wrong?
function GetVMData(url_s){
return $.ajax({
url: url_s,
crossDomain: true,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert('failed')
}
}).pipe(function(data) { return data[4]; });
}
If I print the value of data[4] within the ajax callback it prints the right value, therefore i know the request is going through but when I try this:
var cord;
cord = GetVMData(url).done(function(cpu_USG) {
return cpu_USG;
});
alert(cord)
the value of cord is wrong.
var cord;
cord = GetVMData(url).done(function(cpu_USG) {
return cpu_USG;
});
alert(cord)
This code runs asynchronously. So you need to perform everything in the callback, like:
GetVMData(url).done(function(cpu_USG) {
alert(cpu_USG);
});
Here:
var cord;
cord = GetVMData(url).done(function(cpu_USG) {
return cpu_USG;
});
alert(cord);
cord contains object, not the value. And by the way, you don't know where ajax calling will be finished, so you should be familiar with idea of callbacks..
As an example:
function makeRequest(url, callback) {
$.ajax({
url: url,
crossDomain: true,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert('failed')
},
success: callback
});
}
var do_something = function (data) {
alert(data[4]);
};
cord = makeRequest(url, do_something);

Variable is undefined error (even if console.log shows variable)

My function looks like that
var mail_ntfy=$("#nav_mail"), question_ntfy=$("#nav_question"), users_ntfy=$("#nav_users");
function CheckAll(){
var data=checkFor("m,q,u");
if(mail_ntfy.attr("data-number")!=data.m_count && data.m_count!=0)
mail_ntfy.attr("data-number", data.m_count);
if(question_ntfy.attr("data-number")!=data.q_count && data.q_count!=0)
question_ntfy.attr("data-number", data.q_count);
if(users_ntfy.attr("data-number")!=data.u_count && data.u_count!=0)
users_ntfy.attr("data-number", data.u-count);
showNotes(data.msg);
chngTitle(data.msg);
}
$(document).ready(function () {
setInterval(CheckAll(), 10000);
})
function checkFor(param){
$.ajax({
url: "core/notifications.php",
type: "POST",
dataType: "json",
data: {
chk:param
},
success: function (data) {
if(data.status!="error") {
console.log(data);
return data;
}
}
});
}
I got 2 questions:
1) I see that, checkFor function returns result (console.log shows result) but still getting data is undefined error message on line if(mail_ntfy.attr("data-number")!=data.m_count && data.m_count!=0). What am I missing?
2) I want to execute, CheckAll in every 10 seconds. But it doesn't start more than 1 time. why setinterval doesn't work properly?
checkFor() does not return any result. The console.log() statement is in the anonymous function attached to the success handler of your AJAX request; its return does not return from the checkFor() function.
If you want checkFor to return the data the AJAX call has to be synchronous. This is, however, bad Javascript practice (for example, it will hang the execution of scripts on the page until the request is complete). Unfortunately this whole design is flawed, but you could use this code if you REALLY have to:
function checkFor(param){
var result;
$.ajax({
url: "core/notifications.php",
type: "POST",
async: false,
dataType: "json",
data: {
chk:param
},
success: function (data) {
if(data.status!="error") {
console.log(data);
result = data;
}
}
});
return result;
}
You can't return data from success callback. Instead you can call CheckAll from success callback like this
success: function (data) {
if(data.status!="error") {
console.log(data);
//return data;
CheckAll(data);
}
}
To run checkFor instead every 10 seconds you can set the timer from within success callback too. That will call the checkFor 10 seconds after every successful ajax request. Using setInterval can end up with multiple simultaneous ajax calls.
success: function (data) {
if(data.status!="error") {
console.log(data);
//return data;
CheckAll(data);
setTimeout(checkFor,10000);
}
}
And your updated checkAll would be like
function CheckAll(data){
if(mail_ntfy.attr("data-number")!=data.m_count && data.m_count!=0)
mail_ntfy.attr("data-number", data.m_count);
if(question_ntfy.attr("data-number")!=data.q_count && data.q_count!=0)
question_ntfy.attr("data-number", data.q_count);
if(users_ntfy.attr("data-number")!=data.u_count && data.u_count!=0)
users_ntfy.attr("data-number", data.u-count);
showNotes(data.msg);
chngTitle(data.msg);
}
You are calling Ajax asynchronously therefore the system wont wait for ajax to end in order to continue proccessing. You'll have to add
async:false,
To your ajax call, like this:
function checkFor(param){
$.ajax({
url: "core/notifications.php",
type: "POST",
async:false,
dataType: "json",
data: {
chk:param
},
success: function (data) {
if(data.status!="error") {
console.log(data);
var ret=data;
}
}
});
return ret;
}
Hope it helps!

Categories