Nested Promise structure - javascript

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

Related

undefined variable under jquery payload

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

Check(validate) send form data with ajax

I,m try check(validate) form data by using AJAX.
First i create callback function with AJAX request(in my example it's field time)
When i found same record in database, my NodeJS server response with value false, it's means we have record and we don't need add second record with that time).
My problem is that the form is still sent, regardless of the server response.
here my code(front end)
function funABC(mdata,callback){
console.log(mdata);
$.ajax({
url:'/dashboard/materials/checkshowrange',
method: 'GET',
dataType: "json",
contentType: "application/json",
data:mdata,
success: callback ,
// error:callback,
});
}
$('.addForm').on('submit', function (event) {
let form = $('.addForm');
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
// return false;
}
event.preventDefault();
checkdata = {
time_show : document.querySelector('.addForm').elements.time_show.value
}
functABC(checkdata,function(result) {
console.log(result);
if (result == 'true') {
alert(`For time: ${checkdata. time_show} there is already an event, choose a different time`);
return false;
}
})
form.addClass('was-validated');
some operations with form data, then send with ajax
$.ajax({
type: "POST",
url: "/dashboard/materials/add",
dataType: "json",
contentType: "application/json",
success: function (data) {
setTimeout(location.href = '/dashboard/materials', 10000);
},
data: JSON.stringify(formdata)
});
});
How and where did you call that post request ?
May be you would need to move post request into the callback
function funABC(mdata, callback) {
console.log(mdata);
$.ajax({
url: '/dashboard/materials/checkshowrange',
method: 'GET',
dataType: "json",
contentType: "application/json",
data: mdata,
success: callback,
// error:callback,
});
}
$('.addForm').on('submit', function(event) {
let form = $('.addForm');
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
// return false;
}
event.preventDefault();
checkdata = {
time_show: document.querySelector('.addForm').elements.time_show.value
}
functABC(checkdata, function(result) {
console.log(result);
if (result == 'true') {
alert(`For time: ${checkdata. time_show} there is already an event, choose a different time`);
return false;
} else {
$.ajax({
type: "POST",
url: "/dashboard/materials/add",
dataType: "json",
contentType: "application/json",
success: function(data) {
setTimeout(location.href = '/dashboard/materials', 10000);
},
data: JSON.stringify(formdata)
});
}
})
form.addClass('was-validated');
});
Or you could async false for validation request
$.ajax({
url: '/dashboard/materials/checkshowrange',
method: 'GET',
dataType: "json",
contentType: "application/json",
data: mdata,
success: callback,
async: false,
// error:callback,
});

get the return value of success in Iron-Ajax after POST

I'm currently working the project using Polymer and I'd like to get the return value of API after POST using Iron-Ajax.
Here is my sample code,
var rs = $.ajax({
type: "POST",
url: apiUrl,
data: _data,
dataType: "json",
contentType: 'application/json'
});
rs.done(function (data) {
console.log(data);
alert(data);
}
});
Ajax is asynchronous by default,you need add async:false to make it synchronous
var rs = $.ajax({
type: "POST",
url: apiUrl,
data: _data,
async:false,
dataType: "json",
contentType: 'application/json'
});
var result = null;
rs.done(function (data) {
console.log(data);
alert(data);
result = data;
}
});
//return result;//you can return value like this

Codes raises exception '[specific_method] is not defined'

I've got following javascript code. It's simply class, that should receive some data from REST WCF client.
class EmployeesWcfClient {
constructor(url) {
if (url == null) {
url = "http://localhost:35798/MyCompanyService.svc/";
}
this.url = url;
}
doGetRequest(relUrl) {
return $.ajax({
type: 'GET',
contentType: 'json',
dataType: 'json',
url: this.url + relUrl,
async: false
});
}
doPostRequest(relUrl, data) {
return $.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
url: this.url + relUrl,
async: false
});
}
getEmployees() {
return doGetRequest('Employees');
}
}
And I don't know why it's raises exception: 'doGetRequest is not defined'. Could someone help?
The answer is simple:
Use this operator in 'return this.doGetRequest('Employees');'. In first code example the this operator was missing.
inside ajax of doGetRequest the this.url will not refer to EmployeesWcfClient.url, instead it will point to the ajax options object itself. So take the reference of this before calling ajax request.
doGetRequest(relUrl) {
var _this = this;
return $.ajax({
type: 'GET',
contentType: 'json',
dataType: 'json',
url: _this.url + relUrl,
async: false
});
}
But I am not sure returning this ajax function will exactly return you the response from the request though you made it async: false. Better use callbacks or promise.

Call ajax.fail() from ajax.success()

So all I want to do is conditionally call the .fail method from within the .success method, how?
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail") { ajaxCall.fail(); return; }
alert("success");
})
.fail(function () {
alert("fail");
});
$.ajax return a promise so you can't do it directly. Your best shot is that :
var fail = function () {
alert("fail");
};
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail") { fail(); return; }
alert("success");
})
.fail(fail);
You can simply call as this.fail(); as shown below :-
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail")
{
this.fail();
return;
}
alert("success");
})
.fail(function () {
alert("fail");
});
For more information :-
http://www.youlikeprogramming.com/2013/07/jqueryajax-conditionally-call-error-method-fro-success/
just use the "this" keyword to actually call any other method of the ajax call, I have made a sample for error method.
$.ajax({
url: 'url',
dataType: 'json',
contentType: 'application/json; charset=utf-8;',
type: 'GET',
success: function (dataReturn) {
this.error('error called explicitly');
},
error: function (errorMessage) {
if(errorMessage.ResponseText) // or directly compare as errorMessage !== "error called explicitly" if u send the same message elsewhere
//actual error code
else
alert(errorMessage);
}
});
hope this helps :)

Categories

Resources