Using two different ajax call - javascript

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

Related

Ajax call doesn't work without an alert call

Based on the flag 'isConformpage' we are adding some log in the database.
The log code is triggered via an AJAX call.
The flag condition is not being passed even though the value is 'true'.
It works if I add an alert() before the if condition.
PS: WriteLog1 method return in VB.net. Mentioning here although it doesn't have any impact on the question.
try {
setTimeout(function () {
//your code to be executed after 5 second
if (isconformpage) {
var split = document.getElementById("hdnconfirmpage").value.split("#");
transaction = split[0];
transaction = jQuery.parseJSON(transaction);
user = jQuery.parseJSON(split[1]);
component = jQuery.parseJSON(split[2]);
//Tagging log start
var pathurl = "/" + loc[1] + "/thankyou.aspx/WriteLog1";
$.ajax({
type: "POST",
url: pathurl,
data: '{Message: "' + "-" + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
// success: OnSuccess1,
failure: function (response) {}
});
// Tagging log end
}
}, 5000);
}
You are "Missing catch or finally after try"
Check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

AJAX - Wait for data to append before looping next

I am creating a drop down list in JavaScript, I am loading the data via Ajax and JSON, at the moment my code loops through a set of departments and runs into the ajax call in each iteration.
My problem is that my data seems to be appending in a random order, its likely that its loading in the order of whichever loads quickest.
I want to be able to loop through my Ajax call and append the data in the order that I declare (for each department).
is this something that can be done?
Here is my code:
//-- Ajax --
var departments = ['Accounts', 'Commercial', 'Installation', 'Production', 'Sales'];
var i;
for (i = 0; i < departments.length; i++) {
$.ajax({
type: "POST",
url: "Default.aspx/EmployeesDropDown",
data: '{X: "' + departments[i] + '"}',
contentType: "application/json; charset=utf-8",
dataType: "text json",
async: true,
success: createdropdown,
failure: function () {
alert("FAIL!");
}
});
}
//-- Creates dropdown --
function createdropdown(data) {
...appends all the data to my drop down list...
}
Any help or advice is appreciated, thank you in advance.
EDIT: This question is different from the related ones because I need to be able to loop through the string array, rather than just iterating based on numbers.
If you want to load the departments in the order they appear in the departments array you could load them one by one, waiting for each ajax request to finish until you start the next request.
Here is an example:
var departments = ['Accounts', 'Commercial', 'Installation', 'Production', 'Sales'];
var i = 0;
function reqDep(department) {
/*
Since i can't use ajax here let's use a promise.
*/
var p = new Promise(function(res, rej) {
setTimeout(function() {
res(department)
}, 1000)
})
return p;
// This is what you would actually do.
/*
var data = '{X: "' + department + '"}'
return $.ajax({
type: "POST",
url: "Default.aspx/EmployeesDropDown",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "text json",
});
*/
}
function initDepartments(index) {
reqDep(departments[index])
// Here you would use `.done(function(data...`
// I am using `.then(function(data...`
// because of the promise.
.then(function(data) {
console.log(data)
if(i < departments.length) {
initDepartments(i)
}
})
i++;
};
initDepartments(i)

Data is lost after ajax call

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;
}

adding to array from inside ajax call javascript - undefined

I declare an array then make an ajax call which returns multiple rows of values. I'm trying to add the id of these rows to that array that i declared previously, but it keeps returning undefined.
var recipeIds = Array();
$.ajax({
url: url,
type: 'POST',
contentType: "application/json",
dataType: 'jsonp',
crossDomain: true,
jsonp: 'jsoncallback',
cache:true,
success: function(data, status){
$.each(data, function(i,item){
recipeIds.push(item.id);
});
},
error: function(){
console.log("Ajax not working - recipies in cat");
}
});
alert("array0 = " + recipeIds[0]);
any suggestions?
When you alert, the ajax call hasn't yet returned. It's asynchronous, meaning the ajax call will happen after the alert.
You must use the result from inside the success callback you give to the ajax function.

Jquery post success variable scope

I'm trying to return the ajax success array from one function to another. For some reason I don't seem to be able to pass the data stored in a variable in the success part of the ajax function into the parent function to return.
I looked at this post to try and figure things out, but not such luck:
jQuery Ajax call - Set variable value on success
Thanks so much for any assistance.
Here's a simplified version of the code:
// make json_to_return global
var json_to_return;
function loop_through_data(){
// call the load_days function and put its array data into days_array
var days_data = load_days(03,2010);
// I'd like to be able to iterate through days_data here
//
//
}
function load_days(selectedMonth, selectedYear){
$.ajax({
type: "POST",
dataType: "json",
url: "../includes/get_availability.php",
data: "month=" + selectedMonth + "&year=" + selectedYear,
success: function(available_json){
json_to_return = available_json;
},
error: function(msg){
alert("error " + msg);
}
});
return json_to_return;
}
This part of your function happens later:
success: function(available_json){
json_to_return = available_json;
}
So the variable you're returning is undefined, because the code to set it doesn't happen until the response comes back from the server. Either call the rest of the code to run from your success function, so it'll run when the data's ready, or set async:false (less desirable because it locks the browser).
The async: false method is like this:
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "../includes/get_availability.php",
data: "month=" + selectedMonth + "&year=" + selectedYear,
success: function(available_json){
json_to_return = available_json;
},
error: function(msg){
alert("error " + msg);
}
});
The better approach:
$.ajax({
type: "POST",
dataType: "json",
url: "../includes/get_availability.php",
data: "month=" + selectedMonth + "&year=" + selectedYear,
success: function(available_json){
loopThroughTheDaysAndDoStuff(available_json);
},
error: function(msg){
alert("error " + msg);
}
});
$.ajax is an asynchronous function.
It means that when called, the function keeps executing.
In your code provided var days_data = load_days(03,2010); this happens:
Start an ajax call (asynchronous, function keeps executing)
return json_to_return (undefined)
days_data == undefined
ajax call finishes, json_to_return gets assigned (this can happen in any timespan)
You should rethink your logic, and start coding around the asynchronousity of the ajax call.
A first approach might be passing a function (callback) to load_days which should be called AFTER the success of the ajax call.

Categories

Resources