How to show Json data to the dialog box in html - html

I am a beginner in the ajax, dom, jsonm etc in web application. my project is to use jquery UI to parse json data and show all of data from database and retrive one data by id, it's part of create, retrieve, update, and delete. so retrieving is key function here. I can get all data and populate datatable with all data no problem.
"aoColumns" :[
{"mData" : "image"},
{"mData" : "name"},
{"mData" : "type"},
{"mData" : "description"},
{"mData" : "price"},
{"mData" : "id",
"mRender" : function(data, type,full)
{return '<a href="#" id="'+ full.id +
'" class="id">Details</a>'; }
}
-->to fetch all the data
var findById= function(id) {
console.log('findById: ' + id);
$.ajax({
type:'GET',
url: rootUrl + '/' + id,
dataType: "json",
success: renderList
});
};
var renderList = function(data){
var list = data == null?[] : (data instanceof Array ? data : [ data ]);
///////////////////////////////////
solution1//////////////////////////////////////////////////
$.each(list, function(index, pet){
var row="<tr>" + "<td>" + pet.type + "</td>"
+ "<td>" + pet.price + "</td>"
+ "<td>" + pet.contact_no+ "</td>"
+ "<td> "+ pet.contact + "</td>"
+ "</tr>";
//$(tblRow).appendTo("#entrydata tbody");
$(row).appendTo('dialogTable tbody');
});
to retrieve more details
the result(in xml) show this if I click the "details " link by checking element,
<pet>
<contact>bob.hoskins#lgfriday.com</contact>
<contact_no>5-(254)756-8567</contact_no>
<description>Great companion for up to 75 years</description>
<id>42</id>
<image>bird</image>
<name>Amazon</name>
<price>40</price>
<type>BIRDS</type>
</pet>
(failed)
net::ERR_CONNECTION_REFUSED
the data is coming back in MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML so I can check data type easily but cant make connection to it to show in dialog box
<div id="dialog" title="More Information">
<table id="dialogTable" style="width: 350px;">
<thead>
<tr id="findById">
<th>Type</th>
<th>Price</th>
<th>Contact</th>
<th>Email</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

I resolved the problem. I had set var rooturl = http://localhost/xxx/rest/xxx"; instead of rooturl = "http://localhost:8080/xxx/rest/xxx" . It solved the cross origin connection and connection failure problem and now it renders.

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.

Using datatables to display json file data

I tried many solution which are available in stack overflow but any single solution is not useful to me. Here is my code which I am trying still now.
HTML
<table id="example1" class="table table-bordered">
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody></tbody>
</table>
Json file data
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
....
}
Datatables code
var table;
$(function () {
table = $('#example1').DataTable({
"processing": true,
"serverSide": true,
"ajax" : {
"url" : "../apps/language/fr/fr.json",
"dataSrc" : function (json) {
console.log(json ? json.length : 'json_data is null or undefined');
$.each(json, function( index, value ) {
//console.log(index + "^_^" + value)
var html = "<tr>";
html += "<td>" + index + "</td>";
html += "<td>" + value + "</td>";
html += "<td><a href='javascript:void(0);' class='btn btn-sm btn-primary waves-effect waves-light edit'>EDIT</a></td>";
html += "</tr>";
var row = $(html);
$("#example1 tbody").append(row);
});
}
}
});
});
Can you please help me where I am wrong? I need data in table format with pagination. Same like datatables. I already load databables library. I am also getting length error in js while I used this code. Uncaught TypeError: Cannot read property 'length' of undefined

Populate HTML table with JSON data

We would be grateful for some guidance, [we are early into coding] and have looked at lots of examples but can cannot get our JSON to import into the table.
At that moment we have the table data in-line however a correctly formatted JSON file is now available and automatically updates and we want to load it into the table on the fly when the page is loaded.
This is an example of what were currently use:
<div>
<p> *** OTHER STUFF HERE ***<p/>
<table id="gable">
<colgroup>
<col class="twenty" />
<col class="fourty" />
<col class="thirtyfive" />
<col class="twentyfive" />
</colgroup>
<tr>
<th onclick="sortTable(0)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspCOUNTRY</th>
<th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspLOCATION</th>
<th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspBALANCE</th>
<th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspDATE</th>
</tr>
</table>
</div>
<script>
var data = [
{ "COUNTRY":"UK", "LoC":"London", "BALANCE":"78,573", "DATE":"1/06/2018" },
{ "COUNTRY":"US", "LoC":"New York", "BALANCE":"43,568", "DATE":"18/05/2018" },
{ "COUNTRY":"PL", "LoC":"Kraków", "BALANCE":"12,362", "DATE":"22/06/2018" },
{ "COUNTRY":"AU", "LoC":"Townsville", "BALANCE":"7,569", "DATE":"1/07/2018" },
{ "COUNTRY":" ", "LoC":"BALANCE:", "BALANCE":"142,072", "DATE":" " }
];
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.COUNTRY + '</td>' +
'<td>' + object.LoC + '</td>' +
'<td>' + object.BALANCE + '</td>' +
'<td>' + object.DATE + '</td>';
table.appendChild(tr);
});
</script>
There are a lot more lines of data, the table has CSS styling and applies the sortTable(n) function to the Headers. It displays perfectly, looks and functions like we want,
We've Googled [lots] and tried various load / populate scripts and attempted to get the example on w3schools working - https://www.w3schools.com/js/js_json_html.asp - alas we're fairly new to this.
Our JSON file /assets/sample.JSON is correctly formatted and meets the requirements.
How do we do a simple import of the JSON to populate the table id="gable"?
Ok, so in this solution I am going to assume that your external json file is called 'example.json'
Your external file should look something like this
example.json:
[
{ "COUNTRY":"UK", "LoC":"London", "BALANCE":"78,573", "DATE":"1/06/2018" },
{ "COUNTRY":"US", "LoC":"New York", "BALANCE":"43,568", "DATE":"18/05/2018" },
{ "COUNTRY":"PL", "LoC":"Kraków", "BALANCE":"12,362", "DATE":"22/06/2018" },
{ "COUNTRY":"AU", "LoC":"Townsville", "BALANCE":"7,569", "DATE":"1/07/2018" },
{ "COUNTRY":" ", "LoC":"BALANCE:", "BALANCE":"142,072", "DATE":" " }
]
The html remains the same all the changes have been made in the script tags. I split the functionality into 2 new functions. The first function (get_json_data) gets the json data from the external json file. The second function (append_json) appends the data to the table.
I have put comments throughout the code to explain what everything is doing. if you have any questions or if something is unclear let me know.
here is the code for the html file:
<div>
<p> *** OTHER STUFF HERE ***<p/>
<table id="gable">
<colgroup>
<col class="twenty" />
<col class="fourty" />
<col class="thirtyfive" />
<col class="twentyfive" />
</colgroup>
<tr>
<th onclick="sortTable(0)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspCOUNTRY</th>
<th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspLOCATION</th>
<th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspBALANCE</th>
<th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspDATE</th>
</tr>
</table>
</div>
<script>
//first add an event listener for page load
document.addEventListener( "DOMContentLoaded", get_json_data, false ); // get_json_data is the function name that will fire on page load
//this function is in the event listener and will execute on page load
function get_json_data(){
// Relative URL of external json file
var json_url = 'example.json';
//Build the XMLHttpRequest (aka AJAX Request)
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {//when a good response is given do this
var data = JSON.parse(this.responseText); // convert the response to a json object
append_json(data);// pass the json object to the append_json function
}
}
//set the request destination and type
xmlhttp.open("POST", json_url, true);
//set required headers for the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// send the request
xmlhttp.send(); // when the request completes it will execute the code in onreadystatechange section
}
//this function appends the json data to the table 'gable'
function append_json(data){
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.COUNTRY + '</td>' +
'<td>' + object.LoC + '</td>' +
'<td>' + object.BALANCE + '</td>' +
'<td>' + object.DATE + '</td>';
table.appendChild(tr);
});
}
</script>
you can have a function to create the table independent from your data fields:
function updateTable(tableId, jsonData){
var tableHTML = "<tr>";
for (var headers in jsonData[0]) {
tableHTML += "<th>" + headers + "</th>";
}
tableHTML += "</tr>";
for (var eachItem in jsonData) {
tableHTML += "<tr>";
var dataObj = jsonData[eachItem];
for (var eachValue in dataObj){
tableHTML += "<td>" + dataObj[eachValue] + "</td>";
}
tableHTML += "</tr>";
}
document.getElementById(tableId).innerHTML = tableHTML;
}

