Ajax call doesn't work without an alert call - javascript

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

Related

How do I override JSON errors and prevent a blank page from loading?

How do I prevent my JSON feed from crashing and ignore errors from a database if they occur while running, also how do I change the undefined errors into a string to return as a fall back like "pending" or "not available."
I tried inputting the Try, catch, finally method. Also, the If statements conditional equal and null ones I found to change undefined into a "string"
var flight = document.getElementById("flight");
var time = document.getElementById("time");
var airline = document.getElementById("airline");
var stat = document.getElementById("status");
var cities = document.getElementById("cities");
//Loading the document
//this is for updating the url
var url = './airport-test.json';
//var url = './proxy.php';
$(document).ready(function () {
$.ajax({
type: "GET",
dataType: "json",
url: url,
async: true,
contentType: "application/json; charset=utf-8",
cache: false,
success: function (data) {
var flightString = "";
var timeString = "";
var airlineString = "";
var statString = "";
var citiesString = "";
if(data) {
try {
var a = JSON.parse(data);
console.log(a);
} catch(e) {
var errorMessage = e.name + '' + e.message;
console.log(errorMessage);
}
}
for (i= 0,l = data.length = 16; i < l; i++ ) {
code here I erased to fit this question better...
}
flight.insertAdjacentHTML('beforeend', flightString);
time.insertAdjacentHTML('beforeend', timeString);
airline.insertAdjacentHTML('beforeend', airlineString);
stat.insertAdjacentHTML('beforeend', statString);
cities.insertAdjacentHTML('beforeend', citiesString);
}});
});
I am using a raspberry pi with chromium I just want the JSON feed to still show up even when there is an error instead of a blank page. It works most of the time. Also, want to change undefined from errors into a fallback string.
Not totally sure what exactly is the problem, taking a wild guess the server is not responding properly.
Define error handler,
$.ajax({
type: "GET",
dataType: "json",
url: url,
async: true,
contentType: "application/json; charset=utf-8",
cache: false,
success: function (data) {
....
}
error: function (error) {
// handle your error here.
....
}

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

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

JavaScript closure in a loop with asynchronous code

I have an array which contains two URLs for a web service. The following code executes both posts correctly and prints the correct data of which to the screen. Interestingly, however, is that the function will only print out "2" to the console, and yet it correctly prints out the correct number of objects in each request, screen cap:
You can see that there are a different number of objects returned from each AJAX request.
$(document).ready(function () {
var urlList = ['../NewService.asmx/GetNames', '../NewService.asmx/GetPersons'];
//executes both functions
multipleAjaxCalls(urlList);
//ajax function definition
function multipleAjaxCalls(array) {
var functionArray = [];
for (var i = 0; i < array.length; i++) {
var func = (function () {
$.ajax({
type: "POST",
url: array[i],
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log('this is the index: ' + i);
console.log('ajax success ' + i);
console.log(data.d);
},
error: function (xhr) {
console.log(xhr.status);
}
})
})(i); //<--I honestly don't understand what passing paramters to these closing parens actually does
//in this case it doesn't affect the output
functionArray.push(func);
}
return functionArray //this is superfluous
}
});
Why does this function return both sets of data correctly, but only prints out the an index of "2", especially when the array has a LENGTH of two?
fix
function (yetanotherI) {
$.ajax({
type: "POST",
url: array[yetanotherI],
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log('this is the index: ' + yetanotherI);
console.log('ajax success ' + yetanotherI);
console.log(data.d);
},
error: function (xhr) {
console.log(xhr.status);
}
})
})(i)
You were passing the value of i to the anony function but not using it. I changed that.
This is how it works... the inner function does not get called before the loop has finished so when it is called i (the outer one) is always 2.
You are doing this
(function(){
// stuff
})(something)
You should be doing this
(function(something){
// stuff
})(something)
Otherwise it won't matter if you create a closure, you're still not passing i to it.

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