I have a JSON response, one that I can't figure out. Here is my current response that I receive.
This is my ajax script:
<script>
$(document).on('click', '#pullDetails', function() {
$.ajax({
type:'POST',
url: '/carrier/claims/pullDetails',
data: {
num: $('input[name=proNumber]').val(),
_token: $('input[name=_token]').val()},
dataType: 'json',
success: function(data) {
if(data.details != undefined) {
console.log('success');
console.log(data.details.SearchResults[0].Shipment.Origin.Name); //result: ATLAS INTL
$('#carrierReturnData').html(data.details.SearchResults[0].Shipment.Origin.Name);
}else{
console.log('failed');
console.log(data);
console.log(data.details.SearchResults.SearchItem);
}
},
error: function(data) {
console.log('error');
console.log(data);
}
});
});
</script>
Now my question is how would I get the specific data from the line "SearchItem" (on the first line of the response json)?
At the moment I get the following: TypeError: data.details.SearchResults is undefined, but data.details is recognized as my console logs "success."
Do a JSON.parse of details and then try to log SearchResults
var results = JSON.parse(data.details);
console.log(results.SearchResults.SearchItem);
Related
I make a API call to Wordpress with Angular:
angular.module('assetApp.services',[])
.factory('Asset', function($resource, $cacheFactory) {
var assetsCache = $cacheFactory('Assets');
var res = $resource('/wp-json/wp/v2/assets?&tags=:tags&posts_per_page=40&page=:page', {
'get': { method:'GET', cache: assetsCache, isArray:true },
'query': { method:'GET', params:{}, cache: assetsCache, isArray:true }
});
return res;
}).factory('Category', function($resource) {
return $resource('/wp-json/wp/v2/asset_category/', {
'get': { method:'GET' },
});
});
an become in the console the follow error:
angular.min.js?ver=1539242296:2920 SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
If i test the API with a Rest API tool it returns a valid JSON.
try adding responseType: 'text'
$resource('/wp-json/wp/v2/asset_category/', { 'get': { method:'GET', responseType:
'text' } })
There is a error while parsing JSON, your JSON is not correct if you wants to you can check your JSON format at
JSON Viewer
else you can check your json format by installing json viewer chrome extension
I am trying to pass a variable through AJAX to an API. Here is the angular controller:
$scope.register = function() {
_.each($scope.photos, function(images) {
$upload.upload({
url: '/api/indorelawan/timaksibaik/register/upload-images',
method: 'POST',
data: {},
file: images
})
.success(function(data) {
$scope.team.photos.push(data.result.path);
})
});
$http({
method : 'POST',
url : '/api/indorelawan/timaksibaik/register',
data : $.param($scope.team),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data) {
if (!data.success) {
...
}
else {
...
}
});
}
I tried console.log the $scope.team.photos before it calls the /register API. It displays the data perfectly. But when /register API is runned, the $scope.team.photos is not included. Here is the API:
/*Register Tim Aksi Baik*/
apiRouter.post('/timaksibaik/register', function(req, res) {
// TODO: Create new value to access general statistics data, e.g.: response time.
console.log(req.body);
var team = new GoodActionTeam();
_.each(req.body, function(v, k) {
team[k] = v;
});
team.created = new Date();
team.save(function(err, data) {
if (err) {
res.status(500).json({
success: false,
message: "Gagal menyimpan data organisasi baru.",
system_error: "Error while saving organization data: " + err.message
});
}
else {
res.status(200).json({
success: true,
message: "Organisasi Berhasil Dibuat",
result: data
});
}
});
});
The output of the req.body is only:
{ logo: '/uploads/user_avatar/register/2018-1-14_18:18:3.png',
name: 'ererr',
url_string: 'ererr',
description: 'dfdfd',
focuses: [ '549789127e6a6e2c691a1fc0', '549789127e6a6e2c691a1fc0' ] }
It looks like the $scope.team.photos is not included when the data is passed to the API. What went wrong?
The $upload.upload() is async and by the time you make a post with $scope.team there is no guarantee that all the upload success callbacks have been completed
I'm new to node and angular script. I'm having a function readDetails within my service which gives a GET request.
this.readDetails = function() {
return $http({
method: 'GET',
url: '/getDetails'
}).then(function(data) {
return data;
});
}
Given below is my server side code.
app.get('/getDetails', function(request, response) {
fs.readFile('details.json', 'utf8', function(err, data) {
if (err) throw err;
var obj = JSON.parse(data);
response.send(obj);
response.end();
})
})
I don't get the response from the server. I do not find Why. Suggestions are welcome
OK, I'm stumped. I have an angular json GET process that is pulling results in as expected but I can't seem to parse and get to individual values of the result.
Here is the string result I'm getting:
{"result":[{"sys_id":"f4425c21ec0970407e85e2a57ceff437","number":"INC0035062"}]}
And here is my code:
$http({
method:'GET',
url:$scope.url,
transformResponse: undefined}).then(function(response) {
console.log(response.data);
}).catch(function(response) {
console.error('Error', response.status, response.data);
})
.finally(function() {
console.log("All Done");
});
SO, how can I get to an individual value of a sys_id?
Thanks in advance,
DP
*******EDIT:
Sajeetharan, still having an issue. Changed code per your example:
console.log(response.data);
$scope.data = response.data.result;
console.log($scope.data);
console.log("Sys id is:"+$scope.data[0].sys_id);
Output:
{"result":[{"sys_id":"f4425c21ec0970407e85e2a57ceff437","number":"INC0035062"}]}
undefined
TypeError: Unable to get property '0' of undefined or null reference
at Anonymous function (******.EvScripts.jsdbx:59:3)
at Anonymous function (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:130:399)
at m.prototype.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:145:96)
at m.prototype.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:142:165)
at m.prototype.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:145:399)
at l (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:97:248)
at K (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:101:373)
at y.onload (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:102:397)
Error undefined undefined
If you want to access sys_id, access the 0th index of the array data,
$http.get('test.json').then(function(response){
$scope.data = response.data.result;
});
If you want to access the sys_id using expression,
In Html
<div ng-controller="ListCtrl">
<h1> Sys id is :{{data[0].sys_id}} </h1>
</div>
If you want to access the sys_id using controller,
$http.get('test.json').then(function(response){
$scope.data = response.data.result;
console.log("Sys id is:"+$scope.data[0].sys_id);
});
DEMO
This is what ended up working, via angular.fromJson:
//CALL TO REST SERVICES
//---------------------
$http({
method:'GET',
url:$scope.url,
transformResponse: undefined}).then(function(response) {
console.log(response.data);
$scope.data = angular.fromJson(response.data);
console.log($scope.data['result'][0].sys_id);
}).catch(function(response) {
console.error('Error', response.status, response.data);
})
.finally(function() {
console.log("All Done");
});
//---------------------
I am trying to make a post request through Angular. My code looks as follows,
Javascript Code looks like:
GET:
$scope.getRecord = function() {
debugger;
$http({
method: 'GET',
url: 'SomeURL'
}).then(function(response) {
debugger;
$scope.mainEntity = response.data.anEntity;
}, function(error) {
$scope.content = "something went wrong"
});
};
Post:
$scope.save = function() {
debugger;
var body = JSON.stringify({
"xyzaa": $scope.value.xyzaa || "One fielfd of its",
"xyzbb": $scope.value.xyzbb || One fielfd of its,
"xyzcc": $scope.value.xyzcc || "One fielfd of its",
"xyzaaa": $scope.value.xyzaaa || "One fielfd of its"
});
var request = {
method: 'POST',
url: 'Some URL',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
data: body
};
$http(request).then(function (result) {
debugger;
$scope.getRecord();
}, function (error) {
debugger;
console.log(error)
alert("error")
})
};
Well, I can see that the post request returns the data that I have done in a JSON Format, yet am receiving the error:
POST http://localhost:xyz/xyz/a (Unprocessable Entity)
Object {data: Object, status: 422, config: Object, statusText: "Unprocessable Entity"}.
I can see that data that am being posting is getting in the data key and I can see the data that I have passed, yet I get this error and it doesnt change in the api