undefined variable under jquery payload - javascript

I'm trying to post some data to an API but I'm struggling with javascript.
function pushData() {
let rawdata;
$.ajaxSetup({
async: false
});
$.getJSON('https://api.db-ip.com/v2/free/self', function(result) {
result = rawdata;
})
console.log(rawdata);
let message = {
"ip": rawdata.ipAddress,
"country": rawdata.countryName,
"city": rawdata.city
};
console.log(message);
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/get",
headers: {},
/* crossDomain: true,
*/
type: "GET",
success: function(result) {
console.log(result);
},
error: function() {
console.log("error");
}
})
}
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/post",
crossDomain: true,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(message),
success: function(result) {
console.log(result);
},
error: function() {
console.log("error pushing data");
}
})
I'm getting Uncaught ReferenceError: message is not defined although I think that message is a global variable, so it should be called successfully on the payload? What I'm I doing wrong here?
Thanks to anyone for his reply in advance, I'm just trying to write a quick script for my API here.

message is a local variable in the pushData() function, not a global variable. But even if it were global, you'd have to call the function before the second $.ajax() call.
Move the second AJAX call inside the function so you can access the variable. And embrace asynchrony, don't fight it with async: false. Nest the successive AJAX calls inside the callback function of the previous one.
function pushData() {
$.getJSON('https://api.db-ip.com/v2/free/self', function(rawData) {
console.log(rawdata);
let message = {
"ip": rawdata.ipAddress,
"country": rawdata.countryName,
"city": rawdata.city
};
console.log(message);
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/get",
headers: {},
/* crossDomain: true,
*/
type: "GET",
success: function(result) {
console.log(result);
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/post",
crossDomain: true,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(message),
success: function(result) {
console.log(result);
},
error: function() {
console.log("error pushing data");
}
})
});
},
error: function() {
console.log("error");
}
})
}

Related

JS Aysnc call from DotNet Application

I am getting Timeout error as execution of this call takes 4-5 mins.
Can you please help me out on this.
This is C# application and I am calling from JS.
function fnGetAlertsData() {
$.ajax({
url: "http://192.168.55.95:8011/mas_billing/pullroster", async: true, type: 'POST',
data: '{"startdate": "03/28/2022", "enddate": "03/28/2022","invoice_number": ""}',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (result) {
console.log(result);
var mydata = JSON.stringify(result);
console.log(mydata);
sessionStorage.setItem("SnNvbkl0bXNPZVJlZ2lzdHJ", mydata);
// $("#dvResult").html(result);
}
,
error: function (error) {
console.log(error);
},
timeout: 300000
});

Nested Promise structure

I have a javascript function with two promises:
uploadDocument = function (formData, order) {
$.ajax({
type: "POST",
url: "/API/Documents/addDocument",
data: formData,
contentType: false,
processData: false
}).then(function (documentID) {
order.referenceID = documentID;
return $.ajax({
type: "POST",
url: "/API/Documents/addOrder",
data: ko.toJSON(transaction),
contentType: "application/json"
});
}).then(function (result) {
return 'success';
});
}
That works perfectly, the API calls success.
the call to the function is:
uploadDocument(formData, order).then(function (data) {
console.log('success');
})
At this point I'm getting an error:
Uncaught TypeError: Cannot read property 'then' of undefined
What am I doing worng?
You need to return your $.ajax() and then use then on it. Without return the function returns undefined by default, so why you get an error. See return before $.ajax(...).then(...).
uploadDocument = function (formData, order) {
return $.ajax({
type: "POST",
url: "/API/Documents/addDocument",
data: formData,
contentType: false,
processData: false
}).then(function (documentID) {
order.referenceID = documentID;
return $.ajax({
type: "POST",
url: "/API/Documents/addOrder",
data: ko.toJSON(transaction),
contentType: "application/json"
});
}).then(function (result) {
return 'success';
});
}

ajax jquery message show after the function completed

I think it is simple question. I've tried to search but still not found an answer yet.
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
messageBox(result.d);
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
I want to show message after success() performed.
That means the comment left already then show message.
Thanks anyway!
P/s: I read a topic about jQuery Callback Functions at https://www.w3schools.com/jquery/jquery_callback.asp.
Can we use it in here? If we can, how to use?
You can try like this
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
$.when(this).then(setTimeout(function(){ messageBox(result.d)}, 200));
// if you dont want use set timeout then use
// $.when(this).then(messageBox(result.d), 200));
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events.
Considering your implementation of var success = function() you may try with following approach:
Modify the success() to accept callback function as follows:
var success = function(callback) {
self.removeComment(commentId);
if(parentId)
self.reRenderCommentActionBar(parentId);
if(typeof callback == "function")
callback();
};
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
//passing the callback function to success function
success(function(){
messageBox(result.d);
});
}
},
error: error
});
},

Why Unable to get success callback in Jquery/ajax call to RESTful services?

function GET() {
jQuery.support.cors = true;
$.ajax({
url: 'http://localhost:32253/api/UserDetail/GetRoleDetails',
type: 'GET',
async:true,
contentType: "application/json",
dataType: 'json',
xhrFields: {
withCredentials: true
},
error: function (xhr, status)
{
alert(status);
},
success: function (data) {
alert("Success!");
}
});
return false;
}
I am very much new to ajax,I tried a ajax call to my services method which returns value.But the success callback function is never fired .I only get error.What might be the reason?
I tried using dataType to jsonp and other similar solutions which had been found in Stackoverflow regarding this issue.Nothing worked out.I am getting server response as 200 oK.
try this code
$.ajax({
type: "POST",
url: URL,
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
jsonp: "onJSONPLoad",
jsonpCallback: "newarticlescallback",
crossDomain: "false",
beforeSend: function (xhr) {
},
error: function (request, status, error) {
console.log("Error In Web Service...." + request.responseText);
return false;
},
success: ajax_success,
complete: function (xhr, status) {
}
});
create function "ajax_success" in ur page
like below
function ajax_success(parsedJSON) { //you code here
}
this may be help you
try this code
$.ajax({
type: "POST",
url: URL,
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
jsonp: "onJSONPLoad",
jsonpCallback: "newarticlescallback",
crossDomain: "false",
beforeSend: function (xhr) {
},
error: function (request, status, error) {
console.log("Error In Web Service...." + request.responseText);
return false;
},
success: function (data) {
Result = data;
},
complete: function (xhr, status) {
}
});

Ajax method to a webmethod in asmx is not firing

I have a strange problem with the below AJAX jQuery method to call a webmethod in an asmx service. It's not firing when I try to call it, but the moment I uncomment any of the alert in code to debug, it works all of sudden.
It confuses me, what would be the problem? Am I missing something here..
Code:
var endXsession = function() {
var fwdURL = "";
$.ajax({
type: "POST",
url: "Session.asmx/RemoveSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msge) {
//alert(msge.d);
fwdURL = msge.d;
},
error: function(response) {
//alert(response.responseText);
fwdURL = response.responseText;
}
});
//alert(fwdURL);
return fwdURL;
};
response.responseText is undefined ... it's response.statusText ..
function endXsession() {
var fwdURL = "";
$.ajax({
type: "POST",
url: "Session.asmx/RemoveSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msge) {
// alert(msge.d);
fwdURL = msge.d;
}
,
error: function (response) {
// alert(response.statusText);
fwdURL = response.statusText;
}
});
// alert(fwdURL);
return fwdURL;
}
console.log(endXsession());

Categories

Resources