How to get data from ajax call? - javascript

I am trying to get data from ajax call by cross domain.
Here is code
function GetMaxWULen() {
var x;
$.ajax({
url : url,
method : 'POST',
jsonp : "callback",
async : false,
data : {
Function : "GetMaxWULen",
Authorization : Base64.encode(login + ":" + token),
WuType : $("#ddlWUType").val()
},
dataType : 'jsonp',
crossDomain : true,
error : function(request, status, error) {
alert('nie udało sie');
alert(error);
}
}).done(function(result) {
console.log('done result');
x = result;
console.log(x);
});
console.log('function end');
console.log(x);}
At the end of the function, x variable is undefined but in done event value is correct.
Could anyone can help me or tell what is wrong in this code?

This happens because your AJAX request is done asynchronously. It means the rest of your code won't wait your response be ready to continue.
If you need to use the data returned from AJAX outside your function, you might want to create a parameter to serve as a callback when the response is ready. For example:
function yourFunction(callback) {
$.ajax({
/* your options here */
}).done(function(result) {
/* do something with the result here */
callback(result); // invokes the callback function passed as parameter
});
}
And then call it:
yourFunction(function(result) {
console.log('Result: ', result);
});
Fiddle: http://jsfiddle.net/9duek/

try
$.ajax({
url : url,
method : 'POST',
jsonp : "callback",
async : false,
data : {
Function : "GetMaxWULen",
Authorization : Base64.encode(login + ":" + token),
WuType : $("#ddlWUType").val()
},
dataType : 'jsonp',
crossDomain : true,
error : function(request, status, error) {
alert('nie udało sie');
alert(error);
}
}).success(function(result) {
var datareturned = result.d;
console.log('done' + datareturned);
x = datareturned;
console.log(x);
});

Related

Javascript async loop with ajax call

