AngularJS Iterate over ajax returned object - javascript

I am writing a program to learn AngularJS. This program has an ajax function that returns an object from an API endpoint, like so:
$.ajax(
{
url: "/api/request.json",
dataType: "json",
statusCode: {
404: function(){
console.log("Error 404");
}
},
success: function(data){
console.log("Successfully copied data to meteo_values");
fn(data); // do something with the data
},
error: function(err){
console.log(err);
}
}
);
I would like to iterate through the object that is returned using AngularJS. Right now I'm using jQuery to inject the data inside a div, like so:
function fn(val){
// populate the webpage with the values
var data_table = "<div class='data_table'><p>" + datetext + "</p>";
// iterate through val array
for (var value in val){
data_table += "<div class='card'><h2>" + val[value]["city"] + "</h2>";
data_table += "<table><tr><th>Orario</th><th>Temperatura</th><th>Umidità</th></tr>";
data_table += "<tr><td>" + val[value]["t1"]["ora"] + "</td><td>" + val[value]["t1"]["temperatura"] + "</td><td>" + val[value]["t1"]["humidity"] + "</td></tr>";
data_table += "<tr><td>" + val[value]["t2"]["ora"] + "</td><td>" + val[value]["t2"]["temperatura"] + "</td><td>" + val[value]["t2"]["humidity"] + "</td></tr>";
data_table += "<tr><td>" + val[value]["t3"]["ora"] + "</td><td>" + val[value]["t3"]["temperatura"] + "</td><td>" + val[value]["t3"]["humidity"] + "</td></tr>";
data_table += "</table></div>";
}
data_table += "</div>"
$(".results").append(data_table);
}
Instead of doing that (which works, but it doesn't seem elegant), I would like to use AngularJS. I tried using ng-repeat but It didn't work out.
Consider that the returned object is an object that contains an array of n objects which also contain another set of three objects.
I already tried ng-repeat="(key,value) for name_of_the_variable_in_the_$scope"
I might have forgot useful info for you to help me and answer and I already searched for the answer but I didn't find it.
EDIT:
var meteoApp = angular.module('meteoapp', []);
meteoApp.controller('meteoPopulateCtrl', function ($scope) {
$scope.data = [];
$.ajax(
{
url: "/api/request.json",
dataType: "json",
statusCode: {
404: function(){
console.log("Error 404");
}
},
success: function(data){
$scope.data = data;
},
error: function(err){
console.log(err);
}
}
);
HTML MARKUP
<div ng-app="meteoapp">
<div ng-controller="meteoPopulateCtrl">
<div class="results" ng-repeat="???">
something that is repeated
</div>
</div>
</div>
RETURNED OBJECT (To be prettified)
[
{
"city":"a city",
"t1":
{
"ora":"01",
"temperatura":"7.2°",
"humidity":"92%"},
"t2":
{
"ora":"04",
"temperatura":"7.1°",
"humidity":"93%"},
"t3":
{
"ora":"07",
"temperatura":"7.4°",
"humidity":"94%"
}
}]

If your code is in angularjs, you should use ng-repeat for displaying it on html page.
Here is the basic example of ng-repeat:
HTML:
<h3>FIFA Mactch Summary:</h3>
<div ng-app ng-controller="MyCtrl">
<ul>
<li ng-repeat="(country,goals) in items">{{country}}: {{goals}}</li>
</ul>
</div>
Javascript:
var m = {
"India": "2",
"England": "2",
"Brazil": "3",
"UK": "1",
"USA": "3",
"Syria": "2"
};
function MyCtrl($scope) {
$scope.items = m;
}
Working example
For ajax request you should be using $http because $http callbacks are all wrapped in $scope.$apply(). Else you need to call $scope.$apply() which will call $scope.$digest() for you.

ng-repeat will do the job - you need to remember to refresh the scope before asynchronously loaded content will be displayed. Try $scope.$apply() after receiving the response and the ng-repeat should pick it up.
Hope this helps.

Related

How to render multiple value inside single Colum in datatable

This is my render code function which is working
{
"data": "assignedTo",
"render": function (data) {
var btnDetail = "<a href='/Ticket/TicketDetail?ticketId=" + data + "'>" + data + "</a>";
return btnDetail;
}
},
However I want something like
var btnDetail = "<a href='/Ticket/TicketDetail?ticketId=" + data + "'>" + data + "</a>";
where user can see assignedTo but when they click it should got to the ticketId. In short i want both ticketId and assignedTo value in single colum. Please guide me.
You need to make use of row parameter from render function. It contains all values available for current row.
row The full data source for the row (not based on columns.data)
Read more about column rendering here.
{
data: 'assignedTo',
render: function (data, type, row) {
var btnDetail = "<a href='/Ticket/TicketDetail?ticketId=" + row.TicketId + "'>" + data + "</a>";
return btnDetail;
}
}
or you can ignore data completely if you want to use render function.
{
data: null,
render: function (data, type, row) {
var btnDetail = "<a href='/Ticket/TicketDetail?ticketId=" + row.TicketId + "'>" + row.assignedTo + "</a>";
return btnDetail;
}
}
All other values returned from server will be available through row parameter.

how to display JSON Array into table using AJAX in JSP

I am new to ajax. I am trying to display data into table in JSP file.
API is called using AJAX.
Controller pass below response:
BatchwiseStudent [name=Ram, course=MCA (Commerce), emailId=rammansawala#gmail.com, placed=null, batch=2016, mobileNo=7.276339096E9]
In JSP page:
<script type="text/javascript">
function getStudentDetails(){
$batch = $('#batch');
$course = $('#course');
$.ajax({
type: "GET",
url: "./batchAjax?batchId="+$batch.val()+"&courseId="+$course.val(),
success: function(data){
console.log("SUCCESS ", data);
if(data!=null){
$("#batchwiseTable").find("tr:gt(0)").remove();
var batchwiseTable = $("#batchwiseTable");
$.each(JSON.parse(data),function(key,value){
console.log(key + ":" + value);
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['name']);
rowNew.children().eq(2).text(value['emailId']);
rowNew.children().eq(3).text(value['placed']);
rowNew.children().eq(4).text(value['batch']);
rowNew.children().eq(5).text(value['mobileNo']);
rowNew.appendTo(batchwiseTable);
});
$("#batchwiseTable").show();
}
},
error: function(e){
console.log("ERROR ", e);
}
});
}
</script>
I can see new row into the table but there is no data. I want name, emaild, mobileNo, etc into particular field.
can anyone guide me where am i wrong?
Below code should be keep in the .jsp Page where you show table you don;t need to write html code for table jsp page.
<div id="insert-table-here"></div>
Javascript code:
below code is for ajax call
replace uri with your url value that is used in your url.
$.ajax({
type: 'GET',
url: uri,
success: function (data) {
var str = '<table class="table table-bordered"><thead>'+
'<tr><td>Name</td><td>Course</td><td>EmailId</td><td>Place</td><td>Batch</td><td>Mobile Number</td></tr></thead><tbody>';
$.each(data, function (key, value) {
str = str + '<tr><td>' +
value.name + '</td><td>' +
value.course + '</td><td>' +
value.emailId + '</td><td>' +
value.placed + '</td><td>' +
value.batch + '</td><td>' +
value.mobileNo + '</td></tr>';
});
str = str + '</tbody></table>';
$('#insert-table-here').html(str);
}, error: function (data) {
}, complete: function (data) {
}
});

Run a function when element rendered

I have a javascript function, for example:
function SuperTD(id,str,tooltip) {
return '<td id="' +id+ '" title="' +tooltip+ '">' +str+ '</td>';
}
The SuperTD called and concatenated with many elements, and I don't want to change how it works (into generating element without using html string).
And I need to trigger a function when that elements are rendered, for example:
function SuperTD(id,str,tooltip) {
var onwhat = 'onwhat="executeFixedFunction(' + "'" +id+ "'" + ')"';
return '<td><div id="' +id+ '" title="' +tooltip+ '" ' +onwhat+ '>' +str+ '</div></td>';
}
where executeFixedFunction is:
function executeFixedFunction(id) {
$('#' + id).uploadFile({
url:"/file/upload"
});
}
what the correct event to do this? I need to initialize a file-upload element everywhere SuperTD called
The users still using Firefox 3.5.
EDIT more context:
GridBuilder.render = function() {
// return from cache
var html = '';
// calls html += SuperTD( ... )
return html;
}
GridBuilder.renderTo = function(id) {
$('#'+id).html(this.render());
// I guess this is where I should initialize the file upload, but still, is there another way?
}
If you are already using jquery i would consider doing it this way:
function superTD (id, str, tooltip) {
return $('<td/>', {
id: id,
title: tooltip,
text: str
}).uploadFile({
url: '/your-url'
})
}
Then you can call appendTo method on superTD to insert it into table row
You can use a setTimeout function to delay the callback function.
function SuperTD(id,str,tooltip) {
var onwhat = 'onwhat="executeFixedFunction(' + "'" +id+ "'" + ')"';
setTimeout(function(){ executeFixedFunction(id) }, 1000);
return '<td><div id="' +id+ '" title="' +tooltip+ '" ' +onwhat+ '>' +str+ '</div></td>';
}
Everything put together with slightly modified Jakubs suggestion. See on Plunkr.
function superTD(id, str, tooltip, callback) {
var td = $('<td/>', {
id: id,
title: tooltip,
text: str
});
var up = $('<span/>'); // <-- this elm will be replaced
td.append(up);
$('#container').append(td);
callback(up, str);
}
function onCreated(elm, fname) {
elm.uploadFile({
url: '/url',
fname: fname
});
}
$(document).ready(function() {
superTD(1, 'foo', 'bar', onCreated);
superTD(2, 'bar', 'foo', onCreated);
});

Undefined is not a function (AJAX, PHP, jQuery)

I am very new to jQuery and AJAX so I apologise if I am being stupid.
I am receiving an error in my AJAX jQuery script.
I am retrieving data via AJAX get to display dynamically on my page.
The JSON file returns an array which must be iterated and displayed in a DIV for each item.
The JSON is:
[{"id":1,
"user_id":14,
"title":"The Title",
"thumbnail":"image.jpg",
"summary":"summary of post",
"content":"content info here",
"category":"Graphic Design",
"sub_category":"Adobe Photoshop",
"views":0,
"published":0,
"created_at":"2015-04-16 00:09:57",
"updated_at":"2015-04-16 00:09:57"}, {and so on...}]
The jQuery is:
function retrieveTutorials()
{
$.ajax({
type: "GET",
url: "/tutorials/retrieve",
dataType: "json",
success: function(data){
var tutorial = ('')
$.each(data, function(){
tutorial.append($( '<div class="generatedbox"><img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p></div>'))
});
$("#generated-content").empty().append(tutorial);
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
}
The error I am currently receiving is "Uncaught TypeError: undefined is not a function" which refers to the following section
tutorial.append($( '<div class="generatedbox"><img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p></div>'))
Any ideas as to where I am going wrong?
I have used very similar code before which worked fine
try this
var tutorial = $('<div></div>');
You should select any DOM Element and assign it to tutorial variable, something like this:
var tutorial = $('someCSSselector');
There is an error because you are calling .append() on (''). .append() is a jQuery function, but ('') is an empty string, not a jQuery object.
You can do this:
var tutorial = $('<div>');
...
$("#generated-content").empty().append(tutorial.html());
You should define your div object first, and you can keep generatedbox class when defining it. Then, you can omit the div that you had in the appended content.
var tutorial = $('<div class="generatedbox">')
$.each(data, function(){
tutorial.append($('<img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p>'))
});

How to call Rails form helper with params in jQuery AJAX?(SUPER SIMPLE)

I'm new on Rails, and i think this is super simple, just not used to the syntax.
this is the jQuery part,
$.ajax({
type: "get",
contentType: "application/json; charset=utf-8",
url: "/users/search_users",
data: {
name: name
},
dataType: "text",
success: function (result) {
var test = "<%=get_user_list_html(result)%>";
if (result == "User not found") {
alert("User not found");
} else {
//console.log(result);
var peopleData = jQuery.parseJSON(result);
var resultHTML = "<tr>";
resultHTML += "<th></th><th style='display:none'>User ID</th>" + "<th>First Name</th><th>Last Name</th><th>Email Address</th>" + "<th style='display:none'>Time Zone</th>";
resultHTML += "</tr>";
$.each(peopleData, function (index, obj) {
resultHTML += "<tr>";
resultHTML += "<td><input type='checkbox'></td>" + "<td style='display:none;'>" + obj.id + "</td>" + "<td>" + obj.firstname + "</td>" + "<td>" + obj.lastname + "</td>" + "<td>" + obj.email + "</td>" + "<td style='display:none;'>" + "Etc/GMT+9 (Japan)" + "</td>";
//consider now
resultHTML += "</tr>";
});
$("#internal_table").html(resultHTML);
}
},
error: function () {
window.alert("something wrong!");
}
});
in here, i'm going to call get_user_list_html, which is in the helper.
But my problem is, how can i use the result from the respone, i have to send this as a param?
if i just put it like that, it says undefined var.
Ruby code must be executed on the server side, this line: var test = "<%=get_user_list_html(result)%>"; won't work after an ajax call, and it should be in a .erb file.
You can have a ruby + javascript view template with .js.erb extension but ruby code is always executed before your document loads.
I don't know what the helper does but this is not the way to do it.
Solution 1: Render a HTML partial instead of JSON from server. That's make things much easier in you case.
Solution 2: Use a template to render JSON response, say jQuery template or Underscore template.
The usage in your case is not good. You missed better part in both server and client side.

Categories