Display json data in angular - javascript

I have a post that runs on page load. I am trying to get data objects in json to use on my page and in my controller so I am trying to store the value in Angular scope.
I do not know where I have gone wrong but I cant get the value and when I console.log I get
angular.js:11655 ReferenceError: data is not defined
I want to store
c_name
max_slots
base_image
Summery of what I need
I need my array objects listed above stored in scope variables so that I may use them in my html and else where in my JavaScript controller.
My json
{data: Array(1), status: 200, config: {…}, statusText: "OK", headers: ƒ}
config
:
{method: "POST", transformRequest: Array(1), transformResponse: Array(1), url: "http://www.site.co.uk/one/two/getdata", date: {…}, …}
data
:
Array(1)
0
:
c_name
:
"ben"
d_text
:
[]
max_slots
:
2
resolution
:
(2) [1920, 1080]
slots
:
Array(3)
0
:
{path_image: "", base_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…O7/aaFdrXd6na2UApSIJEwod/rWVlSUUk2h2Gbknfi6P/2Q==", slot_id: 1}
1
:
{path_image: "", base_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…O7/aaFdrXd6na2UApSIJEwod/rWVlSUUk2h2Gbknfi6P/2Q==", slot_id: 2}
2
:
{path_image: "", base_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…O7/aaFdrXd6na2UApSIJEwod/rWVlSUUk2h2Gbknfi6P/2Q==", slot_id: 3}
length
:
3
__proto__
:
Array(0)
__v
:
0
_id
:
"59c92d6f45b79c8c110ee6ab"
__proto__
:
Object
My script I am trying to get the data
My JavaScript
$scope.GetData = function () {
$http({
url: "http://www.site.co.uk/one/two/getdata",
method: "POST",
date: {},
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
// success
console.log('you have received the data ');
console.log(response);
// $scope.base_image = response.base_image; $scope.c_name = response.c_name;
$scope.c_name = data.c_name;
$scope.max_slots = data.max_slots;
$scope.slot_image = data.slots.base_image;
console.log($scope.c_name);
}, function (response) {
// failed
console.log('failed getting campaigns goo back to log in page.');
console.log(response);
});
};
$scope.GetData();
Full response from console.log(data);
you have received the data
{data: Array(1), status: 200, config: {…}, statusText: "OK", headers: ƒ}
config
:
{method: "POST", transformRequest: Array(1), transformResponse: Array(1), url: "http://www.site.co.uk/one/two/getdata", date: {…}, …}
data
:
Array(1)
0
:
c_name
:
"ben"
d_text
:
[]
max_slots
:
2
resolution
:
(2) [1920, 1080]
slots
:
[{…}]
__v
:
0
_id
:
"59c92d6f45b79c8c110ee6ab"
__proto__
:
Object
length
:
1
__proto__
:
Array(0)
headers
:
ƒ (c)
status
:
200
statusText
:
"OK"
__proto__
:
Object
And a screen shot

I understood as you have to print JSON data for that I'm posting this answer, if you not expect this answer please post your question more clearly.
$scope.GetData = function () {
$http({
url: "http://www.site.co.uk/one/two/getdata",
method: "POST",
date: {},
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
// success
console.log('you have received the data ');
console.log(response); // if the response data is in json
console.log(angular.toJson(response)); // if the response data is in json
// $scope.base_image = response.base_image; $scope.c_name = response.c_name;
$scope.c_name = response.c_name;
$scope.max_slots = response.max_slots;
$scope.slot_image = response.slots.base_image;
console.log($scope.c_name);
}, function (response) {
// failed
console.log('failed getting campaigns goo back to log in page.');
console.log(response);
});
};
$scope.GetData();

$scope.GetData = function () {
$http({
url: "http://www.site.co.uk/one/two/getdata",
method: "POST",
date: {},
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
// success
var data = JSON.parse(response);
console.log('you have received the data ');
console.log(data);
// $scope.base_image = response.base_image; $scope.c_name = response.c_name;
$scope.c_name = data.c_name;
$scope.max_slots = data.max_slots;
$scope.slot_image = data.slots.base_image;
console.log($scope.c_name);
}, function (response) {
// failed
console.log('failed getting campaigns goo back to log in page.');
console.log(response);
});
};
$scope.GetData();
Replacing response with data should fix the issue.

Related

PHP if (isset) JavaScript equivalent

I have a problem here, I want to create conditions like if (isset) in PHP, but after ajax response
the response received here is like this if it is empty:
(2) [Array(0), Array(0)]
0: []
1: []
length: 2
and like this if there is data:
0: {description_content: "mnadmnsa", course_content1: "madmna", course_content2: "mmnsadm", course_content3: "msadn", …}
1: {course_content1: "madmna", course_content2: "mmnsadm", course_content3: "msadn", course_content4: "msandm"}
length: 2
I have tried with the empty method but an error:
empty is not defined
This is my code:
$.ajax({
type : "get",
url : url,
success:function(data){
if (empty (data[0]) !=null) {
console.log('has data');
}else{
console.log('data');
}
}
Just remove the empty() function, as that is invalid JS. With that said, here is you adjusted code:
$.ajax({
type: 'get',
url: url,
success: function (data) {
if (data[0] != null) {
console.log('has data');
} else {
console.log('does not have data');
}
}
});

Javascript not showing notification from GET springboot rest api

I am totally new to javascript . I just want to show a notification using notify.js when a button is clicked.
Following is my RestController code:
#RequestMapping(value = "/checkCurrentBranch" , method=RequestMethod.GET)
public String checkCurrectGitBranch(Model model, HttpServletResponse response) {
String branchName = "";
GitInfo gitInfo = new GitInfo();
JsonFactory factory = new JsonFactory();
String json = apiService.readGitProperties();
ObjectMapper mapper = new ObjectMapper(factory);
JsonNode rootNode;
try {
rootNode = mapper.readTree(json);
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
while (fieldsIterator.hasNext()) {
Map.Entry<String, JsonNode> field = fieldsIterator.next();
if (field.getKey().toString().equalsIgnoreCase("git.branch")) {
branchName = field.getValue().toString();
adminAppLogger.info("Current Branch name :: "+branchName);
}
}
} catch (IOException e) {
adminAppLogger.error("Error while getting current Git branch :" + e);
branchName = "Error while fetching branch name";
}
model.addAttribute("res", branchName);
return branchName;
}
Following is my js code:
$('#gitBranch').click(function(res) {
/* <![CDATA[ */
var path = /* [[#{/}]] */'checkCurrentBranch';
/* ]]> */
$.notify(res, "info");
console.log(res);
});
I think I am missing some points but I am stuck. Any suggestions?
I tried using axios following is my js:
$('#gitBranch').click(function(res) {
/* <![CDATA[ */
var path = /* [[#{/}]] */'checkCurrentBranch';
/* ]]> */
axios({
method:'get',
url:path,
responseType:'json'
})
.then(function (response) {
console.log(response)
$.notify(data,"info")
});
});
Following response I get on brwoser console. Now I just want that data field to be shown as notification :
{data: "qc_mediaworker_details", status: 200, statusText: "", headers: {…}, config: {…}, …}
config
:
{adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data
:
"qc_mediaworker_details"
headers
:
{pragma: "no-cache", date: "Sun, 04 Nov 2018 05:59:32 GMT", x-content-type-options: "nosniff", x-frame-options: "DENY", content-type: "application/json;charset=UTF-8", …}
request
:
XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status
:
200
statusText
:
""
__proto__
:
Object
You need to properly use data key in axios response block.
axios({
method:'get',
url:path,
responseType:'json'
})
.then(function (response) {
console.log(response)
$.notify(response.data,"info")
});
In above code, I replaced data by response.data
, because according your give code, data is not declared, that means its undefined. So if you mean data to that data which you get in axios response, then you need to access data by $.notify(response.data,"info") instead of $.notify(data,"info")
You don't have anywhere http request.
I recommend you using axios (because it's simple)
Sample code:
axios.get('host:port/checkCurrentBranch')
.then(response => {
// do what you want to do
})
.catch(error => {
// do something if an error occurs
})

Using json objects retrieved by post angular

I have a post that posts on page load. it returns json. how do i then use this json on the page to display images and text based on the object.
is there a way to hold the value of the objects in scope in angular
My post on page load
$scope.GetData = function () {
$http({
url: "http://www.somepage.co.uk/page/page2/objects",
method: "POST",
date: {},
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
// success
console.log('you have received the data ');
console.log(response);
}, function (response) { // optional
// failed
console.log('failed getting campaigns goo back to log in page.');
console.log(response);
});
};
$scope.GetData();
I would like if I could store the objects in different scopes so that I may use them on the page.
Thanks
UPDATE
here is the object I need to turn into scopes
data
:
Array(1)
0
:
c_name
:
"ben"
d_text
:
[]
max_slots
:
2
resolution
:
(2) [1920, 1080]
slots
:
Array(3)
0
:
{path_image: "", base_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…O7/aaFdrXd6na2UApSIJEwod/rWVlSUUk2h2Gbknfi6P/2Q==", slot_id: 1}
1
:
{path_image: "", base_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…O7/aaFdrXd6na2UApSIJEwod/rWVlSUUk2h2Gbknfi6P/2Q==", slot_id: 2}
2
:
{path_image: "", base_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…O7/aaFdrXd6na2UApSIJEwod/rWVlSUUk2h2Gbknfi6P/2Q==", slot_id: 3}
length
:
3
__proto__
:
Array(0)
__v
:
0
_id
:
"59c92d6f45b79c8c110ee6ab"
Inside the then callback, you have to save the returned data into your $scope :
$scope.GetData = function () {
$http({
url: "http://www.somepage.co.uk/page/page2/objects",
method: "POST",
date: {},
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
// success
$scope.data = response; // Save the returned data into your $scope
console.log('you have received the data ');
console.log(response);
}, function (response) { // optional
// failed
console.log('failed getting campaigns goo back to log in page.');
console.log(response);
});
};

AngularJS - $http missed specific key from request Payload

I'm using angular 1.5.7, and no idea why It's missing that key. Frequency of that bug is really low.
Server side rarely get post Request Payload without "priceMin":
expected:
{priceMin: 0, priceMax: 964, category: "", name: ""}
what I've get:
{priceMax: 964, category: "", name: ""}
function _doRequestPOST(request_url, data) {
var def = $q.defer(),
request = {
headers: {
'X-Requested-With' :'XMLHttpRequest'
},
method : 'POST',
url : request_url,
data : data
};
http = $http(request).then(
function(response){
//success
def.resolve(response);
},
function(response){
//error
def.reject(response);
}
);
delete http;
return def.promise;
};
this.sendStats = function(){
var requestData = {
priceMin: self.priceRange.min,
priceMax: self.priceRange.max,
category: self.filterExterior,
name: self.searchBot.name
};
_doRequestPOST('/saveFilterData', requestData);
}
};

How to post data with angular js to sql server

Thanks for all your input, but now I have more or less a similar problem, I have the data that needs to be stored in sql-server database, when I try to post it the data does not get written. Is my code structure correct?
self.CurrentDowntimeEvent = {
method: 'POST'
, url: 'someurl/test'
, data: {
DepartmentId: cookie
, CategoryId: -1
, Comment: ""
, DowntimeStart: "2014-07-07T10:00:00"
, DowntimeEnd: null
}
, headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function (data) {
console.log(data);
}).error(function (data) {
});
$http is a service which should be injected into the controller, so you shouldn't need self. to reference it:
self.RecordsSave = function () {
for (var i = 0; i < self.Employees.length; i++) {
var employee = self.Employees[i];
var params = {
CompanyNumber: employee.ClockNumber,
Department: employee.DepartmentID,
Present: employee.Present,
Reason: employee.AbsentCode
};
$http.post(SAVE_EMPLOYEERECORDS, {
params: params
}).success(function (data) {
alert("testing");
});
}
};

Categories