Data is lost after ajax call - javascript

I've got one ajax call after two previous. I need to pass results of those calls to the new one, so I do the following
$.when(getRespData(), getAxisComponents()).done(function (respData, axisData) {
var a = respData; //everything is ok
var b = axisData; //everything is ok
$.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload?runName=' + runName+ '&type=' + 'VAL',
success: (function (data) {
var c = respData; //everything is ok
var d = axisData; // Uncaught ReferenceError: axisData is not defined
}
but I've got Uncaught ReferenceError when I try to get my axisData inside my new ajax call, although operations with respData are ok.
My first 2 ajax calls look like
function getRespData() {
return $.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload?runName=' + runName + '&type=' + 'RESP',
success: (function (data) {
return data;
})
});
}
function getAxisComponents() {
return $.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload/axis?runName=' + runName,
success: (function (data) {
return data;
})
});
}
where runName, type, taskName are some params of function which contains all these ajax calls.
How can I fix this error, so that I would be able to access both respData and axisData ind my inner ajax call?

i solved it putting async false and declaring an array out of ajax call, like this
let array = [];
$.ajax({
url: path,
type: 'GET',
async: false,
dataType: 'json',
success: function(response){
array = response;
}
});
return array;

You're calling data in your success function but data isn't set before this.
In a jQuery .ajax function, data is the data that is sent to the server when performing the Ajax request, which is why you may think it is lost (because it was never there).
Consider the following:
$.ajax({
data: {"data": data},
dataType: "json",
url: 'yourURl',
success: function(data){
return data;
}

Related

sum values from multiple ajax requests

im trying to get the total value of the data returned by the ajax requests, but it is showing total:0 because it is executing the totalRev before completing the ajax requests.
var totalRev = 0;
$.ajax({
type: "POST",
url: "cloudmobi.php",
data: {action: 'cloudmobi'},
dataType:'JSON',
success: function(response){
document.getElementById('cloudmobi').innerHTML = response.cloudmobi;
console.log(response.cloudmobi);
var cloudmobi = parseInt(response.cloudmobi);
console.log('CLOUDMOBI:'+cloudmobi);
totalRev += cloudmobi;
}
});
$.ajax({
type: "POST",
url: "mobusi.php",
data: {action: 'mobusi'},
dataType:'JSON',
success: function(response){
document.getElementById('mobusi').innerHTML = response.mobusi;
console.log(response.mobusi);
var mobusi = parseInt(response.mobusi);
totalRev += mobusi;
console.log('MOBUSI:'+mobusi);
}
});
$.ajax({
type: "POST",
url: "appnext.php",
data: {action: 'appnext'},
dataType:'JSON',
success: function(response){
document.getElementById('appnext').innerHTML = response.appnext;
console.log(response.appnext);
var appnext = parseInt(response.appnext);
totalRev += appnext;
console.log('APPNEXT:'+appnext);
}
});
console.log('TOTAL:'+totalRev);
I do not want to use async because the whole purpose of using ajax here is to load the site fast then dynamically load the data
jQuery "when" solves your problem:
$.when( d1, d2 ).done(function ( v1, v2 ) {
console.log( v1 ); // "Fish"
console.log( v2 ); // "Pizza"
});
It would be far better to send all the data in a single request so you can do the sum on the server and send it in a single property in the response.
Assuming, for whatever reason, you cannot do that, then you could instead store all the promises from the AJAX requests and then execute your code after all of them have completed and added their values to an array. Then you can sum the array. Something like this:
var values = [];
var promises = [
$.ajax({
// ajax settings...
success: function() {
values.push(parseInt(response.cloudmobi), 10);
}
}),
$.ajax({
// ajax settings...
success: function() {
values.push(parseInt(response.mobusi), 10);
}
}),
// Nrequests...
];
$.when.apply(this, promises).done(function() {
var sum = values.reduce(function(a, b) {
return a + b;
}, 0);
// work with sum here...
});

AJAX: Store PHP data in a Javascript variable

As stated in the title, I have an ajax call. On the success function I want to store the returned data into a variable for use in my javascript. randNum.php simply returns a random number every 2 seconds, and I would like to use that number for other functions in my scripts. How can I use the data sent back from the php file in my javascript?
I know there are more logical ways to go about this, but want to know how to accomplish the task this way.
var result;
var interval = 2000;
function myCall() {
var request = $.ajax({
url: "randNum.php",
type: "GET",
dataType: "html",
success:function (msg) {
result = msg; //Not working as I intend
setTimeout(myCall, interval);
}
});
}
function(){
do something with result;
}
Declare a Global variable outside of the function and assign response variable to it after the ajax response.
var results;
function TestJSONP(){
$.ajax({
url: "randNum.php",
jsonp: "callback",
dataType: "jsonp",
success: function (response) {
console.log(response);
results = response;
}
});
}
You might not need to specify dataType, but use jqXHR.responseText to get the raw response. Something like
function myCall() {
var request = $.ajax({
url: "randNum.php",
type: "GET",
success:function (data, textStatus, jqXHR) {
result = jqXHR.responseText;
setTimeout(myCall, interval);
}
});
}
When you set dataType, and the response is not that type, then the ajax did not succeed and error call back will be invoked.

how to print values in array of deferred objects?

I have the following requests:
var req1 = $.ajax({
type: "GET",
url: url,
dataType : "xml"
});
req1.done(function (resp1) {
$(resp1).find('interest').each(function() {
var interest_id = $(this).find('id').text();
var interest_name = $(this).find('name').text();
var request = $.ajax({
type:"GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&page="+ interest_name + "&redirects&prop=text",
dataType: "jsonp"
});
requestsArray.push(request);
});
$.when.apply(null, requestsArray).done(function () {
console.log("entrou");
});
});
But when i get inside of
$.when.apply(null, requestsArray).done(function () {
console.log("entrou");
});
I dont know how to reach the individual responses in requestsArray. how can i do that? i have tried and tried but nothing seems to work.
You can use the arguments object to access an unknown number of values passed to a function:
$.when.apply($, requestsArray).done(function(){
console.log(arguments); //plain arguments object
console.log([].slice.call(arguments)); //arguments turned into real array
});
See MDN docs on the arguments object
Since you are pushing $.ajaxs into your array you might consider getting rid of the additional arguments they will pass like:
var request = $.ajax({
type:"GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&page="+ interest_name + "&redirects&prop=text",
dataType: "jsonp"
}).then(function(data, textStatus, jqXHR){
return data; //this will make sure textStatus and jqXHR aren't passed any further
});

Using two different ajax call

I have two different ajax calls . First one connects to one method of a web service . if it gets any null value for a specific field then it should call the other method from same web service . Here are the codes ..
$.ajax({
url: "webservices/ProdMonitorService.asmx/GetEstTimePrelimFinalCur",
data: "{'myactivity':'" + myactivity + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
success: function (data) {
var obj = jQuery.parseJSON(data.d);
for (var i = 0; i <= obj.length - 1; i++) {
var dur_time_formated = '';
var mytimedur = obj[i].time_duration;
if (mytimedur != null) {
dur_time_formated = mytimedur.replace('.000000', '');
}
else {
//only one time check for this
$.ajax({
url: "webservices/ProdMonitorService.asmx/GetEstTimePrelimFinalCurTotalProcessing",
data: "{'myactivity':'" + myactivity + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
success: function (data2) {
var obj2 = jQuery.parseJSON(data2.d);
dur_time_formated = obj2[0].total_processtime.replace('.000000', '');
}, error: function (result) {
//alert("Error: Please contact administrator for help: " + result.responseText);
}
});
}
For the first ajax call , it gets obj[0]......obj[7] but let say obj[0].time_duration comes null then it should go to second ajax call ,but even method "GetEstTimePrelimFinalCurTotalProcessing" returns some result , dur_time_formated varialbe comes null;, it is not even go thru second ajax call completely after first one.
Should use done function after first one is completed ?
You should try "async: false" instead of "async: true" here. This will work in your case.
bear in mind that ajax call is async. it means that dur_time_formated will be set later after your for-loop. so to solve the problem you can use any array variable outside your loop or sync ajax request

Ruby on Rails: Get json from controller in Javascript file

in my controller I've some json:
votes_controller.rb:
def create
...
vote_status = current_user.user_votes.pluck(:recipient_uid).include?(#user.uid)
render json: vote_status
end
I need to get vote_status in javascript file
votes.js:
jQuery(function($) {
$(".doWant").click( function () {
var status = vote_status.evalJSON();
var uid = $(this).parents("#dialog")[0];
var username = $(this).parents("#dialog")[0];
if(confirm("Are you sure?")) {
$.ajax({
url: '/votes' + "?uid=" + $(uid).attr("data-user-uid") + "&username=" + $(username).attr("data-user-username"),
type: 'POST',
success: function(data) {
console.log(data)
}
});
};
});
});
But there is an error Uncaught ReferenceError: vote_status is not defined. What am I doing wrong?
Thanks!
You're not defining this variable:
var status = vote_status.evalJSON();
You must define that variable.
It seems likely that you intended for that code to go into the success function, which returns the data from the ajax call as the first argument in that function:
success: function(data) {
console.log(data)
}
The vote_status is returned in success json callback, init the status there
$.ajax({
url: '/votes' + "?uid=" + $(uid).attr("data-user-uid") + "&username=" + $(username).attr("data-user-username"),
type: 'POST',
success: function(data) {
var status = JSON.parse(data);
}
});

Categories

Resources