AngularJS $http get data object displays status code instead of response - javascript

I have mulled over this for days and can still not figure out what I'm doing incorrectly so any ideas or even shots in the dark are appreciated. I am trying to display the response from a rest service to the user using the using the AngularJS $http get method, but when I print the data object to the console, I consistently receive the number 200 (I'm fairly certain it is giving me the status code). I hit success every time and, upon sending the request, the Chrome debug tool shows me the response with all the correct data. I just can't seem to get it to appear in a variable for display. Let me know if you think of anything! Thanks!
My javascript:
$scope.resendDestinations = [];
$scope.resendDestGet = function () {
var omtTypeCodeString = '';
for(var i = 0; i < $scope.mySelections.length; i++){
if(omtTypeCodeString == ''){
omtTypeCodeString = $scope.mySelections[i].orderHeader.omtOrderTypeCode;
}
else{
omtTypeCodeString = omtTypeCodeString + ',' + $scope.mySelections[i].orderHeader.omtOrderTypeCode;
}
}
$http({
method: 'GET',
url: restService.pom + //service url,
respondType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials': true
},
params: {
orderTypeCode: omtTypeCodeString,
transactionCode: 3
}
}).success(function (status, data, response, header) {
console.log("Success!");
//TODO see if this is being used... has to be
status = parseInt(status);
$scope.resendDestinations = data.multipleOrders;
if (status == 200 && $scope.resendDestinations.length == 0) {
$scope.bigAlert.title = 'Error',
$scope.bigAlert.header = 'Search Error';
$scope.bigAlert.content = 'Current search parameters do not match any results.';
$scope.showBigAlert();
}
else{
$scope.resendDestinations = data;
console.log("Data DestinationList here: ");
console.log($scope.resendDestinations);
console.log(data.multipleOrders);
console.log(data);
}
$scope.isSearching = false;
}).error(function (response, data, status, header) {
//Do error things
});
return $scope.resendDestinations;
};
And the service response:
[{"destCode":3,"destDescr":"Repository","attributes":null},{"destCode":4,"destDescr":"Pipeline","attributes":null},{"destCode":1,"destDescr":"Processor","attributes":null},{"destCode":2,"destDescr":"DEW","attributes":null},
{"destCode":7,"destDescr":"Management System","attributes":null},
{"destCode":8,"destDescr":"Source","attributes":null}]