I have a jQuery ajax call that I want to do some task in order after the result comes.
$.ajax({
url : 'https://api.spacexdata.com/v3/launches',
type : 'GET',
dataType:'json',
success : function(data) {
data.forEach(async function(element) {
await console.log(element.flight_number);
await auto(element.flight_number);
});
},
error : function(request,error) {
console.log(request,error);
}
});
function auto(val) {
$.ajax({
url : 'https://api.spacexdata.com/v3/launches/latest',
type : 'GET',
dataType:'json',
success : async function(data) {
await console.log('second api called' , data);
},
error : function(request,error) {
console.log(request,error);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
the out put is :
1
2
3
4
...
second api called Obj
second api called Obj
second api called Obj
second api called Obj
...
but the expected result is :
1
the second api called
2
the second api called
3
the second api called
4
the second api called
....
here is the jsfiddle:
Do you have any idea what is wrong with the loop? I want the sequence I mentioned!
Can you try this code
$.ajax({
url : 'https://api.spacexdata.com/v3/launches',
type : 'GET',
dataType:'json',
success : function(data) {
data.forEach(function(element) {
console.log(element.flight_number);
auto(element.flight_number);
});
},
error : function(request,error) {
console.log(request,error);
}
});
async function auto(val) {
const dataset= $.ajax('https://api.spacexdata.com/v3/launches/latest');
console.log('second api called');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Get ajax result in foreach

I try to load data from service yelp, no problem with the request, but I can't push it to array and return it.
I need to get ajax result in every iteration.
How to stop it until ajax result has received?
can anyone help me?
this.getDataForPlaces = function(addresses){
var locationDescs = [];
_.each(addresses, function(address){
var promise = getLocationDesc(address).then(function(data) {
locationDescs.push(data);
});
})
return locationDescs;
};
var getLocationDesc = function(address){
var parameters = [];
var message = {
'action' : 'http://api.yelp.com/v2/search',
'method' : 'GET',
'parameters' : parameters
};
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var parameterMap = OAuth.getParameterMap(message.parameters);
return $.ajax({
'url' : message.action,
'cache': true,
'method':message.method,
'data' : parameterMap,
'dataType' : 'jsonp',
'jsonp' : 'callback',
'success':function(data){
console.log(data);
}
});
};
You have to return the data variable instead of ajax function like this : replace the following
return $.ajax({
'url' : message.action,
'cache': true,
'method':message.method,
'data' : parameterMap,
'dataType' : 'jsonp',
'jsonp' : 'callback',
'success':function(data){
console.log(data);
}
});
with
$.ajax({
'url' : message.action,
'cache': true,
'method':message.method,
'data' : parameterMap,
'dataType' : 'jsonp',
'jsonp' : 'callback',
'success':function(data){
return data;
}
});
for pausing / stoping the loop until the ajax request completes you can replace the following :
var promise = getLocationDesc(address).then(function(data) {
locationDescs.push(data);
});
with
var promise = $.when(getLocationDesc(address)).done(function(data){
locationDescs.push(data);
});
if above does not work then use the following and replace the whole loop with following
var locationDescs = [];
_.each(addresses, function(address){
locationDescs.push(getLocationDesc(address));
});
$.when.apply($,locationDescs).done(function(){
});
Don't return complete ajax function , just inside the success function of ajax return the data like this : return data; because return whole ajax function it is not an data that you are getting from services , you have to return data variable.

How to mock ajax call to Jasmine test

Here is my code:
function sendRequestData(url, urlParameters) {
$.ajax({
url : url,
method : 'POST',
headers : {
'Accept' : 'application/json'
},
contentType : 'application/json',
data : JSON.stringify(urlParameters),
dataType : "json",
success : function(data) {
successCallBack(data)
},
error : function(data, status, errorThrown) {
failCallBack(data, status, errorThrown)
}
});
I want to mock and test this ajax call. Is there anyway I can do that?
If your test are hard to test, this means you are doing something wrong.
In your specific case, you need follow Dependency Inversion principle (think Dependency Injection) and inject your requirements into your function. Basically, you need to pass in all the dependencies including $, successCallback and failCallback. This would let you mock your ajax calls with Jasmine's spyOn() method and then check for correct function calls.
function sendRequestData(url, urlParameters, $, successCallBack, failCallBack) {
$.ajax({
url : url,
method : 'POST',
headers : {
'Accept' : 'application/json'
},
contentType : 'application/json',
data : JSON.stringify(urlParameters),
dataType : "json",
success : function(data) {
successCallBack(data)
},
error : function(data, status, errorThrown) {
failCallBack(data, status, errorThrown)
}
});
}
Your tests might look like this. I have not checked it, but you get an idea of what I mean.
describe("sendRequestData() does correct ajax calls", function() {
var $ok, $error, successCallback, failCallback = null;
beforeEach(function() {
// You can create a spy object using this syntax
$ok = jasmine.createSpyObj('$', ['ajax']);
// Or define it yourself like so
$ok = {
ajax: function(value) {
successCallback();
}
};
$error = {
ajax: function(value) {
failCallback();
}
};
spyOn($, 'ajax');
spyOn(successCallback);
spyOn(failCallback);
});
it("calls successCallback on success", function() {
sendRequestData('url', {}, $ok, successCallback, failCallback);
expect($.ajax).toHaveBeenCalled();
expect(successCallback).toHaveBeenCalled();
expect(failCallbackCallback).not.toHaveBeenCalled();
});
it("calls failCallback on failure", function() {
sendRequestData('url', {}, $error, successCallback, failCallback);
expect($.ajax).toHaveBeenCalled();
expect(successCallback).not.toHaveBeenCalled();
expect(failCallbackCallback).toHaveBeenCalled();
});
});
Or simply use jasmine-ajax plugin to mock your ajax calls.
If you are doing this on legacy code and cannot change the JS code maybe you can try as below
JS file
$.ajax({
async : true,
type : "POST",
data : requestPayload,
url : APIURL,
contentType: "application/json",
success : function (response) {
/* -- some code here --*/
},
error : function (errorResponse) {
/* -- some code here --*/
}
});
SPEC file
it("check api call", function () {
var testResponse = {
'status' : 'ok',
'errorCode' : '',
'message' : 'this is a mock response'
};
/*...*/
spyOn($, 'ajax').and.callFake(function(e) {
return e.success(testResponse);
// for failure case
//return e.error({
// 'status' : 'not_ok',
// 'errorCode' : 'Unauthorized'
//});
});
form.submit();
});
You can also call the e.success and
return $.Deferred().resolve(testData).promise(); from what I have understood in other examples.
Mocking jQuery ajax calls with Jasmine
spyOn($, 'ajax').and.callFake(function (e) {
e.success(testData)
return $.Deferred().resolve(testData).promise();
});

Ajax call to spring controller callback error function

Can you tell me what it's going wrong with the following ajax call to controller ?
The controller that is called via ajax :
#RequestMapping(value = "/userManagement/loadData.html", method = RequestMethod.POST,produces="text/plain")
public #ResponseBody String loadData(#RequestBody String jsonData) {
try {
Map<String, Object> data = JsonUtils.jsonAsMap(jsonData);
pageSize = Integer.valueOf(data.get("pageSize").toString());
pageNumber = Integer.valueOf(data.get("pageNumber").toString());
} catch (Exception e) {
return "failure";
}
return "success";
}
The ajax function :
function reloadUsers(){
$.ajax({
type : "POST",
cache : false,
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
url : "userManagement/loadData.html",
data : JSON.stringify({
pageSize : 10,
pageNumber : 0
}),
success : function(response) {
if(response.responseText=='true'){
console.log('success');
}else{
console.log('server error');
}
},
error : function(jqxhr){
console.log('error');
console.log(jqxhr.responseText);
}
});
}
Now when i execute the ajax call to the controller it always goes on the error function and the jqxhr.responseText is always the value returned by the controller(in this case 'success' or 'failure'.
My question is why is this happening ?
If i change the controller returned values to "true" or "false" the ajax successfully callback the 'success' function.
I also tried with produces="application/json"and got the same result.
Change the datatype to:
dataType: 'text',
As you are going to get a string in response because of this:
#RequestMapping(value = "/userManagement/loadData.html", ....... produces="text/plain")
//--------because of this-----------------------------------^^^^^^^^^^^^^^^^^^^^^^

Execute ajax function until get success of another ajax call

I need to execute an ajax function, the detail here is that i want to execute this function until another ajax function return success.
This is the function that will i have to wait to return success (try..catch block)
Ajaxfunction1
$.ajax({
type : "GET",
url :url,
data : parameters,
success : function(msg) {
try {
var jsonObject = JSON.parse(msg);
console.debug(msg);
//SendToDMS(msg);
} catch (e) {
$("#SaveConfig").removeAttr("disabled");
toastr.error(msg + '.', "Message");
}
},
failure : function(msg) {
$("#SaveConfig").removeAttr("disabled");
toastr.error('Error: ' + msg + '.', "Message");
}
});
I want something like this:
while ( Ajaxfunction1 != success ) { // while the previous ajax function not return success execute this another ajax function
$.ajax({
type : "GET",
url :url,
data : parameters,
success : function(msg) {
// something on success
},
failure : function(msg) {
// something when comes an error
}
});
}
How can I accomplish this? Thanks for your help
You can use the returned Deferred from $.ajax and check it's state() to see if it's resolved, rejected or pending, so something like this with a recursive function should do what you want.
var waitFor = $.ajax({
type : "GET",
url : url,
data : parameters
}).done(function(msg) {
try {
var jsonObject = JSON.parse(msg);
} catch (e) {
$("#SaveConfig").removeAttr("disabled");
toastr.error(msg + '.', "Message");
}
}).fail(function(msg) {
$("#SaveConfig").removeAttr("disabled");
toastr.error('Error: ' + msg + '.', "Message");
});
(function rec() {
$.ajax({
type : "GET",
url : url,
data : parameters
}).always(function() {
if (waitFor.state() != 'resolved') rec();
}).done(function(msg) {
// something on success
}).fail(function(msg) {
// something when comes an error
});
})();

Categories