How to append/display/render data to page on click - javascript

I want to get the data from the API and display it on my index.html page. What's the best way in doing this? looking for multiple ways, that be jquery or data binding with angular. I can't seem to figure out a function to display the data I get. I'm fetching two different datas from two different players and I want to display them side by side. JSON data is returned by the API
/**Part of Index.html**/
<body ng-app="lolvs" ng-controller="MainController">
<div class="throwdown">
<h1> LoL THROWDOWN </h1>
<div class="summonerNames">
<input id="summonerOne" ng-model="summonerOne" placeholder="summoner name">
<button class="start" ng-click="start()">vs</button>
<input id="summonerTwo" ng-model="summonerTwo" placeholder="summoner name">
</div>
/**app.js**/
(function(){
'use-strict'
var mainCtrl = function mainCtrl($scope, $rootScope, MainFactory) {
$scope.start = MainFactory.start;
$rootScope.$on('gotStats', function (e, m) {
console.log('arguments >>', arguments);
$scope.player1 = {
totalChampionKills : 0,
totalDeathsPerSession : 0,
totalAssists : 0,
totalSessionsWon : 0,
totalSessionsLost :0,
totalMinionKills: 0,
totalTurretsKilled: 0,
};
$scope.apply();
});
};
var mainFactory = function ($http, $rootScope) {
var api = 'api_key=***************************';
var add = function(data, status, headers) {
var stats = {
totalChampionKills : 0,
totalDeathsPerSession : 0,
totalAssists : 0,
totalSessionsWon : 0,
totalSessionsLost :0,
totalMinionKills: 0,
totalTurretsKilled: 0,
};
var champions = data.champions;
for(var i = 0; i < champions.length; i++) {
var champ = champions[i].stats;
for(stat in stats) {
if(champ[stat]) {
stats[stat] += champ[stat]
}
}
}
};
var start = function(name) {
var options = {
url: 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/' + name + '?' + api,
type: 'GET',
success: summonerOption
};
$http(options);
};
var summonerOption = function(data, status, headers) {
var name = Object.keys(data)[0];
var newOption = {
url: 'https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/' + data[name].id + '/ranked?season=SEASON4&' + api,
type: 'GET',
success: add
};
$http(newOption);
};
return {
start: start
}
};
angular.module('lolvs', [])
.controller('MainController', ['$scope', '$rootScope', 'MainFactory', mainCtrl])
.factory('MainFactory', ['$http', '$rootScope', mainFactory])
})();

What kind of data is being returned? If it is a json array, you might want to iterate through it before printing the whole thing to your webpage.
In theory however, you should handle the data after a successful ajax call, which seems to be executed after pressing the <button> in your index.html..
This could look like so:
var newOption = {
url: 'https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/' + data[name].id + '/ranked?season=SEASON4&' + api,
type: 'GET',
success: function(data) {
$('.containerForData').html('<div class="data-wrap">' + data + '</div>');
}
};
Unfortunately your question is not very clear, but I hope this helps.

Related

Cannot show value after AJAX call (ASP.NET MVC)

I have two <p> fields where I need to assign text
Here is html code:
<p id="appId" style="visibility: hidden;"></p>
<p id="calculationId" style="visibility: hidden;"></p>
I make AJAX call like this
$('#openCalculationConsumables').click(function() {
addConsumables();
});
function addConsumables() {
var patientName = $('#patientsId').val();
var finding = $('#findingvalue').val();
var procedure = $('#procedurevalue').val();
var model = {
findingValue: finding,
procedureValue: procedure,
patientId:patientName
}
$.ajax({
url: '#Url.Action("AddIndividualCalculation", "Calculations")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(model),
type: 'POST',
dataType: 'json',
processData: false,
success: function (data) {
$('#masters_data').load('#Url.Action("IndividualCalculationConsumables", "Calculations")', function() {
var list = data;
$('#calculationId').text(list[0].calcid);
$('#appId').text(list[0].appid);
});
}
});
}
And here is my back end code:
public JsonResult AddIndividualCalculation(string findingValue, string procedureValue,int patientId)
{
using (var ctx = new ApplicationDbContext())
{
Calculation calc = new Calculation
{
};
ctx.Calculations.Add(calc);
ctx.SaveChanges();
int calculationId = calc.Id;
Appointment app = new Appointment
{
Calculation_id = calculationId,
FindingContent = findingValue,
ProcedureContent = procedureValue,
Patient_id = patientId
};
ctx.Appointments.Add(app);
ctx.SaveChanges();
int appointmentId = app.Id;
var items = new
{
appid = appointmentId,
calcid = calculationId
};
return Json(items,JsonRequestBehavior.AllowGet);
}
}
I set breakpoint and see , that I have values in items. In console log I have this {appid: 1006, calcid: 1006}
But I cant assign it to <p> and have this error.
Cannot read property 'calcid' of undefined
Where is my problem?
Thank's for help.
$('#masters_data').load('#Url.Action("IndividualCalculationConsumables", "Calculations")', function() {
var list = data;
$('#calculationId').text(list[0].calcid);
$('#appId').text(list[0].appid);
});
list[0] is not defined as you are returning just an anonymous object not a list of objects
new {
appid = appointmentId,
calcid = calculationId
};

