HTML Table data will disappear after page refresh - json

I am using a web service to get data from MySQL database and show them in a HTML Table. And it is working data will appear in the table. But when I reload the page Table data will disappear. How can I fix that? How can I keep data even page reloaded?
HTML
<body>
<button id="btnSearch">Search</button>
<table id="tab">
</table>
</body>
And the following JS.
<script type="text/javascript">
$("#btnSearch").click(function()
{
$.getJSON("http://localhost:8080/Service/Rest/cart/get/cart",function(data)
{
var tb = $("#tab");
$.each(data,function(i,value)
{
tb.append("<tr><td>Product Name: " + value.name + "</td><td>Price: " + value.price + " </td><td>Description: " + value.description + "</td></tr>");
});
});
});
</script>

<script type="text/javascript">
$( document ).ready(function() {
$.getJSON("http://localhost:8080/Service/Rest/cart/get/cart",function(data)
{
var tb = $("#tab");
$.each(data,function(i,value)
{
tb.append("<tr><td>Product Name: " + value.name + "</td><td>Price: " + value.price + " </td><td>Description: " + value.description + "</td></tr>");
});
});
});
$("#btnSearch").click(function()
{
$.getJSON("http://localhost:8080/Service/Rest/cart/get/cart",function(data)
{
var tb = $("#tab");
$.each(data,function(i,value)
{
tb.append("<tr><td>Product Name: " + value.name + "</td><td>Price: " + value.price + " </td><td>Description: " + value.description + "</td></tr>");
});
});
});
</script>

I have another solution for this, create a dummy table data with null value, and store your value in browser session and then replace all the null value on runtime through jquery/javascript.
Hope this helps.

Related

Is there a good package/library to add Pagination/Sorting/Searching to my table? ASP.NET Core

I am new to web development in ASP.NET Core. I have a table with information, I would like to add pagination/sorting/searching to the table. Is there an easy way to add this using some sort of library/package? Thanks
I need pagination, sorting, and searching for my ASP.NET Core table.
I would like to add pagination/sorting/searching to the table. Is
there an easy way to add this using some sort of library/package?
Well, considering all the requirement you can go for jquery data table regardless of simplicity, quick implementation and free subscription. Importantly, its light weight and easy to use.
Here is the compplete example how you can implement that:
Controller:
[HttpGet]
public IActionResult ConAction()
{
var controlleractionlist = _context.Controller.ToList();
return Json(controlleractionlist);
}
Note: I am returning a simple list to demonstrate you , sorting, searching and paging functionality.
View:
<table id="userTable_info" >
<thead>
<tr>
<th>action </th>
<th>controller </th>
<th>returnType</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tBody"> </tbody>
</table>
#section scripts {
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script>
//Button Click Functions
function DetailsFunc(data) {
alert("User Id:" + data + " Details!");
}
function EditFunc(data) {
alert("User Id:" + data + " will be Edited!");
}
function DeleteFunc(data) {
alert("User Id:" + data + " will be deleted!");
}
//On Load
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'http://localhost:5094/Home/ConAction',
dataType: "json",
contentType: "application/json",
success: function (response) {
console.log(response);
var id = 0;
$.each(response, function (index, value) {
id++;
console.log(id);
var tr = "<tr>";
tr += "<td>" + value.action + "</td>";
tr += "<td>" + value.controller + "</td>";
tr += "<td>" + value.returnType + "</td>";
tr += "<td>" + "<input type='button' id='" + id + "' class='btn btn-info' onclick='DetailsFunc(" + value.id + ")' value='Details'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-warning' onclick='EditFunc(" + value.id + ")' value='Edit'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-danger' onclick='DeleteFunc(" + value.id + ")' value='Delete'>" + "</td>" + "</tr>";
$("#tBody").append(tr);
});
$("#userTable_info").DataTable();
}
});
});
</script>
}
Output:
You could refer to official document for more details.

How do I pull data from JSON URL?