Looping through AJAX result and post to HTML,

I have the following AJAX code for processing a returned results from the database,
$.ajax({
type: 'POST',
async: true,
url: "../../../avocado/private/functions/measures.php",
data: {name:selectedValue},
success: function(data, status){
var selectedData = JSON.parse(data);
console.log(selectedData);
document.getElementById("measures").innerHTML = "<div id=\"measures\">"
+ "<table class=\"table table-condensed\">"
+ "<tr><th>desc1</th><td>"+selectedData[0][6]+"</td></tr>"
+ "<tr><th>desc2</th><td>"+selectedData[0][7]+"</td></tr>"
+ "<tr><th>desc3</th><td>"+selectedData[0][8]+"</td></tr>"
+ "<tr><th>desc4</th><td>"+selectedData[0][9]+"</td></tr>"
+ "</table>"
+ "</div>";
},
error: function(xhr, status, err) {
alert(status + ": " + err);
}
});
The data returned is a 2D array, like this below,
Array[5]
0: Array[14]
1: Array[14]
2: Array[14]
3: Array[14]
4: Array[14]
so what I want to do is to loop each array and display the inner information on the HTML page but I have no idea how I should go about doing it.. this code only returns the values stored on index[0].
Can I please get some help?
==============================================================================
UPDATED
So I tried to use Jquery.append() like the following below..
jQuery.each( selectedData, function( i, val ) {
$("measures").append(
"<table class=\"table table-condensed\">"
+ "<tr><th>desc1</th><td>"+selectedData[i][6]+"</td></tr>"
+ "<tr><th>desc2</th><td>"+selectedData[i][7]+"</td></tr>"
+ "<tr><th>desc3</th><td>"+selectedData[i][8]+"</td></tr>"
+ "<tr><th>desc4</th><td>"+selectedData[i][9]+"</td></tr>"
+ "</table>"
);
});
/*
document.getElementById("measures").innerHTML = "<div id=\"measures\">"
+ "<table class=\"table table-condensed\">"
+ "<tr><th>desc1</th><td>"+selectedData[0][6]+"</td></tr>"
+ "<tr><th>desc2</th><td>"+selectedData[0][7]+"</td></tr>"
+ "<tr><th>desc3</th><td>"+selectedData[0][8]+"</td></tr>"
+ "<tr><th>desc4</th><td>"+selectedData[0][9]+"</td></tr>"
+ "</table>"
+ "</div>";
*/
now..its not appending any values to the div #measures at all...
I have not tried the code. But I hope this will help you.
document.getElementById("measures").innerHTML = "<div id=\"measures\">";
$.each( selectedData, function( index, value ){
$.each( index, function( index2, value2 ){
$('#measures').append(value2);
});
});