Retrieving data from myapifilms.com api

I am following a tutorial on YouTube showing how to get data from the myapifilms.com api and I am having trouble rendering the data to HTML. Currently my ajax call is working and the data is showing in the console. The problem I am having is getting the data to show on the page itself. I searched through the question already asked but had no luck. Here's my js code so far:
$(document).ready(function(){
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody"); //table.find("tbody");
function searchMovie() {
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title="+ title +"&token= + token goes here +&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&quotes=0&fullSize=0&companyCredits=0",
dataType: "jsonp",
success: renderMovies
})
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title);
var plotTd = $("<td>").append(plot);
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I feel like I am so close but can't quite figure what I am missing. Again I was following a tutorial so if there's a better way to accomplish this goal I'm definitely open to suggestions.
Update:
I changed my code to this and I'm getting undefined in the browser. I changed the for loop to this
success: function (movies) {
console.log(movies);
tbody.empty();
for (var m in movies) {
$(".movies").append("<h3>"+ movies[m].title +"</h3>");
$(".movies").append("<h3>"+ movies[m].plot +"</h3>");
}
}
I figured out a solution, instead of using myapifilms, I used the tmdb api instead. Changing my code to this worked:
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = 'myapikey';
//Function to make get request when button is clicked to search
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json.results);
for (var i = 0; i < json.results.length; i++){
var result = json.results[i];
$(".moviesContainer").append('<div class="movies col-md-12">'+
'<img class="poster" src="http://image.tmdb.org/t/p/w500'+ result.poster_path +'" />'
+'<h3>'+ result.title +'</h3>'
+'<p><b>Overview: </b>'+ result.overview +'</p>'
+'<p><b>Release Date: </b>'+ result.release_date +'</p>'
+'</div>');
}
},
error: function(e) {
console.log(e.message);
}
});
});

Not able to obtain value in view (directive)

I have an array in the profile-form.html directive's controller.
But I am neither able to obtain the value of that array (all_languages) nor iterate over it using ng-options in the directive. It's simply printing as string. I am new to Angular and maybe doing everything terribly wrong.
Directive
app.directive("profileForm", function() {
return {
restrict: "E",
templateUrl: "/static/translatorNgApp/profile-form.html",
controller: ['$scope','$http',function($scope, $http) {
this.getCookie = function(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
console.log(cookieValue);
return cookieValue;
};
$scope.csrftoken = this.getCookie('csrftoken');
$scope.myForm={};
$scope.all_languages = ['English', 'Hindi'];
$scope.language_pairs = [];
$scope.getAllLanguages = function () {
$http.get('/getAllLanguages'
).success(function(response) {
// success
$scope.all_languages.concat(response);
}).error(function(response) {
// failed
});
};
$scope.submitForm = function() {
var postData = {
method: 'POST',
url: '/accounts/tprofile/',
// headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
headers: {'X-CSRF-Token' : $scope.csrftoken },
data: $scope.myForm
};
$http(postData)
.then(function(response) {
// success
},
function(response) { // optional
// failed
});
console.log("Form submitted");
// $scope.message = "Sent Successfully 2";
// console.log(postData);
console.log(postData);
console.log($scope.myForm);
};
$document.ready(function(){
console.log("document ready");
$scope.getAllLanguages(); //This can be commented out for the question's sake.
});
}],
controllerAs: "profileFormCtrl"
};
});
Directive Template (profile-form.html)
<div class="form-group" >
<label for="id_source_language">Source language: </label>
<ul>
<li>
<pre>all_languages = {{all_languages | json}}</pre>
<select data-ng-model="source" ng-options="language for language in all_languages" class="form-control" id="id_source_language" name="source_language" placeholder="Source Language" required>
</select>
<button ng-click="language_pairs.pop($index)" aria-label="Remove">Remove</button>
<button ng-click="language_pairs.push({})">Add more pair</button>
</li>
</ul>
</div>
Using document.ready event inside a angular directive doesn't make sense to call specific method of scope. Because document.ready event has already happened after that event only angular started process page.
Ideally to make your code working state you need to remove $document.ready(function(){ .... }); code which isn't required there. And as document.ready is already accomplished, so the one which you had registered from directive wouldn't get call.