I am trying to display the "students" data in a table with their SRN, firstName, surName and allocated group. I am also trying to display their tutorial group from the "groups" data based on students SRN.
This is my HTML file:
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<title>Student groups</title>
<link rel="stylesheet" type="text/css" href="app.css">
<script type="text/javascript" src="displayStudents.js"></script>
<script type="text/javascript">
var studentsListJSON ;
function getStudentsJSON() {
makeRequest('http://homepages.herts.ac.uk/~comqgrs/ads/moduleGroups.php?moduleCode=6com9051');
}
function makeRequest(url) {
console.log("Making Request to..." + url);
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
console.log('Giving up. Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = processContents;
httpRequest.open('GET', url);
httpRequest.send();
}
function processContents() {
console.log("Call back to process contence: state = " + httpRequest.readyState + "; status = " + httpRequest.status);
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
console.log("request returned, processing data... \n" + httpRequest.responseText);
studentsListJSON = JSON.parse(httpRequest.responseText);
displayStudents();
} else {
console.log('There was a problem with the request.');
}
}
}
</script>
</head>
<body>
<h1>Student Groups for 6COM9051: More Web Scripting</h1>
<h2>Selected Students</h2>
<p>Lets go ... display the Students!</p>
<div id="studentsList"></div>
</body>
</html>
This is my JS file:
function displayStudents() {
var studentsListHTML = '<table id="studentsTable"><thead><tr><th>SRN</th><th>Firstname</th><th>Lastname</th><th>Allocated Group</th></tr></thead>'
for (var studentsName = '"students"' in studentsListJSON) {
var students = studentsListJSON[studentsName];
var studentHTML = '<tr><td>' + students.SRN + '</td><td>' + students.firstName + '</td><td>' + students.lastName + '</td><td>' + students.allocatedGroup + '</td></tr>';
studentsListHTML += studentHTML;
}
studentsListHTML += '</table>';
document.getElementById('studentsList').innerHTML=studentsListHTML;
}
I need to have the data in a table as the user opens the page on a browser and have a search bar so that the user can search for any of the data displayed in the table.
Try changing the displayStudents() method to :
function displayStudents() {
var studentsListHTML = '<table id="studentsTable"><thead><tr><th>SRN</th><th>Firstname</th><th>Lastname</th><th>Allocated Group</th></tr></thead>'
for (var studentSRN in studentsListJSON.students) {
var student = studentsListJSON.students[studentSRN];
var studentHTML = '<tr><td>' + studentSRN + '</td><td>' + student.firstName + '</td><td>' + student.lastName + '</td><td>' + student.allocatedGroup + '</td></tr>';
studentsListHTML += studentHTML;
}
studentsListHTML += '</table>';
document.getElementById('studentsList').innerHTML=studentsListHTML;
}
Note the line (line 5) - var student = studentsListJSON.students[studentSRN];
You need to use the studenSRN as a key to access the corresponding Student in the studentsListJSON.students dictionary.

Best way to load/store ndDialog template?

I am using ngDialog to display a modal window with an alert message.
I have the modal window working however the code looks messy.
I am wondering is it possible to replace the raw html template with a link to a html file instead of writing the HTML within the function itself.
$scope.openDialog = function(components) {
$scope.selected = components.component;
ngDialog.open({
template: '<h4>' + 'Alert' + '</h4>' +
'<table class="table">' +
'<tr><th>Type</th><td>' + components.type + '</td></tr>' +
'<tr><th>Component</th><td>' + components.component + '</td></tr>' +
'<tr><th>Created</th><td>' + components.created + '</td></tr>' +
'<tr><th>Alert</th><td>' + components.alert + '</td></tr>'+
'</table>',
plain: true
});
};
Yep, just use templateUrl rather than template.
$scope.openDialog = function(components) {
$scope.selected = components.component;
ngDialog.open({
templateUrl: 'yourfilename.html',
plain: true
});
};

Trying to simply implement the google+ sign in button HTML

