heres my code
var readAll = function () {
$.ajax(
{
url: _spPageContextInfo.webServerRelativeUrl +
"/_api/web/lists/getByTitle('PhoneBook')/items/" +
"?$select=Id, Title, pb_FirstName, pb_PhoneNumber" +
"&$orderby=Title,pb_FirstName, pb_PhoneNumber",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (data) {
console.log(data);
},
error: function (err) {
alert(JSON.stringify(err));
}
}
);
};
$(document).ready(function () {
readAll();
});
data = {
"d": {
"results": [{
"__metadata": {
"id": "b4d773a6-f31e-442d-8974-38c535d491d6",
"uri": "mysite:6555",
"etag": "\"1\"",
"type": "SP.Data.LST_x005f_PhoneBookListItem"
},
"Id": 1,
"Title": "name11",
"pb_FirstName": "name",
"pb_PhoneNumber": "1234",
"ID": 1
}]
}
}
function readList(data) {
var html = [];
html.push("<table><thead><tr><th>ID</th><th>First Name</th>" +
"<th>Last Name</th><th>Phone</th></tr></table></thead>");
data = data.d.results;
for (var i = 0; i < results.length; i++) {
html.push("<tr><td>");
html.push(results[i].ID);
html.push("</td><td>");
html.push(results[i].Title);
html.push("</td><td>");
html.push(results[i].pb_FirstName);
html.push("</td><td>");
html.push(results[i].pb_PhoneNumber);
html.push("</td><tr>");
}
html.push("</table>"`enter code here`);
$('.table').html(html.join(''));
}
so i get an in the console a json array with the data. im trying to bring the data in my html table. but i dont know how. so i need to bring my data object and render it in the right html
hope u can help me
Replace
console.log(data);
with the strangely named
readList(data);
You should use $.get for get data and handlebars for render html with data, its easy.
// Link handlebars
var template = "<table>\
<thead>\
<tr>\
<th>ID</th>\
<th>Title</th>\
<th>First Name</th>\
<th>Phone</th>\
</tr>\
</thead>\
<tbody>\
{{#objects}}\
<tr>\
<td>{{ Id }}</td>\
<td>{{ Title }}</td>\
<td>{{ pb_FirstName }}</td>\
<td>{{ pb_PhoneNumber }}</td>\
</tr>\
{{/objects}}\
</tbody>\
</table>";
$.get('someurl')
.success(function(response){
//here render data to html
// We can use Handlebars, is a engine of templates.
$("#box").html(Handlebars.compile(template)({'objects' : response['d']['results']}));
})
.error(function(err){
alert(JSON.stringify(err));
});
Related
I want to use the jquery pluging datatables and complement local data through an external REST ressource.
My table has to columns, Id and RestCalledValue:
<table id="table">
<thead>
<tr>
<th>Id</th>
<th>RestCalledValue</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
My js has an object data, which holds my local data:
let data = [
{
"id": 1
},
{
"id": 2
}
]
My datatables initialisation looks like below: i want to give the second column the returned value from the function getRestDataForId (id).
$(function () {
var table = $('#table').DataTable({
data: data,
columns: [
{
data: "id"
},
{
data: function (row, type, set, meta) {
getRestDataForId(row.id);
},
defaultContent: "-"
}
]
});
});
function getRestDataForId(id) {
fetch('https://jsonplaceholder.typicode.com/todos/' + id)
.then(response => response.json())
.then(data => data.title)
}
I constructed a fiddle here:
https://jsfiddle.net/mxhdwfz6/2/
I must be treating the promise wrong. Looking forward for your input!
I have a Library angularJS application and a JSON Data file that contains an array of book's information like this
[
{
"name" : "test1",
"pages": 0,
"author": "author1",
"year": 1940,
"section": "history",
"current": 0,
"description": "bla bla bla",
"bookUrl": "data/book.pdf"
},
{
"name" : "test1",
"pages": 0,
"author": "author1",
"year": 1940,
"section": "history",
"current": 0,
"description": "bla bla bla",
"bookUrl": "data/book.pdf"
}
]
"current" is for the current page of the current book that i'm reading
and there is a "next" and "prev" buttons in the reading view
when i press "next" it adds "+1" to the "current" num page
the question is (How to send this +1 to the "current" in JSON file with PHP?)
I have this PHP code :
<?php
$jsonString = file_get_contents('library.json');
$data = json_decode($jsonString, true);
$data[0]['current'] = 3;
$newJsonString = json_encode($data);
file_put_contents('library.json', $newJsonString);
?>
See the ($data[0]) is for the index of the first book, how do i send to PHP the index of the current book so it updates the "current" data of the current book?
Here is the "next" function :
scope.goNext = function() {
if (scope.pageToDisplay >= pdfDoc.numPages) {
return;
}
scope.pageNum = parseInt(scope.pageNum) + 1;
$http.get("data/insert.php")
.success(function(data, status, headers, config) {
console.log("data inserted successfully");
});
};
And here is the reading Controller :
app.controller('read', ['$scope','books', '$routeParams',function($scope,books, $routeParams) {
books.success(function(data){
$scope.book = data[$routeParams.bookId]
$scope.pdfUrl = data[$routeParams.bookId].bookUrl;
$scope.pdfName = data[$routeParams.bookId].name;
});
//the pdf viewer options
//$scope.pdfUrl = 'data/tohfa12.pdf';
$scope.scroll = 0;
$scope.loading = 'Loading file please wait';
$scope.getNavStyle = function(scroll) {
if(scroll > 100) {
return 'pdf-controls fixed';
} else {
return 'pdf-controls';
}
};
$scope.onError = function(error) {
console.log(error);
};
$scope.onLoad = function() {
$scope.loading = '';
};
$scope.onProgress = function(progress) {
console.log(progress);
};
$scope.currentBookIndex = parseInt($routeParams.bookId);
}]);
I know it's complicated but i really need that , thanks.
How do you expect your application to behave?
You need to send the bookId and the pageNum with your request!
scope.goNext = function() {
if (scope.pageToDisplay >= pdfDoc.numPages) {
return;
}
scope.pageNum = parseInt(scope.pageNum) + 1;
$http.get("data/insert.php", {
param : {
bookId: $scope.bookId,
pageNum: $scope.pageNum
}
})
.success(function(data, status, headers, config) {
console.log("data inserted successfully");
});
};
BTW. By REST design a GET http request should never change a resource. GET is for READING. If you want to update a resource you should use POST, PUT or DELETE
I have an issue with Knockout binding to a model here is my code. The code fires and returns a JSON object but the table is empty. Any suggestions would be appreciated.
HTML
<table style="border: double">
<thead>
<tr>
<td>jobId</td>
</tr>
</thead>
<!--Iterate through an observableArray using foreach-->
<tbody data-bind="foreach: Jobs">
<tr style="border: solid" data-bind="click: $root.getselectedjob" id="updtr">
<td><span data-bind="text: $data.jobId "></span></td>
</tr>
</tbody>
</table>
Javascript
var JobViewModel = function () {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.jobId = ko.observable("");
self.name = ko.observable("");
self.description = ko.observable("");
//The Object which stored data entered in the observables
var jobData = {
jobId: self.jobId,
name: self.name,
description: self.description
};
//Declare an ObservableArray for Storing the JSON Response
self.Jobs = ko.observableArray([]);
GetJobs(); //Call the Function which gets all records using ajax call
//Function to Read All Employees
function GetJobs() {
//Ajax Call Get All Job Records
$.ajax({
type: "GET",
url: "/Client/GetJobs",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
debugger;
self.Jobs(data); //Put the response in ObservableArray
},
error: function (error) {
alert(error.status + "<--and--> " + error.statusText);
}
});
//Ends Here
}
//Function to Display record to be updated. This will be
//executed when record is selected from the table
self.getselectedjob = function (job) {
self.jobId(job.jobId),
self.name(job.name),
self.description(job.description)
//,
//self.DeptName(employee.DeptName),
//self.Designation(employee.Designation)
};
};
ko.applyBindings(new JobViewModel());
C# Method to get jobs
public ActionResult GetJobs(string AccountIDstr)
{
//parse this as parameter
int AccountID = Convert.ToInt32(AccountIDstr);
AccountID = 1;
var jobs = (from c in db.jobs
select c).OrderByDescending(m => m.jobId).ToList();
//"Business logic" method that filter jobs by the account id
var jobsFilter = (from e in jobs
where (AccountID == null || e.accountId == AccountID)
select e).ToList();
var jobsresult = from jobrows in jobsFilter
select new
{
jobId = jobrows.jobId.ToString(),
name = jobrows.name,
description = jobrows.description
};
return Json(new
{
Jobs = jobsresult
},
JsonRequestBehavior.AllowGet);
}
JSON Object
{"Jobs":[{"jobId":"5","name":"Job 5 ","description":"Job 5 description"},{"jobId":"1","name":"Job 1 ","description":"Job 1 description"}]}
Your Jobs is an observableArray, but the data is wrapped in an object. When you set the value in GetJobs, you should be doing
self.Jobs(data.Jobs);
Here's a runnable snippet that works. You should be able to run this using your ajax function to populate data. If it doesn't work, examine what you're getting back.
var JobViewModel = function() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.jobId = ko.observable("");
self.name = ko.observable("");
self.description = ko.observable("");
//The Object which stored data entered in the observables
var jobData = {
jobId: self.jobId,
name: self.name,
description: self.description
};
//Declare an ObservableArray for Storing the JSON Response
self.Jobs = ko.observableArray([]);
GetJobs(); //Call the Function which gets all records using ajax call
//Function to Read All Employees
function GetJobs() {
//Ajax Call Get All Job Records
var data = {
"Jobs": [{
"jobId": "5",
"name": "Job 5 ",
"description": "Job 5 description"
}, {
"jobId": "1",
"name": "Job 1 ",
"description": "Job 1 description"
}]
};
setTimeout(function() {
self.Jobs(data.Jobs);
}, 500);
}
//Function to Display record to be updated. This will be
//executed when record is selected from the table
self.getselectedjob = function(job) {
self.jobId(job.jobId),
self.name(job.name),
self.description(job.description)
//,
//self.DeptName(employee.DeptName),
//self.Designation(employee.Designation)
};
};
ko.applyBindings(new JobViewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.1.0/knockout-min.js"></script>
<table style="border: double">
<thead>
<tr>
<td>jobId</td>
</tr>
</thead>
<!--Iterate through an observableArray using foreach-->
<tbody data-bind="foreach: Jobs">
<tr style="border: solid" data-bind="click: $root.getselectedjob" id="updtr">
<td><span data-bind="text: $data.jobId "></span>
</td>
</tr>
</tbody>
</table>
I have an api endpoint at /api/pin that returns the following JSON:
{
"num_results": 4,
"objects": [
{
"id": 1,
"image": "http://placekitten.com/200/200/?image=9",
"title": "Test"
},
{
"id": 2,
"image": "http://placekitten.com/200/200/?image=9",
"title": "test"
},
{
"id": 3,
"image": "www.test.com",
"title": "test"
}
],
"page": 1,
"total_pages": 1
}
I want to map this into a knockout observable array and display it in my page. Here's my js file:
define(['knockout', 'text!./pins.html'], function(ko, templateMarkup) {
function Pins(params) {
var self = this;
self.agents = ko.observableArray([]);
$.getJSON('/api/pin', function(data){
self.agents = ko.mapping.fromJS(data);
});
}
return { viewModel: Pins, template: templateMarkup };
});
My html:
<b data-bind="agents.num_results"> results </b>
<table>
<tbody data-bind="foreach: agents.objects">
<tr>
<td data-bind="text: image"></td>
<td data-bind="text: title"></td>
</tr>
</tbody>
</table>
I get nothing rendered, other than the word "results".
I know that I can create a view model that represents the JSON data and push it into the array during the getJSON (and I've done that successfully). But I thought the whole point of the knockout mappings library was so that you didn't have to do that. I guess I'm having trouble wrapping my head around what exactly I'm doing wrong here. Seems like I must be missing something super obvious, but I'm pulling my hair out trying to figure out what's wrong.
So I figured it out. Basically I had to mock up a PinViewModel like this:
define(['knockout', 'text!./pins.html'], function(ko, templateMarkup) {
function PinVewModel (){
this.objects = ko.observableArray();
}
function Pins(params) {
var self = this;
self.agents = new PinVewModel();
$.getJSON('/api/pin', function(data){
ko.mapping.fromJS(data, {}, self.agents);
});
}
return { viewModel: Pins, template: templateMarkup };
});
And if anyone is interested in the POST part...
function Pin(data){
this.image = ko.observable(data.image);
this.title = ko.observable(data.title);
}
this.createPins = function(formElement){
formPin = new Pin({image: formElement.pin_url.value, title: formElement.pin_name.value});
$.ajax("/api/pin", {
data: ko.toJSON(formPin),
type: "post", contentType: "application/json",
success: function(result) {
self.pins.objects.push(formPin);
}
});
};
There's probably redundancy I'm doing in here, but it works and achieves the desired results.
i am using the below format to get a JSON object from my localhost. The JSON is pretty complicated and lengthy so , using jquery to populate the HTML is getting complicated.
function processmsg(msg) {
var jobj = JSON.parse(msg);
if (typeof jobj === 'object')
{
// Parse the JSON
}
document.getElementById("messages").innerHTML = globalTag;
}
}
function waitForMsg() {
$.ajax({
type: "GET",
url: "1.json",
cache: false,
timeout: 50000,
success: function (data) {
processmsg(data);
if (!data) {
setTimeout(
waitForMsg,
1000
);
};
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
setTimeout(waitForMsg, 15000);
processmsg("error");
}
});
};
$(document).ready(function () {
waitForMsg();
processmsg("loading");
});
I would like to use the format like {{jobj.entries}}. something like this. This can be done on angularJS. can you guys please suggest me how to do the same in angular ?
i want to query the JSON every 1 min and when the data is found i want to cancel the interval. I dono how to do it in angularjs.
==================update================
i got below code snippet. It is working fine, But how do i stop the url query once the json object is obtained..
var app = angular.module('urlanalyzer', []);
app.controller('jsonController', function($scope, $http) {
$scope.getData = function(){
var url = "{% static "" %}tmp/{{url_hash}}/{{url_json}}";
$http.get(url)
.success(function(data, status, headers, config) {
console.log(data);
});
};
if (!$scope.data){
setInterval($scope.getData, 2000);
}
The issue here is the json object will be available after 3 sec only.
var app = angular.module('urlanalyzer', []);
app.controller('jsonController', ['$scope','$http','$timeout',function($scope, $http, $timeout) {
$scope.getData = function(){
var url = "{% static "" %}tmp/{{url_hash}}/{{url_json}}";
$http.get(url)
.success(function(data, status, headers, config) {
if(!data)
$timeout(function(){
$scope.getData()
}, 2000)
else{
$scope.myData = data.data? data.data:data;
$scope.showError = false;
}
})
.error(function(msg) {
$timeout(function(){
$scope.getData()
}, 2000)
$scope.processMessage(msg)
});
};
$scope.processMessage = function(msg){
if(angular.isString(msg))
$scope.errorMessage = msg;
else if(angular.isObject(msg)){
$scope.errorMessage = msg.message // the property you want;
}
$scope.showError = true;
}
$scope.getData();
}])
HTML:
<div ng-controller="jsonController">
<div ng-show="showError">
{{errorMessage}}
</div>
<div id="myDatacontainer">
//you can bind any propery of your data by using angular direvtives
//look at ng-bing, ng-if etc. directives
{{myData.name}} ...
</div>
</div>
Hope it help.
Consider you have following JSON data stored in a scope variable named data:
$scope.data = {
"array": [
1,
2,
3
],
"boolean": true,
"null": null,
"number": 123,
"object": {
"a": "b",
"c": "d",
"e": "f"
},
"string": "Hello World"
}
Then you write your HTML in the following way like:
<div>
Boolean: {{data.boolean}}
</div>
<div>
Number: {{data.number * 2}}
</div>
<div>
Array:
<p ng-repeat="(key, value) in data.object"> {{key}} : {{value}}</p>
</div>
Another way to bind <div ng-bind="data.string"></div>
Here you can stop your call. You can use enhanced angular service $interval for this:
$scope.getData = function(){
var url = "{% static "" %}tmp/{{url_hash}}/{{url_json}}";
$http.get(url)
.success(function(data, status, headers, config) {
console.log(data);
$interval.cancel($scope.intervalObject); // cancel the interval when data is loaded
});
};
if (!$scope.data){
$scope.intervalObject = $interval($scope.getData, 2000);
}
if (!$scope.data){
setInterval($scope.getData, 2000);
}
since $scope.data is not set it'll continue calling the request(since you are not setting $scope.data anywhere).
Edit: Also, use angularjs $interval since it's the angular way of using setInterval and it keeps track of the $digest cycle