Angularjs why this html page(view) does not integrate with Angular

I have an Angularjs site that works. However one html file(view) does not integrate with Angular. The flight fields are not show and the button is not active.
Can anybody help?
<nav class="top-bar" data-topbar="" role="navigation">
<ul class="title-area">
<li class="name"><h1><a ui-sref="client.payment">Pagamento</a></h1></li>
</ul>
</nav>
<div id="sidePanelContent">
<a ui-sref="^" ui-sref-opts="{reload: true}" class="closeSidePanel"><img src="images/admin/botao-fechar.png" alt="Fechar"></a>
<h1>Pagamento do Voo</h1>
<div>
<p ng-show="flight"><strong>Voo:</strong> {{flight.fromairport.name}} ➝ {{flight.toairport.name}}</p>
<p ng-show="flight"><strong>Horário:</strong> {{flight.departure | formatDateTime}}h</p>
<p ng-show="flight"><strong>Lugares disponíveis:</strong> {{flight.availableseats}}</p>
<p ng-show="flight"><strong>Aeronave:</strong> {{flight.airplane.name}}</p>
<p ng-show="flight"><strong>Preço atual:</strong> R$ {{flight.price | formatPrice}}</p>
</div>
<button class="button" ui-sref="client.payment({flight:flightid})" >Pagar com Paypal</button>
---------------- Java script -----------------
'use strict';
/**
* #ngdoc function
* #name flyvipApp.controller:AboutCtrl
* #description
* # AboutCtrl
* Controller of the flyvipApp
*/
angular.module('flyvipApp')
.controller('PaymentCtrl', function ($scope, SharedData, $rootScope, $state, $stateParams, Authorization, $http) {
var api = "http://flyvip.com.br/app/api/";
var userid = Authorization.currentUser().user.id;
$rootScope.sidePanel = false;
SharedData.selectedMenu.setItem('voos');
$scope.menu = SharedData.selectedMenu;
$rootScope.homeClient = false;
$scope.orderedFlights = {data: []};
$scope.flag = false;
var _flightid = _id;
var _airplaneid = $scope.flight.airplane.id;
var _dateofdeparture = $scope.flight.dateofdeparture;
var _dateofarrival = $scope.flight.dateofarrival;
var _airportdeparture = $scope.flight.fromairport.id;
var _airportarrival = $scope.flight.toairport.id;
var _price = $scope.flight.price;
var _seats = $scope.flight.availableseats;
var _status = $scope.flight.flightstatus;
var _reason = $scope.flight.reason;
var flight = {
flightid: _flightid,
airplaneid: _airplaneid,
dateofdeparture: _dateofdeparture,
dateofarrival: _dateofarrival,
airportofdeparture: _airportdeparture,
airportofarrival: _airportarrival,
price: _price,
seats: _seats,
flightstatus: _status,
reason: _reason,
invoicenum: "122344",
passengerid: $scope.passengerid
};
$http({method: "POST", url: api + "DoWriteLog.php",msg:'Entrei neste script!', headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).success(function(response, status, headers, config) {
});
$http({method: "POST", url: api + "DoPayment.php", data: flight, headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).success(function(response, status, headers, config) {
if (response.success) {
$scope.flag = true;
}
else
$scope.flag = false;
})});
You are not assigning flight object to scope try this:
$scope.flight = {
...
}
Also I can see that most of the variables are not declared in that object except flight.fromairport.
I'm not sure where are you getting the data from, but make sure it is assigned to $scope.flight at some point.

HTML table not updating, after pushing new item to knockout observableArray

I am having trouble updating my HTML UI.
When the document load and calls "getAllProducts()", the HTML UI displays all my items and with the right css class for 'styleStatusCss', and the right 'displayName', the problem is that when I try to update my observableArray with a newly updated product (product name or status has changed), the html UI does not update and remains the same
So here is a quick list of what is happening:
getUpdatedProducts() is called every 25 sec, and returns, any product
that has been updated
I check how many products my observable array has: appVM.itemList.length and it does have 100 (as expected!), I also check that the json product that has been sent back has some modified data, and indeed it has changed!
I then create the javascrip obj MyProduct using that product json object
Now I add my newly created javascript obj MyProduct to the observablearray: appVM.itemList.push(newUpdatedProduct);
And finally I check how many items my observablearray has, after doing the push, (and since I cannot see any changes on the HTML UI), and appVM.itemList.length now says 101 !!! How can that be? the HTML UI still displays the data as it was after the initial load
Please see below most of the code
HTML
<table >
<tbody data-bind="foreach: itemList">
<tr>
<td>
<div data-bind="css: styleStatusCss"></div>
</td>
<td>
<div data-bind="text: displayName"></div>
</td>
</tr>
</tbody></table>
And here is the javascript:
<script type="text/javascript">
var appVM;
var initializeItems = false;
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
$(document).ready(function () {
getAllProducts();
});
setInterval(function () {
if (initializeItems) {
getUpdatedProducts();
}
}, 25000);
function getAllProducts() {
var url = '#Url.Action("_AllProducts", "Home")';
$.ajax({
url: url,
type: 'GET',
dataType: 'JSON',
})
.success(function (result) {
initializeItems = true;
appVM = new AppViewModel();
var mappedProducts = ko.utils.arrayMap(result.ItemList, function (item) {
var con = new MyProduct(item);
return con;
});
appVM.itemList = mappedProducts;
ko.applyBindings(appVM);
})
.error(function (xhr, status, error) {
alert("FATAL ERROR");
})
}
function getUpdatedProducts() {
var url = '#Url.Action("_UpdateProducts", "Home")';
$.ajax({
url: url,
type: 'GET',
dataType: 'JSON',
})
.success(function (result) {
if (result.HasNewData) {
alert("we have some data");
alert("START COUNT: " + appVM.itemList.length); //this shows all my 100 products -> START COUNT: 100
alert("Number of new items: " + result.ItemList.length); // i only get one product back for easy debugging
for (index = 0; index < result.ItemList.length; ++index) {
var updatedProdJson = result.ItemList[index]; //get the json for the product
alert("New prod json: " + objToString(updatedProdJson)); //just for debugging print out in a readable format
var newUpdatedProduct = new MyProduct(updatedProdJson);//create our MyProduct object (which has all properties as observable)
appVM.itemList.push(newUpdatedProduct); //add our new MyProduct to the list
alert("FINAL COUNT: " + appVM.itemList.length); // --> FINAL COUNT: 101
}
}
})
.error(function (xhr, status, error) {
alert("Error: " + status);
})
}
function AppViewModel() {
var self = this; //so it references the viewModel object
self.itemList = ko.observableArray([]);
self.doAlert = function () {
alert("HERE");
}
}
function MyProduct(data) {
//alert("DATA: " + objToString(data));
this.Id = ko.observable( data.Id);
this.Name = ko.observable(data.Name);
this.status = ko.observable(data.Status);
this.displayName = ko.computed(function () {
var fullnmae = this.Id() + " " + this.Name();
return fullnmae;
}, this);
this.styleStatusCss = ko.computed(function () {
var pStatus = 'divstatusnone';
if (this.status() === 'H')
pStatus = 'divlowstatus';
if (this.status() === 'D')
pStatus = 'divhighstatus';
return pStatus;
},this);
}
function objToString (obj) {
var str = '';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += p + '::' + obj[p] + '\n';
}
}
return str;
}
Hope somebody can tell me where i went wrong.
Many thanks,
in getAllProducts, you're assigning the results to itemList, losing your observable array:
appVM.itemList = mappedProducts;
you need to do this instead:
appVM.itemList(mappedProducts);

Categories

Resources