I'm having trouble parsing response from $.ajax

I'm trying to modify some old code of mine to include comments for photos. The photos are acquired using $.ajax and the response is in html.
My modification is to get the comments as a json object and then parse the previously attained html inserting the comments where appropriate. Here is the [latest incarnation] of my code (I've tried many different alternatives)
$.ajax({
type:"POST",
url:"<?php echo $_SERVER['PHP_SELF']; ?>",
data:"ajax_loadbigthumbs=true&section=<?php echo $_GET['section']; ?>",
dataType : "html",
success: function(html){
jhtml = $(html);
$.getJSON( "/commentsjson.php?getcomments=true&section=<?php echo $_GET['section']; ?>", function( data ) {
$.each(data,function(i,item){
//alert(item.comment); <--- this works so I know the data is coming back correctly
console.log(jhtml.find('#comments_' + item.photoid).attr("id")); // this shows 'undefined'
jhtml.find('#comments_' + item.photoid).css("display","block").html("<p>" + item.name + " said " + item.comment + "</p>");
});
$("#largethumbscontainer").append(jhtml);
});
}
});
But this isn't working. The console.log line (as a test) returns 'undefined' and the following line (jhtml.find) has not found anything to modify.
var $comment = $('#comments_' + item.photoid, jhtml);
if ($comment.length)
$comment.css("display","block").html("<p>" + item.name + " said " + item.comment + "</p>");
I fixed it, buy appending the html to an already existing element, and then appending the comments to that element....
$.ajax({
type:"POST",
url:"<?php
echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");
?>",
data:"ajax_loadbigthumbs=true&section=<?php echo $_GET['section']; ?>",
dataType : "html",
success: function(html){
jhtml = $(html);
$("#largethumbscontainer").append(jhtml);
largethumbs = $("#largethumbscontainer");
$.getJSON( "/commentsjson.php?getcomments=true&section=<?php
echo $_GET['section'];
?>", function( data ) {
$.each(data,function(i,item){
largethumbs
.find('#comments_' + item.photoid)
.css('display','block')
.append('<p>' +
item.name +
' said: <span style="font-style:italic;">' +
item.comment +
'</span></p>');
});
});
}
});