I am trying to implement a google+ sign in button into my website! Working with HTML, and I am not sure why the button itself is not working. I am following these instructions:
https://developers.google.com/+/web/signin/add-button
This is what I have so far (I originally found code for a log in and log out button, but decided to just use the google+ API)
Where would I put this code in??
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}
Am I missing an onclicklistener or something?? Thank you!!!
<!DOCTYPE html>
<html>
<head>
<script src="https://apis.google.com/js/client:platform.js" async defer></script>
</head>
<body>
<!---<input type="button" value="Login" onclick="login()" />
<input type="button" value="Logout" onclick="logout()" />--->
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-clientid="805034040388-erokn7fetmrl9id1romu3o75m7tbnpqp.apps.googleusercontent.com"
data-cookiepolicy="single_host_origin"
data-requestvisibleactions="http://schema.org/AddAction"
data-scope="https://www.googleapis.com/auth/plus.login">
</span>
</span>
<div id="profile"></div>
<script type="text/javascript">
function logout()
{
gapi.auth.signOut();
location.reload();
}
function login()
{
var myParams = {
'clientid' : 'PUTYOUR_CLIENT_ID.apps.googleusercontent.com',
'cookiepolicy' : 'single_host_origin',
'callback' : 'loginCallback',
'approvalprompt':'force',
'scope' : 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read'
};
gapi.auth.signIn(myParams);
}
function loginCallback(result)
{
if(result['status']['signed_in'])
{
var request = gapi.client.plus.people.get(
{
'userId': 'me'
});
request.execute(function (resp)
{
var email = '';
if(resp['emails'])
{
for(i = 0; i < resp['emails'].length; i++)
{
if(resp['emails'][i]['type'] == 'account')
{
email = resp['emails'][i]['value'];
}
}
}
var str = "Name:" + resp['displayName'] + "<br>";
str += "Image:" + resp['image']['url'] + "<br>";
str += "<img src='" + resp['image']['url'] + "' /><br>";
str += "URL:" + resp['url'] + "<br>";
str += "Email:" + email + "<br>";
document.getElementById("profile").innerHTML = str;
});
}
}
function onLoadCallback()
{
gapi.client.setApiKey('PUT_YOUR_KEY');
gapi.client.load('plus', 'v1',function(){});
}
</script>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client.js?onload=onLoadCallback';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
</body>
</html>
I made it work in my localhost.
Please be sure that you followed the proper steps from that link.
Especially the first step .
After finishing the first step, you have to pay attention to two big details:
Whatever Production URL you add there, those ones will be available for your button. If you have a hosting, add that, otherwise I hope you can run your code with a localhost server (wamp, xampp etc).
Client ID
Now, this a piece of code working if you run on the specific Production URL for your Client ID (be careful to add the proper client ID in the code below)
<html>
<head>
<title>Google+ Sign-in button demo</title>
<style type="text/css">
html, body { margin: 0; padding:0;}
#signin-button {
padding: 5px;
}
#oauth2-results pre { margin: 0; padding:0;}
.hide { display: none;}
.show { display: block;}
</style>
<script type="text/javascript">
var loginFinished = function(authResult) {
if (authResult) {
var el = document.getElementById('oauth2-results');
var label = '';
toggleDiv('oauth2-results');
if (authResult['status']['signed_in']) {
label = 'User granted access:';
gapi.auth.setToken(authResult);
} else {
label = 'Access denied: ' + authResult['error'];
}
el.innerHTML =
label + '<pre class="prettyprint"><code>' +
// JSON.stringify doesn't work in IE8.
'{<br />' +
' "id_token" : "' + authResult['id_token'] +'",<br />' +
' "access_token" : "' + authResult['access_token'] + '",<br />' +
' "state" : "' + authResult['state'] + '",<br />' +
' "expires_in" : "' + authResult['expires_in'] + '",<br />' +
' "error" : "' + authResult['error'] + '",<br />' +
' "error_description" : "' + authResult['error_description'] + '",<br />' +
' "authUser" : "' + authResult['authuser'] + '",<br />' +
' "status" : {"' + '<br />' +
' "google_logged_in" : "' + authResult['status']['google_logged_in'] + '",<br />' +
' "method" : "' + authResult['status']['method'] + '",<br />' +
' "signed_in" : "' + authResult['status']['signed_in'] + '"<br />' +
' }<br />' +
'}</code></pre>';
toggleDiv('signin-button');
} else {
document.getElementById('oauth2-results').innerHTML =
'Empty authResult';
}
};
function toggleDiv(id) {
var div = document.getElementById(id);
if (div.getAttribute('class') == 'hide') {
div.setAttribute('class', 'show');
} else {
div.setAttribute('class', 'hide');
}
}
</script>
<script src="https://plus.google.com/js/client:platform.js" type="text/javascript"></script>
</head>
<body>
<div id="signin-button" class="show">
<div class="g-signin" data-callback="loginFinished"
data-approvalprompt="force"
data-clientid="CLIENT_ID"
data-requestvisibleactions="http://schema.org/CommentAction"
data-cookiepolicy="single_host_origin"
>
</div>
</div>
</body>
</html>
The error in the console I see is:
Callback function named "signinCallback" not found
You did not use the function from here: data-callback="signinCallback"
In your documentation it is down there:
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}

