I'm trying to fill a table based on the selected tab, I'm using JQuery-UI tabs library with ajax, the problem is that only the last function
$('#tabs, #tab-4').tabs()
is working (Actually all functions are executed but I can see only the last one), therefore it only brings the information from the last tab. I'm not sure if i'm doing the things right.
<ul id="tabs">
<li>Abiertos</li>
<li>Solucionados</li>
<li>Cerrados</li>
<li>Cancelados</li>
</ul>
<div class="containerTab" id="tab-1">
<table class="table table-striped" id="records_table">
<thead>
<tr>
<th class="text-center">Id</th>
<th class="text-center">Cliente</th>
<th class="text-center">Producto</th>
<th class="text-center">Descripción</th>
<th class="text-center">Fecha</th>
<th class="text-center">Incidente</th>
<th class="text-center">Operación</th>
</tr>
</thead>
<tbody>
<tr></tr>
</tbody>
</table>
</div>
<div class="containerTab" id="tab-4">
<table class="table table-striped" id="records_table4">
<thead>
<tr>
<th class="text-center">Id</th>
<th class="text-center">Cliente</th>
<th class="text-center">Producto</th>
<th class="text-center">Descripción</th>
<th class="text-center">Fecha</th>
<th class="text-center">Incidente</th>
<th class="text-center">Cancelado por</th>
</tr>
</thead>
<tbody>
<tr></tr>
</tbody>
</table>
</div>
This is my script section (I removed tab-2 and tab-3 for the sake of not making it longer)
$('#tabs, #tab-1').tabs({
activate: function (event, ui) {
$("#records_table tbody tr").remove();
$.ajax({
type: "POST",
url: "/Servicios/GetIncidentes",
contentType: "application/json; charset=utf-8",
data: "{'incidente':'Abiertos'}",
dataType: "json",
success: function (response) {
$(function () {
$.each(response, function (i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.Id).addClass('text-center'),
$('<td>').text(item.Cliente).addClass('text-center'),
$('<td>').text(item.Producto).addClass('text-center'),
$('<td>').text(item.Descripcion).addClass('text-center'),
$('<td>').text(item.Fecha).addClass('text-center'),
$('<td>').text(item.Incidente).addClass('text-center'),
$('<td>').text('').addClass('text-center').prepend($('<i />', { 'class': 'fa fa-eye' }))
).appendTo('#records_table');
});
});
},
error: function (ts) { alert(ts.responseText) }
})
}
});
$('#tabs, #tab-4').tabs({
activate: function (event, ui) {
$("#records_table4 tbody tr").remove();
$.ajax({
type: "POST",
url: "/Servicios/GetIncidentes",
contentType: "application/json; charset=utf-8",
data: "{'incidente':'Cancelados'}",
dataType: "json",
success: function (response) {
$(function () {
$.each(response, function (i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.Id).addClass('text-center'),
$('<td>').text(item.Cliente).addClass('text-center'),
$('<td>').text(item.Producto).addClass('text-center'),
$('<td>').text(item.Descripcion).addClass('text-center'),
$('<td>').text(item.Fecha).addClass('text-center'),
$('<td>').text(item.Incidente).addClass('text-center'),
$('<td>').text('').addClass('text-center').prepend($('<i />', { 'class': 'fa fa-eye' }))
).appendTo('#records_table4 tbody');
});
});
},
error: function (ts) { alert(ts.responseText) }
})
}
});
The GetIncidentes method recieves a string (string incidente) and returns a parsed Json list.
Related
My Node API returns a JSON object, the object is being displayed on HTML table. However, my Node app takes some time to process and return the data. So till the time data has being retrieved I want a spinner to load on the page.
$(document).ready(function() {
$("#table1").hide();
$("#myButton").click(function() {
$("#myButton").hide();
$("#table1").show();
$.ajax({
url: "http://localhost:8090/api/route1",
type: 'POST',
data: {
data1: str1,
data2: str2
},
dataType: 'json',
success: function(res) {
console.log(res);
console.log("Result1", res.result1);
console.log("Result2", res.result2);
$('#td1').append(res.result1);
$('#td2').append(res.result2);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="spinner" id="loadingBtn">
Loading...
</span>
<table class="table" id="table1">
<tbody>
<tr>
<td id="td1"></td>
</tr>
<tr>
<td id="td2"></td>
</tr>
</tbody>
</table>
How and where do I put the spinner id so that it is only displayed until the data is fully rendered onto the HTML table.
$(document).ready(function() {
$("#table1").hide();
$("#myButton").click(function() {
$("#myButton").hide();
$("#table1").show();
$.ajax({
url: "https://www.mocky.io/v2/5ec78da22f0000640042721f",
type: 'GET',
dataType: 'json',
success: function(res) {
console.log(res);
console.log("Result1", res.result1);
console.log("Result2", res.result2);
$('#td1').append(res.result1);
$('#td2').append(res.result2);
},
beforeSend: function() {
$("#loadingBtn").show();
},
complete: function() {
$("#loadingBtn").hide();
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="spinner" id="loadingBtn" style="display:none;">
Loading...
</span>
<button id="myButton">Press</button>
<table class="table" id="table1">
<tbody>
<tr>
<td id="td1"></td>
</tr>
<tr>
<td id="td2"></td>
</tr>
</tbody>
</table>
You can just add the loading spinner on loading and done. Show the spinner on call, and just hide it when the call is done. like so:
$.ajax({
type: 'POST',
success: function(res){
console.log(res);
}
}).done(function() {
setTimeout(function(){
$(".spinner").fadeOut(300);
},500);
});
take a look at this codepen:
https://codepen.io/yic666kr/pen/mxmvbV
It depends on your structure where you have it placed but I'll go with what you have put here. You have it visible when you start loading and hide it once data is loaded from your ajax.
$(document).ready(function() {
$("#table1").hide();
$("#myButton").click(function() {
$("#myButton").hide();
$("#table1").show();
// show the loader when you click the button
$('#loadingBtn').addClass('spinner--is-active')
$.ajax({
url: "http://localhost:8090/api/route1",
type: 'POST',
data: {
data1: str1,
data2: str2
},
dataType: 'json',
success: function(res) {
console.log(res);
console.log("Result1", res.result1);
console.log("Result2", res.result2);
$('#td1').append(res.result1);
$('#td2').append(res.result2);
// hide the loader
$('#loadingBtn').removeClass('spinner--is-active')
}
});
});
});
.spinner {
display: none;
}
.spinner--is-active {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="spinner" id="loadingBtn">
Loading...
</span>
<table class="table" id="table1">
<tbody>
<tr>
<td id="td1"></td>
</tr>
<tr>
<td id="td2"></td>
</tr>
</tbody>
</table>
Just show your spinner in beforeSend of ajax function and hide it after data is loaded under success function.
$.ajax({
url: "http://localhost:8090/api/route1",
type: 'POST',
data: {
data1: str1,
data2: str2
},
dataType: 'json',
beforeSend: function() {
$("#loadingBtn").show();//show spinner
},
success: function(res) {
console.log(res);
console.log("Result1", res.result1);
console.log("Result2", res.result2);
$('#td1').append(res.result1);
$('#td2').append(res.result2);
$("#loadingBtn").hide();//hide spinner
}
});
So this is my code
<script>
export default {
name: "app",
data() {
return {
items: []
};
},
created: function() {
this.makeAjaxCall("books.json", "get").then(res => {
this.items = res
return res
}),
this.makeAjaxCall("authors.json", "get").then(resA => {
this.items = resA
return resA
})
},
methods: {
makeAjaxCall:function(url, methodType){
var promiseObj = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
//alert("xhr done ok");
var response = xhr.responseText;
var respJson = JSON.parse(response);
resolve(respJson);
} else {
reject(xhr.status);
//alert("xhr failed");
}
} else {
//alert("xhr processing");
}
}
//alert("request sent succesfully");
});
return promiseObj;
}
}
};
</script>
<template>
<div id="app">
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
<th>Availability</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img id="imageBook" :src="item.imageUrl"></td>
</tr>
</tbody>
</table>
</div>
</template>
I have the function makeAjaxCall that brings me the books.json, but I want to use it for multiple jsons.
I tried to call it under created, with a different json, authors.json, but it doesn't work.
I guess the syntax is wrong.
I know the function could have been created better, but I would like to keep its initial form or maybe add a parameter to be the json file.(Tried that, but didn't work for me)
Any ideas, pretty please?
To bind the data you have to declare first items: {books:[],authors:[]}
Also you are overwriting this.items use this.items.books and this.items.authors to assign.
Below is the example which works without ajax
new Vue ({
el: "#app",
data() {
return {
items: {books:[],authors:[]}
};
},
created: function() {
this.items.books = this.makeAjaxCall("books", "get");
this.items.authors = this.makeAjaxCall("authors", "get");
},
methods: {
makeAjaxCall:function(url, methodType){
if(url == 'books'){
promiseObj= [{name:'name11',author:'author11',genre:'genre11'},{name:'name12',author:'author12',genre:'genre12'}]
}else{
promiseObj= [{name:'name22',author:'author22',genre:'genre22'}]
}
return promiseObj;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.js"></script>
<div id="app">
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img :src="item.imageUrl"></td>
</tr>
</tbody>
</table>
<table class="authorsTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.authors" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img :src="item.imageUrl"></td>
</tr>
</tbody>
</table>
</div>
So I found the answer, after millions of tries and it's pretty simple.
<script>
import './styling.scss'
export default {
name: "app",
data() {
return {
items: {books:[], authors:[]}
};
},
created: function() {
this.makeAjaxCall("books.json", "get").then(res => {
this.items.books = res.books;
return res;
}),
this.makeAjaxCall("authors.json", "get").then(res => {
this.items.authors = res.authors;
return res;
})
},
methods: {
makeAjaxCall:function(url, methodType){
var promiseObj = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
//alert("xhr done ok");
var response = xhr.responseText;
var respJson = JSON.parse(response);
resolve(respJson);
} else {
reject(xhr.status);
//alert("xhr failed");
}
} else {
//alert("xhr processing");
}
}
//alert("request sent succesfully");
});
return promiseObj;
}
}
};
</script>
<template>
<div id="app">
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
<th>Availability</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img id="imageBook" :src="item.imageUrl"></td>
<td>
<button class="btn add"> Add</button>
<button class="btn edit"> Edit</button>
<button class="btn delete"> Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
I am trying to add a row to a HTML table from JSON input using AJAX. I only want specific columns added. I am able to get the table to show; however the rows are not added.
Please see below for the HTML and AJAX (with the returned JSON).
HTML:
<html>
<head>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script src="js/table2excel.js"></script>
<link rel="stylesheet" href="style.css">
<script src="js/tableTest.js"></script>
</head>
<body>
<p><button id="btn-export">Export</button></p>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Activity Name</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
</thead>
<tbody>
<tr>
<td id='adActivityName'></td>
<td id='adStartDate'></td>
<td id='adEndDate'></td>
</tr>
</tbody>
</table>
</body>
</html>
AJAX (with JSON):
function e1ActivitySelect() {
var dataToBeSent = {
ssAccountLevel : sessionStorage.getItem('ssAccountLevel'),
ssAccountID : sessionStorage.getItem('ssAccountID'),
ssArchived : sessionStorage.getItem('ssArchived'),
};
$.ajax({
url: "E1ActivitySelectView",
data : dataToBeSent,
type: "POST",
cache: false
})
.fail (function(jqXHR, textStatus, errorThrown) {
$('#ajaxGetUserServletResponse').text('An error occured getting the Activity information.');
})
.done(function(responseJson1a) {
dataType: "json";
// alert(JSON.stringify(responseJson1a));
// [{"adId":"2","grpId":"2","adActivityID":"2","adActivityName":"Visit Ryde Fire Station","adStartDate":"2017-05-24","adEndDate":"2017-05-24"}]
for (i=0; i < responseJson1a.length; i++) {
$('#adActivityName').append("<td>"+a[i].adActivityName+"</td>");
$('#adStartDate').append("<td>"+a[i].adStartDate+"</td>");
$('#adEndDate').append("<td>"+a[i].adEndDate+"</td>");
}
});
}
You are Not appending table rows in a proper way
When you have multiple rows to append you need to create multiple row tags and append the data like this
HTML:
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Activity Name</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
</thead>
<tbody id="mytablebody">
</tbody>
</table>
Javascript:
function e1ActivitySelect() {
var dataToBeSent = {
ssAccountLevel : sessionStorage.getItem('ssAccountLevel'),
ssAccountID : sessionStorage.getItem('ssAccountID'),
ssArchived : sessionStorage.getItem('ssArchived'),
};
$.ajax({
url: "E1ActivitySelectView",
data : dataToBeSent,
type: "POST",
cache: false
})
.fail (function(jqXHR, textStatus, errorThrown) {
$('#ajaxGetUserServletResponse').text('An error occured getting the Activity
information.');
})
.done(function(responseJson1a) {
var tablebody = "";
try{
for (i=0; i < responseJson1a.length; i++) {
tablebody += "<tr><td>"+responseJson1a[i].adActivityName+"</td><td>"++responseJson1a[i].adStartDate+"</td><td>"++responseJson1a[i].adEndDate+"</td></tr>";
}
$("#mytablebody").empty();
$("#mytablebody").append(tablebody);
}
catch(e){
console.log(e);
}
});
}
I need to parse a remote JSON file using a header with a get request in Angular 5. Not sure how to do it with GET along with header.
Something like this but in Angular 5:
let headers = new Headers({
'key': 'Value',
'key2' :'value2'
});
let request_option = new RequestOptions({ headers: this.headers});
this.http.get("http.//.....", request_option)
.map(res => res.json()
this.user.firstname = user.response.docs[0].FIRST_NAME;
this.user.lastname = user.response.docs[0].LAST_NAME;
JSON:
{
"responseHeader": {
"status":0,
"QTime":1,
},"response":{
"docs":[{
"FIRST_NAME": "John",
"LAST_NAME": "Smith"
}]
}
}
& finally be able to call it in HTML:
<div>{{user.firstname}}</div>
Below is the example for getting json from another server
$scope.userData = undefined;
var req = {
method: 'GET',
url: 'https://randomuser.me/api/?results=30&nat=US',
headers: { 'Content-Type': 'application/json' }
};
$http(req).then(function (response) {
$scope.userData = response.data;
});
If the response.data is recieved in json string, you can easily parse it using following code
JSON.stringify(response.data)
Below is the working example for getting json from another server and display it in table
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link data-require="bootstrap#3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script data-require="angular.js#1.6.6" data-semver="1.6.6" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js" type="text/javascript"></script>
<script>
(function() {
angular.module("testApp", ['ui.bootstrap']).controller('testCtrl', ['$scope', '$http', function($scope, $http) {
$scope.userData = undefined;
var req = {
method: 'GET',
url: 'https://randomuser.me/api/?results=30&nat=US',
headers: { 'Content-Type': 'application/json' }
};
$http(req).then(function (response) {
$scope.userData = response.data;
});
}]);
}());
</script>
<style></style>
</head>
<body ng-app="testApp">
<div ng-controller="testCtrl">
<form name="commonForm">
<table class="table">
<tr>
<th> Name </th>
<th> Gender </th>
<th> Email </th>
<th> Username </th>
<th> Date of Birth </th>
<th> Registered Date </th>
<th> Phone </th>
<th> Mobile </th>
<th> Nationality </th>
<th> Profile </th>
</tr>
<tr ng-repeat="user in userData.results">
<td> {{user.name.first}} {{user.name.last}}</td>
<td> {{user.gender}}</td>
<td> {{user.email}}</td>
<td> {{user.login.username}}</td>
<td> {{user.dob}}</td>
<td> {{user.registered}}</td>
<td> {{user.phone}}</td>
<td> {{user.cell}}</td>
<td> {{user.nat}}</td>
<td>
<img ng-src="user.picture.large">
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
In Angular 5 you can use property binding to access properties of DOM elements, in test case:
<div [innerHTML]="post.body"></div>
for reference look here angular.io docs
I am new to angularjs. I want to display the data in the following json file using ng-repeat.
http://www.cricbuzz.com/api/match/current
But I'm confused as there is a number in the data as key to each object. Can someone help me?
THis is a basic way to do it
Partial
<div ng-controller="Ctrl" >
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in rows">
<td>#{{ row.id}}</td>
<td>{{ row.series.name | uppercase }}</td>
</tr>
</tbody>
</table>
</div>
Controller
angular.module('app').controller('Ctrl', ['$scope', 'Resource', function ($scope, Resource) {
var pageChanged = function () {
$scope.myPromise = Resource.get({}, function (response) {
$scope.rows = response;
});
};
pageChanged();
}])
.factory('Resource', ['$resource', function($resource) {
return $resource('http://www.cricbuzz.com/api/match/current', {
}, {
'get': {
method: 'GET',
headers: {"Content-Type": "application/json"}
}
});
}]);