I have got the below JSON as result from database through calll of json_encode
[
{
"id":1,"FullName":"Duce",
"subjects": [
{
"id":1,
"SubjectName":"Phy",
"pivot":{
"student_id":1,
"subject_id":1
}
}
],
"topics": [
{
"id":1,
"TopicName":"Meas",
"Subject_id":"1",
"pivot":{
"student_id":1,
"topic_id":1,
"Price":15000,
}
}
]
}
]
I need to achive something like this
------------------------------------------------------------------------------------------------------------------
ID Subject Name Topics Name Price Action
--------------------------------------------------------------------------------------------------------------------
1 Phy Meas 15000 X
2 ----- ---- -----
-------------------------------------------------------------------------------------------------------------------
i tried on using Jquery Ajax each methods to pass through every object within a data responses as below but got an intended results
let rows = '';
$.get(URL_GET_STUDENT,
function (data ,status) {
console.log(data);
$.each(data ,function (key ,value) {
$("#FullName").val(value.FullName);
$.each(value.subjects ,function (key1 ,value1 ) {
rows += "<tr>" +
"<td>" +
"<select class='form-control subject_selected' name='subject[]' id='subject' data-id='0' required>" +
"<option>"+ value1.SubjectName +"</option>" +
"</select>" +
"</td>" +
"<td>";
});
$.each(value.topics ,function (key2 ,value2 ) {
rows += "<select class='form-control topic_selected' name='topic[]' id='topic' data-id='0' required>" +
"<option>" + value2.TopicName + "</option>" +
"</select>" +
"</td>" +
"td>" +
"<input type='text' class='form-control Amount' name='Amount[]' id='Amount' value='"+ value2.TopicName +"'/>" +
"</td>" +
"<td>" +
"<a href='javascript:void(0)' class='btn btn-danger remove'>X</a>" +
"</td>"+
"</tr>";
});
});
$("#table_tuition_fee").append(rows);
});
Which is like below
Anyone who can help me to achieve the above result? I real appreaciate your help?
Related
var students = [
["test", "test", "test"],
["test", "test", "test"]
];
students.sort();
function display() {
for (i = 1; i < students.length + 1; i++) {
document.write("<tr>");
document.write("<td>" + (i) + "</td>");
document.write("<td>" + students[i - 1][0] + "</td>");
document.write("<td>" + students[i - 1][1] + "</td>");
document.write("<td>" + students[i - 1][2] + "</td>");
document.write("<td><input type='number' class='form-control' id='quiz" + i + "' ></td>");
document.write("<td><input type='number' class='form-control' id='reqt" + i + "'></td>");
document.write("<td><input type='number' class='form-control' id='exam" + i + "'></td>");
document.write("<td><input type='number' class='form-control' id='pg" + i + "' readonly></td>");
document.write("</tr>");
}
}
function AddData() {
var AddName;
var AddCourse;
var AddBDay;
var Data;
AddName = document.getElementById('Addname').value;
AddCourse = document.getElementById('AddCourse').value;
AddBDay = document.getElementById('AddBDay').value;
if (AddName != "" && AddCourse != "" && AddBDay != "") {
Data = [AddName, AddCourse, AddBDay];
students.push(Data);
console.log(students);
display();
} else {
alert("Invalid Input");
}
}
document.write is very very old-school and it's very rarely used any more for many reasons.
You can either create a string variable that you can then add (concatenate) new strings to, or you can use more modern methods like in the example below which uses map to iterate over the array to create a new array of strings, and then join that array up into one HTML string.
const students = [
["test", "test", "test"],
["test", "test", "test"]
];
function getHtml(students) {
return students.map(arr => {
return `
<tr>
<td>${arr[0]}</td>
<td>${arr[1]}</td>
<td>${arr[2]}</td>
</tr>
`
}).join('');
}
const table = document.querySelector('table');
table.innerHTML = getHtml(students);
<table></table>
You haven't posted any HTML, but assuming you have a <table id="x"> or <tbody id="x">, modify the display function as below:
function display() {
let html = '';
students.map((item, i) => {
html += "<tr>";
html += "<td>" + (i+1) + "</td>";
html += "<td>" + item[0] + "</td>";
html += "<td>" + item[1] + "</td>";
html += "<td>" + item[2] + "</td>";
html += "<td><input type='number' class='form-control' id='quiz" + i + "' ></td>";
html += "<td><input type='number' class='form-control' id='reqt" + i + "'></td>";
html += "<td><input type='number' class='form-control' id='exam" + i + "'></td>";
html += "<td><input type='number' class='form-control' id='pg" + i + "' readonly></td>";
html += "</tr>";
});
document.getElementById("x").innerHTML = html;
}
Also, document.write is rarely to never used. More here.
element.innerHTML is generally used when you want to perform some DOM manipulation as a result of an API call or any other event, as in your case.
I want to get the length of data, when i try console.log(data) i got all of data but console.log(data.length) is undefined.
function tampilesai(idsoal){
$.ajax({
url: "soalesai/baca/"+idsoal,
type: "POST",
dataType: "JSON",
success: function(data){
console.log(data); //here <=================
console.log(data.length); //here <=============
var html = "";
for (i = 0; i < data.length; ++i) {
html += "<tr>" +
"<td class='isitbl'>" + data[i].idsoal + "</td>" +
"<td class='isitbl' style='width:20px;'>" + data[i].noesai + "</td>" +
"<td class='isitbl' style='width:200px;'>" + data[i].matakuliah + "</td>" +
"<td>" + data[i].isiesai + "</td>" +
"<td class='isitbl'><button class='btn btn-danger btn-block' id='hapus' data[i]-id='" + data[i].idsoal + "'>" +
"<span class='icon-trash'></span> Hapus</button>" +
"</td>" +
"</tr>";
}
$("tbody#tblesai").html(html);
}
})
i need data.length for loop and fill my table. its data log
{idesai: "90", idsoal: "1", noesai: "1", matakuliah: "1", isiesai: "<p>asdd</p>"}
this image browser
If your data is an Object then you need to use Object.keys(data).length instead to get the length of the data object.
Try the following...
Convert the result data into JSON object. Although the return type was explicitly stated as JSON, but some version of jQuery may not parse it automatically. I ran into such bug with some version 2.x
var data = $.parseJSON(data);
// console.log(data.length) *should return 1
var html = "";
$.each(data, function(c) {
html += "<tr>" +
"<td class='isitbl'>" + c.idsoal + "</td>" +
"<td class='isitbl' style='width:20px;'>" + c.noesai + "</td>" +
"<td class='isitbl' style='width:200px;'>" + c.matakuliah + "</td>" +
"<td>" + c.isiesai + "</td>" +
"<td class='isitbl'><button class='btn btn-danger btn-block' id='hapus' data[i]-id='" + c.idsoal + "'>" +
"<span class='icon-trash'></span> Hapus</button>" +
"</td>" +
"</tr>";
});
$("tbody#tblesai").html(html);
I have not tested this, but I think it will give you an alternative idea.
Finish..
function tampilesai(idsoal){
$.ajax({
url: "soalesai/ambil/"+idsoal,
type: "POST",
dataType: "JSON",
success: function(data){
var html = "";
for(i=0;i<data.length;i++){
html += "<tr>" +
"<td class='isitbl'>" + data[i].idsoal + "</td>" +
"<td class='isitbl' style='width:20px;'>" + data[i].noesai + "</td>" +
"<td class='isitbl' style='width:200px;'>" + data[i].matakuliah + "</td>" +
"<td>" + data[i].isiesai + "</td>" +
"<td class='isitbl'><button class='btn btn-danger btn-block' id='hapus' data-id='" + data[i].idsoal + "'>" +
"<span class='icon-trash'></span> Hapus</button>" +
"</td>" +
"</tr>";
}
$("tbody#tblesai").html(html);
}
})
}
i change my controller
public function ambil($idsoal){
echo json_encode(
$this->pertanyaan_model
->ambilsoal($idsoal)->result());
}
and my model..
public function ambilsoal($idsoal){
$query = $this->db
->where("idsoal",$idsoal)
->get("tblsoalesai");
return $query;
}
and its works, thanks guys try to help me.. love you
I fixed the problem by calling a function, that graps the id of the table row it is placed in :)
I have this piece of code sorting some different stuff into a table, that works fine. The problem is to pass data into a function called inside HTML tags, like so:
See reference here
$.when(document, getTournamentsData()).done(function(){
var output = "";
$.each(tournamentsData, function(key, data){
output += "<tr class='data_row "+data.isOpen+"' id='"+data._id+"'>";
output += "<td>" + (key+1) + "</td>";
output += "<td><b>" + data.name + "</b></td>";
output += "<td>Start: " + data.begintime + "<br>Slut: " + data.endtime + "</td>";
output += "<td><input class='btn btn-primary' type='button' value='Se beskrivelse' onclick='showTourDescription(data.description)'/></td>";
output += "<td><input class='btn btn-primary' type='button' value='Se billede' onclick='showPic(data.image)'/></td>";
output += "<td>Max antal: "+ data.max_teams +"<br>Tilmeldte: "+ data.teams.length +"</td><br>";
output += "<td><input class='btn btn-primary' type='button' value='Se deltagere' onclick='showMembers(data.teams)'/></td>";
output += "<td>" + prizes(data.prices) + "</td>";
output += "</tr>";
});
output += "";
$('#data_insert').append(output);
});
All I do in the function is to console the data, and I get error "data is not defined"
This is the full script https://github.com/Jakobtottrup/OptekSemester2/blob/master/Web/public/js/tournaments_admin.js
// list tournaments
$.when(document, getTournamentsData()).done(function(){
var output = "";
$.each(tournamentsData, function(key, data){
output += "<tr class='data_row "+convertBoolean(data.isOpen)+"' id='"+data._id+"'>";
output += "<td>" + (key+1) + "</td>"; // index
output += "<td><b>" + data.name + "</b></td>"; // navn
output += "<td>Start: " + data.begintime + "<br>Slut: " + data.endtime + "</td>"; // start/slut
output += "<td><input class='btn btn-primary' type='button' value='Se beskrivelse' onclick='showTourDescription("+data.description+")'/></td>"; // beskrivelse TODO
output += "<td><input class='btn btn-primary' type='button' value='Se billede' onclick='showPic("+data.description+")'/></td>"; // billede
output += "<td>Max antal: "+ data.max_teams +"<br>Tilmeldte: "+ data.teams.length +"</td><br>"; // hold
output += "<td><input class='btn btn-primary' type='button' value='Se deltagere' onclick='showMembers("+data.teams"+)'/></td>"; // medlemmer
output += "<td>" + prizes(data.prices) + "</td>"; // præmier
output += "</tr>";
});
I've taken your code, and as you've done in the HTML strings themselves, concatenated in the event handlers too. Should be all you need to do.
UPDATE: Looks like you are passing data as string. See if that works
$.each(tournamentsData, function(data) {
onclick='showTourDescription(" + data.description + ")
i'm trying to display a table with jsonObject response, using loop for, to begin with objetosRetorna.Propiedad_Msg is always not null, so rows in table don't show anything just columns showing a error message
i'm not using AJAX.
Here is my code.
....
$.post("ListaUser.php",
{
IdPost: DatosJson },
function(objetosRetorna){
for (var i in objetosRetorna){
if(objetosRetorna.Propiedad_Msg=='Null'){
$("#tabla tbody").html("");
var nuevaFila=
"<tr>"
+"<td><a href='NewUser.php?a=" + objetosRetorna.Prop_id + "'><button type='button' class='btn btn-default light-green lighten-1'>Editar </button></a> <button type='button' onclick='Eliminar("+objetosRetorna.Prop_id+")' class='red lighten-1 btn btn-danger '>Eliminar</button></td>"
+"<td>"+objetosRetorna[i].Prop_titulo+"</td>"
+"<td>"+objetosRetorna[i].Prop_propiedad+"</td>"
+"<td>"+objetosRetorna[i].Prop_categoria+"</td>"
+"<td>"+objetosRetorna[i].Prop_direccion+"</td>"
+"<td>"+objetosRetorna[i].Prop_colonia+"</td>"
+"<td>"+objetosRetorna[i].Prop_coordenadas+"</td>"
+"<td>"+objetosRetorna[i].Prop_superficie+"</td>"
+"<td>"+objetosRetorna[i].Prop_recamaras+"</td>"
+"<td>"+objetosRetorna[i].Prop_imagenes+"</td>"
+"<td>"+objetosRetorna[i].Prop_precio+"</td>"
+"<td>"+objetosRetorna[i].Prop_antiguedad+"</td>"
+"<td>"+objetosRetorna[i].Prop_fecha+"</td>"
+"<td>"+objetosRetorna[i].Prop_descripcion+"</td>"
+"<td>"+objetosRetorna[i].Prop_prop_id+"</td>"
+"</tr>";
$(nuevaFila).appendTo("#tabla tbody");
}
if (objetosRetorna.Propiedad_Msg!="Null") {
var nuevaFila =
"<tr>"
+"<td colspan='5'><center><font color='red'>"+objetosRetorna.Propiedad_Msg+"</font></center></td>"
+"</tr>";
$(nuevaFila).appendTo("#tabla tbody");
}
}
},"json");
Json Response
[{"Prop_id":"32",
"Prop_titulo":"Mi titulo de propiedad",
"Prop_propiedad":"Casa",
"Prop_categoria":"Renta",
"Prop_direccion":"Calle Term",
"Prop_colonia":"Progreso",
"Prop_coordenadas":"499965",
"Prop_superficie":"40m2",
"Prop_recamaras":"5",
"Prop_imagenes":"imagenes",
"Prop_precio":"4500","Prop_antiguedad":"15 a\u00f1os","Prop_fecha":"0000-00-00",
"Prop_descripcion":"Departamen","Prop_prop_id":"10",
"Propiedad_Msg":"Null"}....]
Thank you.
Hope somebody can help me
UPDATE.... TypeError: objetosRetorna.map is not a function[Saber más]index.php:62:30
function(objetosRetorna) {
var rows = objetosRetorna.map (function(objeto){
if (objeto.Propiedad_Msg == 'Null') {
return "<tr>" +
"<td><a href='NewUser.php?a=" + objeto.Prop_id + "'><button type='button' class='btn btn-default light-green lighten-1'>Editar </button></a> <button type='button' onclick='Eliminar("+objeto.Prop_id+")' class='red lighten-1 btn btn-danger '>Eliminar</button></td>"+
"<td>"+objeto.Prop_titulo+"</td>"+
"<td>"+objeto.Prop_propiedad+"</td>"+
"<td>"+objeto.Prop_categoria+"</td>"+
"<td>"+objeto.Prop_direccion+"</td>"+
"<td>"+objeto.Prop_colonia+"</td>"+
"<td>"+objeto.Prop_coordenadas+"</td>"+
"<td>"+objeto.Prop_superficie+"</td>"+
"<td>"+objeto.Prop_recamaras+"</td>"+
"<td>"+objeto.Prop_imagenes+"</td>"+
"<td>"+objeto.Prop_precio+"</td>"+
"<td>"+objeto.Prop_antiguedad+"</td>"+
"<td>"+objeto.Prop_fecha+"</td>"+
"<td>"+objeto.Prop_descripcion+"</td>"+
"<td>"+objeto.Prop_prop_id+"</td>"+
"</tr>";
}
return "<tr>" +
"<td colspan='5'><center><font color='red'>"+objeto.Propiedad_Msg+"</font></center></td>"+
"</tr>";
});
$("#tabla tbody").html(rows.join(""));
}
);
Objects, {}, in JavaScript does not have the method .map(), it's only for Arrays, [].
So in order for your code to work change data.map() to data.props.map()
And json response to something like
{"props":[
{"Prop_id":"32"},
{"Prop_titulo":"Mi titulo de propiedad"},
{"Prop_propiedad":"Casa"},
{"Prop_categoria":"Renta"},
{"Prop_direccion":"Calle Term"},
...]}
Something to read .map() on:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
PS. if you just want to iterate json and you can make your props into array you can iterate objects like this:
for (var key in objetosRetorna) {
if (objetosRetorna.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
If you need more in-depth fix or explanation please leave a comment.
You need to refer to the entry you're looping over. Instead of
for (var i in objetosRetorna){
if(objetosRetorna.Propiedad_Msg=='Null'){
you would want
for (var i in objetosRetorna){
if(objetosRetorna[i].Propiedad_Msg=='Null'){
// --------------^^^
You make the same small mistake later with objetosRetorna.Prop_id a couple of times.
But, for-in isn't the correct way to loop through an array. You have lots of options, but here I'd probably use forEach.
Also, unrelated, but you have
if (objetosRetorna.Propiedad_Msg == 'Null') {
and then immediately after that
if (objetosRetorna.Propiedad_Msg != 'Null') {
In that situation, you can just use else to avoid the maintenance issue of having the condition repeated.
You're also removing everything from the table when adding each row, which means you'll end up with just the last row. So instead of forEach, let's use map to return an array of row strings:
So taking all that together (see *** comments):
$.post("ListaUser.php", {
IdPost: DatosJson
},
function(objetosRetorna) {
// *** Note use of `map` to get a string for each row
var rows = objetosRetorna.map(function(objecto) { // *** We receive each entry as the `objecto` argument
// Use `objeto` for the various things below
if (objeto.Propiedad_Msg == 'Null') {
return "<tr>" +
"<td><a href='NewUser.php?a=" + objeto.Prop_id + "'><button type='button' class='btn btn-default light-green lighten-1'>Editar </button></a> <button type='button' onclick='Eliminar(" + objeto.Prop_id + ")' class='red lighten-1 btn btn-danger '>Eliminar</button></td>" +
"<td>" + objetos.Prop_titulo + "</td>" +
"<td>" + objetos.Prop_propiedad + "</td>" +
"<td>" + objetos.Prop_categoria + "</td>" +
"<td>" + objetos.Prop_direccion + "</td>" +
"<td>" + objetos.Prop_colonia + "</td>" +
"<td>" + objetos.Prop_coordenadas + "</td>" +
"<td>" + objetos.Prop_superficie + "</td>" +
"<td>" + objetos.Prop_recamaras + "</td>" +
"<td>" + objetos.Prop_imagenes + "</td>" +
"<td>" + objetos.Prop_precio + "</td>" +
"<td>" + objetos.Prop_antiguedad + "</td>" +
"<td>" + objetos.Prop_fecha + "</td>" +
"<td>" + objetos.Prop_descripcion + "</td>" +
"<td>" + objetos.Prop_prop_id + "</td>" +
"</tr>";
}
// It's not null
return "<tr>" +
"<td colspan='5'><center><font color='red'>" + objeto.Propiedad_Msg + "</font></center></td>" +
"</tr>";
});
// *** Now we replace the table contents with the strings (joined into one string)
$("#tabla tbody").html(rows.join(""));
}
);
I have written JavaScript which retrieves data and sets it into a series of tables as shown below.
$(function()
{
$.ajax(
{
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'9BBF789F-E5BA-449D-A595-BAA326E2C8FF')/Items?$expand=Category&$select=Id,Related_x0020_Working_x0020_PracId,Title,Reference,Policy_x0020_Type,Category/Title&$orderby=Category/Title asc",
type:"get",
headers: { "accept": "application/json;odata=verbose" },
success: function(dataObj)
{
//to uniquely identifiy the accordion.
var intCat = 0;
var arrPolicies = [];
var arrCategories = [];
//Get the policies and seperate out the categories from the returned REST call
for(var i =0; i < dataObj.d.results.length; i++)
{
var strCategory = dataObj.d.results[i].Category.Title;
arrPolicies.push({
"Id" : dataObj.d.results[i].Id,
"Title" : dataObj.d.results[i].Title,
"Category" : strCategory,
"Ref" : dataObj.d.results[i].Reference,
"PolicyType" : dataObj.d.results[i].Policy_x0020_Type,
"WorkingPracticeId" : dataObj.d.results[i].Related_x0020_Working_x0020_PracId
});
//setting category if not found
//in array
if(arrCategories.indexOf(strCategory) == -1)
{
//Add the category to the list...
arrCategories.push(strCategory);
}
}
//Output the menu to the screen for each category - one by one
arrCategories.forEach(function(varCategory)
{
var strCatIdentifier = "tblCategory_" + intCat;
var strCatImgIdentifier = "tblCategory_image_" + intCat;
var strCategoryInfo = "<table>"+
"<tbody>" +
"<tr>"+
"<td class='category'>"+
"<a href='javascript:ExpandCollapseRow(" + strCatIdentifier + ","+strCatImgIdentifier+")'>"+
"<img id='"+strCatImgIdentifier+"' src='" + _spPageContextInfo.webAbsoluteUrl + "/SiteAssets/Images/expand-16.png' alt='expand category'/>"+
"</a> "+
varCategory +
"</td>"+
"</tr>"+
"<tr><td>"+
"<table id='" + strCatIdentifier + "' class='indent hidden'>";
//looping through policies - add the details into the category table's cell
arrPolicies.forEach(function(varPolicy)
{
//checking the category attached to the policy is the same as what
//category it is on
if(varPolicy.Category == varCategory)
{
//checking to see if the
if(varPolicy.PolicyType == "Policy and Responsibility")
{
strCategoryInfo += "<tr>"+
"<td class='policy'>" +
"<a href='#'>"+
"<img src='"+_spPageContextInfo.webAbsoluteUrl+"/SiteAssets/Images/arrowicon.png' alt='View Document'/>"+
"</a>"
+ varPolicy.PolicyType + ": "+varPolicy.Ref +" - " + varPolicy.Title +
"</td>"+
"</tr>";
}
//If Working Practice - add in the sub-table (3rd level table) for attachments
if(varPolicy.PolicyType == "Working Practices")
{
var strCatWPIdentifier = "tblWorkingPractice" + varPolicy.Id;
var strCatWPImgIdentifier = "sub_level_image" + varPolicy.Id;
strCategoryInfo += "<tr>"+
"<td class='working_practice'>"+
"<a href='javascript:ExpandCollapseRow(" + strCatWPIdentifier + ","+strCatWPImgIdentifier+")'>"+
"<img id='"+strCatWPImgIdentifier+"' src='" + _spPageContextInfo.webAbsoluteUrl + "/SiteAssets/Images/expand-16.png' alt='expand working practice'/>"+
"</a> "+
varPolicy.PolicyType + " - " + varPolicy.Title+
"</td>"+
"</tr>";
var intAttachmentCount = 0;
//Build a table by looping through the policies array AGAIN and only use the policies where the Policy Type is 'Attachment' AND the 'WorkingPracticeID' is the same as the pilocy ID
arrPolicies.forEach(function(varWPAttachment)
{
if(varWPAttachment.WorkingPracticeId == varPolicy.Id && varWPAttachment.PolicyType == "Working Practice Attachment")
{
intAttachmentCount++;
strCategoryInfo += "<tr>"+
"<td>"+
"<table id='"+strCatWPIdentifier+"' class='indent hidden'>"+
"<tr>"+
"<td>"+
varWPAttachment.PolicyType +" - "+ varWPAttachment.Title+ " - " + varPolicy.Title+
"</td>"+
"</tr>"+
"</table>"+
"</td>"+
"</tr>";
}
});
if(intAttachmentCount == 0)
{
strCategoryInfo += "<tr>"+
"<td>"+
"<table id='"+strCatWPIdentifier+"' class='indent hidden'>"+
"<tr>"+
"<td>"+
"Sorry, no attachments found for this practice."+
"</td>"+
"</tr>"+
"</table>"+
"</td>"+
"</tr>";
}
}
}
});
//Close the 'Category details' table
strCategoryInfo += "</table>";
//Close the table for the category...
strCategoryInfo += "</td></tr>" +
"</tbody>"+
"</table>";
intCat++;
$('#divQualityFrameworkMenu').append(strCategoryInfo + "<br />");
});
},
error: function(error)
{
alert("Error");
}
});
});
I want to be able to organise them so that related data is grouped together ie Policies are above working practices.
How would I go about doing this
This seems pretty easy. After the first for (var d = 0; [...] ) loop, but before the arrCategories.forEach([...]), just sort arrPolicies to your choosing:
arrPolicies.sort(function(policy1, policy2) {
//Policies BEFORE Working Practicies:
if (policy1.PolicyType === "Policies and Responsibilities" && policy2.PolicyType === "Working Practices") {
return -1;
}
//Working Practicies AFTER Policies:
if (policy1.PolicyType === "Working Practices" && policy2.PolicyType === "Policies and Responsibilities") {
return 1;
}
//[Include any other orderings you might have...]
//If you've reached the end here, then you must not care about the ordering of these policies, so just make them "equal":
return 0;
});