Dynamically generated Radio button from json data

I am developing an application for selecting the PASS/FAIL option for the value generated from the json data.
My problem is that I am not able to select value per row.The selected value applies in all rows.
HTML:
<table id="records" cellspacing="0">
JQUERY:
(function () {
var url = "http://www.filltext.com/?callback=?";
$.getJSON(url, {
'rows': 5,
'fname': '{firstName}',
'lname': '{lastName}',
'tel': '{phone|format}',
})
.done(function (data) {
$.ajaxSetup({
cache: false
});
var t;
$.each(data, function (i, item) {
var html =
"<td>" + item.fname + "</td>" +
"<td>" + item.lname + "</td>" +
"<td>" + item.tel + "</td>" +
"<td><input type='text' name='PASS' placeholder='" + i + "' /></td>" +
"<td><input type='radio' value='Pass' name='PASS'/>PASS</td>" +
"<td><input type='radio' value='Fail' name='PASS'/>FAIL</td>";
$("<tr/> </table>").html(html).appendTo("#records");
});
$('input[name="PASS"]').on('change', function () {
$('input[type="text"]').val($(this).val());
});
});
})();
JSFIDDLE: http://jsfiddle.net/rutvij111/hUAWF/
working fiddle
first you need to add the same name only to the two radiobuttons that you want to associate (pass and fail) for each row
something like this:
"<td><input type='radio' value='Pass' name='PASS" + i + "'/>PASS</td>"+
"<td><input type='radio' value='Fail' name='PASS" + i + "'/>FAIL</td>";
then assign the change handler to the radio buttons using the type instead of the name
$('input[type="radio"]').on('change', function() { });
and get to the parent tr and look for the input[type=text] from there
$(this).parent().parent().find('input[type=text]').val($(this).val());
That's because you assign the same name="PASS" to every radio button. You ought to select a different one for each row. You could number it like name = "PASS1" or so. Demo for recommended method:
http://jsfiddle.net/hUAWF/7/
Alternatively you could only update a single row if it's only for showing the data (and not writing it) by selecting a children of that row:
$('input[name="PASS"]').
on('change', function() {
$(this).
parents("tr").
find('input[type="text"]').
val($(this).val());
Demo for easy alternative:
http://jsfiddle.net/hUAWF/4/
This is not the optimal solution , but it is working
(function() {
var url = "http://www.filltext.com/?callback=?";
$.getJSON( url, {
'rows': 5,
'fname': '{firstName}',
'lname': '{lastName}',
'tel': '{phone|format}',
})
.done(function( data ) {
$.ajaxSetup ({ cache: false});
var t;
$.each( data, function( i, item ) {
var html =
"<td>" + item.fname + "</td>" +
"<td>" + item.lname + "</td>" +
"<td>" + item.tel + "</td>" +
"<td><input id="+i+" type='text' name='PASS' placeholder='"+i+"' /></td>" +
"<td><input id="+i+" type='radio' value='Pass' name='PASS'/>PASS</td>"+
"<td><input id="+i+" type='radio' value='Fail' name='PASS'/>FAIL</td>";
$("<tr/> </table>").html(html).appendTo("#records");
});
$('input[name="PASS"]').on('change', function() {
var id= $(this).attr('id');
$('input[type="text"]#'+id).val($(this).val());
});
});
})();
Working DEMO
Try this,
The problem was since you have specified $('input[type="text"]')it will select all input of type text, so all the textboxes' value will be effected, However the code below gets the corresponding textbox in the same row of the clicked radio button.
$('input[name="PASS"]').on('change', function() {
$(this).parents('tr').find('input[type="text"]').val($(this).val());
});
Hope this helps, thank you