You have the arguments in the wrong order. It should be: success(function(data, status, headers, config)
See the docs here (click).
Also, the .then() method is generally preferred. If you switch to that, you would access the data like this:
.then(function(response) {
var data = response.data;
var status = response.status;
//etc
});

Related

Angular dependent $http requests

I'm trying to fetch data via post request and the API I'm querying from returns a maximal 50 elements. This worked great so far, but now we have some uses cases where it's mandatory to receive an higher indeterminate number of elements.
The $http-method returns a promise but I must rely on this data to make another request.
My simplified code:
var data =
"q=" + term
"&timestamp=" + latest
$http({
method: 'POST',
url: url,
data: data
}).then(
function(response) {
let dataList = response.data.list;
if(dataList.length > 50)
/*TODO: new query with other timestamp-value*/
return dataList ;
},
function(response) {
if(shouldLog){
console.log("[DebuggingService] " + response);
}
}
);
Is there a way to combine multiple http requests depending on the request before?
EDIT
There is not pagination. So it's mandatory to change the timestamp value. (taking the latest timestamp of the response)
I would wrap that request in a function that can also be called recursively inside then() to return another request promise
Something like:
function getData(term, time, res = []) {
var data = "q=" + term + "&timestamp=" + time
// return the $http promise
return $http({
method: 'POST',
url: url,
data: data
}).then(function(response) {
let dataList = response.data.list;
// merge new data into final results array
res = res.concat(dataList);
if (dataList.length > 50) {
const timeStampFromResponse = //????
// return new request promise
return getData(term, timeStampFromResponse, res)
}
// return final array
return res;
})
}
getData(term, latest).then(function(results) {
// all results available here
}).catch(function(response) {
if (shouldLog) {
console.log("[DebuggingService] " + response);
}
})
Why not do something like this:
var data =
"q=" + term + "&timestamp=" + latest;
var amounts = 2;
url = 'https://api.github.com/search/repositories?q=topic:ruby+topic:rails';
call(url, data, checkForMore);
function call(url, data, callback) {
$http({
method: 'POST',
url: url,
data: data
}).then(function(data){
console.log(data);
console.log('------------');
callback(data);
});
}
function checkForMore(data){
if (amounts > 0){
amounts -= 1;
var newData = "q=" + term +
"&timestamp=" + data.SomehowGetLastestTimestamp;
call(url, newData, checkForMore);
} else {
// Save it maybe?
}
}
This is a very rough example, and probably doesn't work but it gets you a good idea what to do.
Basically, have a callback method that is called on the .then anonymous function. Then you can pass in the data and check to see if you need to call it more. (Based on your situations). If you do, then just call the call function again, but update your data.

Why is my $.ajax not showing up in Network tab, but opening in a new tab works?

Here is my AJAX code:
jQuery.ajax({url: url,
method: 'GET',
data: getParams,
/*success: function (json, textStatus, jqXHR) {
if(jQuery.active <= 1){
waitDialog.removeWaitDialog();
}
createProcessButtonEvent();
ajaxError = false;
returnFunction(jqXHR.responseJSON);
},*/
complete: function(jqXHR, textStatus, errorThrown) {
if(jQuery.active <= 1){
waitDialog.removeWaitDialog();
}
createProcessButtonEvent();
var response;
if (typeof jqXHR.responseJSON === 'object') {
response = jqXHR.responseJSON;
} else {
response = jqXHR.responseText;
}
if(response.errors.length == 1){ // jsonResults.message != ''
if(!warningMessage){ //hard coded for ad designer
jQuery('#alertMessageText').text(response.errors[0].message);
jQuery('#alertMessage').show();
jQuery('#waitDialog').jqmHide();
ajaxError = true;
return;
}
warningMessage.displayMessage(response.errors[0].message);
jQuery('.popup').modal('hide');
jQuery('.popup').not('.persist').remove();
}
if (response.errors.length > 1){
for(var n = 0; n < response.errors.length; n++){
if (response.errors[n].id == 1){ // 2005
window.location.href = '/login?destination=' + encodeURIComponent(window.location.pathname + window.location.search);
}
if (response.errors[n].id == 9500){
statusMessage.displayMessage(response.errors[n].message);
}
}
ajaxError = true;
//if(errorFunction){
// errorFunction(jsonResults);
//}
waitDialog.removeWaitDialog();
}
if (!ajaxError) {
returnFunction(jqXHR.responseJSON);
}
},
dataType: 'json',
contentType: 'application/json'
});
I tell it to go to http://127.0.0.1/api/parameter, where the parameter is an invalid resource. My API returns in a new tab:
{"errors":[{"id":3,"message":"GET route not defined for /api/parameter"}],data:{}}
I have it returning with a 500 status code because accessing an invalid resource is an error. When I call the actual AJAX, I get jqXHR.responseJSON is null, and jqXHR.responseText is ''.
I have tried using both success: and error: blocks, and tried the complete: because it seemed like my API was resolving the call after the error block had been called, as you can see with the comments.
So I get TypeError: response is null, because my response object is never populated, and the strangest thing is that my call to parameter?parameters=here is never available to inspect in the Network
Since I have control over the API, I changed this specific error to return with status code 501 Not Implemented, instead of 500, and it seems to work. It looks like this was a very unique edge case.

Javascript fetch api with unlimited timeout

I have a web worker with a fetch request that returns an error after some time.
I am not sure if it is because of timeout, but i want it to have un unlimited timeout.
This is my code inside webWorker:
fetch(data.defaults + 'returnSqlRes.php',
{
headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
method: "post",
body: JSON.stringify(data.sql)
})
.then(status)
.then(json)
.then(function (sData) {
var dt={};
dt['o']=data.tableId;
dt['data']=sData;
_.forEach(dt.data[0],function (row) {
row.DT_RowId = composeId(data.pk, row);
_.forEach( data.tableCols,function (o, index) {
if (_.has(o, 'complexList')) {
var fieldName = o.attr.desigColumn ? o.attr.desigColumn : o.attr.name;
var field = o.name;
var keys = returnListKeys(o);
var search = '';
_.forEach( keys, function (name, i) {
if (i < keys.length - 1) {
search += row[name] + '#';
} else {
search += row[name];
}
});
var result = _.find(data.loadedData[getComplexListIndex(o)], {VAL: search});
if (result == undefined) {
row[field] = "";
} else {
row[field] = result[fieldName];
}
}
});
});
self.postMessage(downloadCSV(dt));
The final purpose of code is to download a csv file. The problem is sometimes i have 150k or 200k records and it takes time to parse and a network error is downloaded instead of the file. In tables with less than 100k records everything is ok, file is downloaded.
Came Across this might help https://github.com/github/fetch/issues/175 good luck!

Using fetch library for Wikipedia API - Javascript

I'm developing a Wikipedia Viewer and I'm trying to extract some data from the Wikipedia API. This is supposed to be a normal request, any idea why this method is not giving any response? I'm using fetch library.
The line console.log(data) doesn't run at all.
function getArticleList() {
var searchFor = "";
searchFor = document.getElementById('intext').value;
console.log(searchFor);
fetch("https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchFor + "&limit=5").then(function(resp) {
console.log("trySearch");
return resp.json()
}).then(function(data) {
console.log(data);
document.querySelector.artName.innerText = data.object[1];
document.querySelector.textArt.innerText = data.object[0];
document.querySelector.href = data.object[2]
})
};
From Wikimedia's documentation: 'For anonymous requests, origin query string parameter can be set to * which will allow requests from anywhere.'
The following worked for me:
fetch("https://en.wikipedia.org/w/api.php?&origin=*&action=opensearch&search=Belgium&limit=5").then(function(resp) {
console.log(resp);
return resp.json()
}).then(function(data) {
console.log(data);
Notice that I filled in my own search with 'Belgium', but your code should work with the right modifications.
Any particular reasons to use fetch library ? This can be done using simple Jquery AJAX.
function getArticleList() {
var searchFor = document.getElementById('intext').value;
var response="";
console.log(searchFor);
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=opensearch&search="+searchFor+"&limit=5",
dataType: 'jsonp',
success: function(data){
console.log(data);
response=data;
}
}).done(function(response) {
console.log(response);
document.querySelector.artName.innerText = response.object[1];
document.querySelector.textArt.innerText = response.object[0];
document.querySelector.href = response.object[2];
});
};

How do i make callbacks on functions activated by ng-click in angular?

I'm having trouble getting my email code to finish after the function processing it's data is finished. It's trigger by NG-click on a button but none of the usual callback methods are working.
Angular sends post requests to my express server to be mailed.
function processQuote() {
$http({
method : 'POST',
url : '/send' ,
data : mailJson,
headers: { 'Content-type': 'application/json' }
}).success(function(data){
console.log('success!');
}).error(function(err,data){
console.log(err);
});
};
loops through mixed object/array table and returns mailJson array I will pump into email
$scope.calculateAll = function(callback){
var mailJson = [];
var amount = 0;
$scope.contact.totalQuote = 0;
for (var i = 0; i < $scope.customers.length; i++) {
if( $scope.customers[i].area != 0) {
$scope.customers[i].total = parseInt($scope.customers[i].area, 10) * parseInt($scope.customers[i].price, 10);
$scope.contact.totalQuote += parseInt($scope.customers[i].total);
mailJson.push($scope.customers[i]);
}
}
mailJson.unshift($scope.contact);
callback(mailJson);
};
and the html, ng-click to activate.
<button type="button" ng-click="calculateAll(processform)" class="btn btn-primary">Submit</button>
Your question was little confusing but I got that you want to run block code after response
$http return a deferred promise so what you can do is
function processQuote() {
var promise=$http({
method : 'POST',
url : '/send' ,
data : mailJson,
headers: {
'Content-type': 'application/json'
});
return promise;
};
In your controller
processQuote().then(function(){
//code should run after a response
});

Categories

Resources