Display Array Object With Jquery - javascript

I want displaying object data in table, which value inside name of object appear as <td>,
i have result in the network preview like this below:
I need displaying value inside A1_score and A2_score as <td>, so i tried jquery like this:
$(document).on('click', '#cektesting', function(e) {
$('.row').css({ 'visibility': 'hidden', 'display': 'none' });
$.ajax({
url: "pengguna/getCounting",
type: "GET",
dataType: "JSON",
success: function(data) {
$('.row').css({ 'visibility': 'visible', 'display': 'flex' });
$.each(data['A1_score', 'A2_score'], function(key, value) {
$('#tbodyres').append(
'<tr id="idscore"><td>' + key + '</td><td>' + value + '</td><td>' + value + '</td></tr> '
);
});
}
});
});
And last thing those data came from my Controller.php:
public function getCounting()
{
$get_row_class = $this->getdata->getAutism();
$get_row = $this->getdata->countrow();
$row_autism = $get_row_class['Autism'];
$row_normal = $get_row_class['Normal'];
$res_autism = number_format($row_autism / $get_row['jml_data_latih'], 6);
$res_normal = number_format($row_normal / $get_row['jml_data_latih'], 6);
$A_Score = $this->getdata->getA_score();
$data = [];
foreach ($A_Score as $as) {
$row['A_Y_NORMAL'] = $as['A1_YES_NORMAL'] / $row_normal;
$row['A_Y_AUTIS'] = $as['A1_YES_AUTIS'] / $row_autism;
$row['A_N_NORMAL'] = $as['A1_NO_NORMAL'] / $row_normal;
$row['A_N_AUTIS'] = $as['A1_NO_AUTIS'] / $row_autism;
$row2['A_Y_NORMAL'] = $as['A2_YES_NORMAL'] / $row_normal;
$row2['A_Y_AUTIS'] = $as['A2_YES_AUTIS'] / $row_autism;
$row2['A_N_NORMAL'] = $as['A2_NO_NORMAL'] / $row_normal;
$row2['A_N_AUTIS'] = $as['A2_NO_AUTIS'] / $row_autism;
$data['A1_score'] = $row;
$data['A2_score'] = $row2;
}
echo json_encode($data);
}
Result:
And this is what i get when i tried build jquery from jquery code above, So i get A2_score data but A1_score didn't displaying only A2_score data get looped.

You can get all keys inside your object and then use that keys to get required data from both JSON Object .
Demo Code :
//just for demo..
var data = {
"A1_score": {
"xs": 12322,
"sse": 1232
},
"A2_score": {
"xs": 1234,
"sse": 213
}
}
//get keys of one object because keys in other object are same
var keys = Object.keys(data["A1_score"])
console.log(keys)
//loop through keys
for (var i = 0; i < keys.length; i++) {
var keys_ = keys[i]
//add that inside your table
$('#tbodyres').append(
'<tr class="idscore"><td>' + keys_ + '</td><td>' + data["A1_score"][keys_] + '</td><td>' + data["A2_score"][keys_] + '</td></tr> '
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbodyres"></table>

You can not use data['A1_score', 'A2_score'] to iterate over properties A1_score & A2_score. What you should do is iterate over either A1_score or A2_score and retrieve key. Then get values from A1_score & A1_score with data["A1_score"][key] & data["A2_score"][key].
Try like below.
$.each(data["A1_score"], function(key, value) {
$('#tbodyres').append(
'<tr id="idscore"><td>' + key + '</td><td>' + data["A1_score"][key] + '</td><td>' + data["A2_score"][key] + '</td></tr> '
);
});

Related

Get Django variable in Javascript : undefined value

I have a little issue and I don't overcome to solve it. I have a list of Django objects generated in my views.py file and I would like to display these variables in my Javascript part.
I get the list in my Javascript code, but each variable are 'undefined'.
In my views.py file, I have :
context['results2'] = SubMethod.objects.values_list('name', flat=True).all()
with this model :
class SubMethod(EdqmTable):
name = models.CharField(verbose_name=_('name'), max_length=80, unique=True)
def __str__(self):
return self.name
Then, in my HTML/JS part :
function get_sub_method_options(keep_cur) {
var sel_option = $('select#id_method-group').find("option:selected");
var sel_val = sel_option.val();
if (!sel_val) {
$("select#id_method-sub_method").empty();
var all_sub_methods = "{{ results2 }}";
console.log(all_sub_methods.name);
for (var i = 0; i < all_sub_methods.length; i++) {
$("select#id_method-sub_method").append('<option value="' + all_sub_methods[i].id + '">' + all_sub_methods[i].name + '</option>'); //here add list of all submethods
}
return;
}
data = {
'test_method': $('select#id_method-test_method').find("option:selected").val(),
'group': sel_val
};
$.ajax({
method: "GET",
url: '{% url 'ajax_method_submethod' %}',
data: data
}).done(function (result) {
reset_select('id_method-sub_method');
for (var i = 0; i < result['results'].length; i++) {
if (keep_cur > 0 & keep_cur == result['results'][i].id)
$("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '" selected>' + result['results'][i].text + '</option>');
else
$("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '">' + result['results'][i].text + '</option>');
}
;
});
}
As you can see, I pick up my context variable result2 in this part :
if (!sel_val) {
$("select#id_method-sub_method").empty();
var all_sub_methods = "{{ results2 }}";
console.log(all_sub_methods.name);
for (var i = 0; i < all_sub_methods.length; i++) {
$("select#id_method-sub_method").append('<option value="' + all_sub_methods[i].id + '">' + all_sub_methods[i].name + '</option>'); //here add list of all submethods
}
return;
}
In my terminal I get :
<QuerySet ['50% cell culture infective dose (CCID50)', 'Acetic acid in synthetic peptides', 'Acid value', 'Adenylate cyclase', ...]>
But in my Javascript part, it displays this :
Do you have any idea why ?
EDIT :
In my django code, count() displays 450
In my JS code : length display 684
In my database : I have 450 elements
You need to convert your queryset to a list first. JS does not read querysets.
context['results2'] = list(SubMethod.objects.values_list('name', flat=True).all())
and you may want to skip wrapping results2 in quotes on the JS side and ass safe` to prevent escaping characters:
var all_sub_methods = {{ results2|safe }};

How to convert the values in an array to strings and send to php?

I have a javascript file here.What it does is,when a user selects seats accordings to his preference in a theater layout,the selected seats are stored in an array named "seat".This code works fine until function where the selected seats are shown in a window alert.But from there onwards,the code doesn't seem to do anything.
After the above window alert, I've tried to serialize the above array and send it to the "confirm.php" file.But it does not show anything when echoed the seats.
Here is the js code.
<script type="text/javascript">
$(function () {
var settings = {
rows: 6,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 80,
seatHeight: 80,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
var jArray = <?= json_encode($seats) ?>;
init(jArray);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('This seat is already reserved!');
} else {
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShowNew').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
});
$('#btnsubmit').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
var seatar = JSON.stringify(seat);
$.ajax({
method: "POST",
url: "confirm.php",
data: {data: seatar}
});
});
});
});
</script>
Can somebody help me figure it out what's wrong in here?
Please Add content type as json.
$.ajax({
method: "POST",
url: "confirm.php",
contentType: "application/json"
data: {data: seatar}
});
For testing you can print file_get_contents('php://input') as this works regardless of content type.

How to create new Tags from results containing delimiter " USE "?

Updated Question
So I am running a query and some of the results have the structure "keyword USE 1 or more keywords". When a user selects entries like this, I want the input field to show the keyword(s) to the right of USE. I got it to work for the first select thanks to #DavidDomain, but now I have a new Problem. The selects goes wild after the first selection. I tried to create a Jsfiddler, but I can't seem to get it to work correctly. I copied code directly from my IDE. Here is the original project. If you type in USE and select one of the options, it works perfectly. If you try another selection then it goes crazy. Here is the JSFiddle I tried to create that shows what I did to get to this point.
$('.productName').select2({
ajax: {
url: "https://api.myjson.com/bins/9t7gz",
dataType: 'json',
type: "GET",
delay: 250,
data: function(params) {
return {
key: params.term // search term
};
},
processResults: function(data) {
for (var d = 0; d < data.length; d++) {
if (data[d].text.includes(" USE ")) {
var dataItems = data[d].text.split(" USE ");
if (dataItems[1].toString().includes(";")) {
var dataKeywordItems = dataItems[1].toString().split(";");
for (var ii = 0; ii < dataKeywordItems.length; ii++) {
var option3 = new Option(dataKeywordItems[ii].toString().trim(), dataKeywordItems[ii].toString().trim(), true);
$('.productName').append(option3);
}
} else {
var option = new Option(dataItems[1], dataItems[1], true);
$('.productName').append(option);
}
}
}
return {
results: data
};
},
cache: true
},
placeholder: 'Keyword/keyphrase search...',
minimumInputLength: 2,
tags: true
}).on("select2:select", function(e) {
var splitValues = $('.productName').val().toString().split(" USE ");
if (splitValues[1].includes("; ")) {
var splitKeywords = splitValues[1].toString().split("; ");
$('.productName').val(splitKeywords).trigger("change");
alert(splitKeywords.toString());
// for(var i = 0; i < splitKeywords.length; i++)
// {
// alert(splitKeywords[i].toString().trim());
// $('.productName').val(splitKeywords[i].toString().trim()).trigger("change");
// }
} else {
$('.productName').val(splitValues[1]).trigger("change");
}
});
.select2-selection__rendered {
line-height: 32px !important;
}
.select2-selection {
height: 34px !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://npmcdn.com/tether#1.2.4/dist/js/tether.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<div class="container">
<div class="row">
<span class='input-group-btn col-lg-12 col-md-12 col-sm-12'>
<select style="width:70%;" class='productName ' id='productName' width=>
</select>
</span>
</div>
</div>
The two important parts of my code are below:
ProcessResults:
If a keyword contains " USE " this takes the one or more keywords to the right of " USE " and dynamically adds them to the dropdown list.
processResults: function (data) {
for(var d = 0; d < data.length; d++)
{
if(data[d].text.includes(" USE "))
{
var dataItems = data[d].text.split(" USE ");
if(dataItems[1].toString().includes(";"))
{
var dataKeywordItems = dataItems[1].toString().split(";");
for(var ii = 0; ii < dataKeywordItems.length; ii++)
{
var option3 = new Option(dataKeywordItems[ii].toString().trim(), dataKeywordItems[ii].toString().trim(), true);
$('.productName').append(option3);
}
}
else
{
var option = new Option(dataItems[1], dataItems[1], true);
$('.productName').append(option);
}
}
}
return {
results: data
};
},
On select:
This takes a selected keyword that contains " USE " and extracts the 1 or more keywords to the right of " USE " and diplays them in the input field.
.on("select2:select", function(e) {
var splitValues = $('.productName').val().toString().split(" USE ");
if(splitValues[1].includes("; "))
{
var splitKeywords = splitValues[1].toString().split("; ");
$('.productName').val(splitKeywords).trigger("change");
alert(splitKeywords.toString());
// for(var i = 0; i < splitKeywords.length; i++)
// {
// alert(splitKeywords[i].toString().trim());
// $('.productName').val(splitKeywords[i].toString().trim()).trigger("change");
// }
}
else
{
$('.productName').val(splitValues[1]).trigger("change");
}
});
A screenshot of the first select:
A screenshot of a potential second select:
The question is how can I keep the first select results and add the new second select results?
You could use the formatSelection method to change how the selected option should be displayed.
Here is an example:
function format(state) {
if (state.text.indexOf('USE') !== -1) {
return state.text.substring(state.text.indexOf('USE') + 4, state.text.length);
}
return state.text;
}
$('#test').select2({
data:[
{id:0,text:"enhancement"},
{id:1,text:"bug"},
{id:2,text:"duplicate USE copy"},
{id:3,text:"invalid USE wrong; incorrect"},
{id:4,text:"wontfix"}
],
multiple: true,
width: "300px",
formatSelection: format,
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.min.js"></script>
<input type="hidden" id="test" />
I can't get the crappy JsFiddles to work, so I am going to post my answer from my original problem. The process is the same. After a lot of searching and mixing different answers together, I came up with this solution.
$('.productName').select2({
ajax: {
url: "DBHandler.php",
dataType: 'json',
type: "GET",
delay: 250,
data: function (params) {
return {
key: params.term // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
placeholder: 'Keyword/keyphrase search...',
minimumInputLength: 2,
tags: true
}).on("select2:select", function(e) {
var valueToRemove = e.params.data.id;
if(valueToRemove.toString().includes(" USE "))
{
var splitValues = valueToRemove.toString().split(" USE ");
if(!splitValues[1].toString().includes(";"))
{
alert("value does not contain ;");
new_data = $.grep($('.productName').val(), function(id){return id !== valueToRemove;});
alert("new data: " + new_data);
$('.productName > option').prop("selected", false);
$('.productName').val(new_data).trigger('change');
$('.productName').append("<option value = '" + splitValues[1].toString().trim() + "' selected>" + splitValues[1].toString().trim() + "</option>");
}
else
{
var splitKeys = splitValues[1].toLocaleString().split(";");
new_data = $.grep($('.productName').val(), function(id){return id !== valueToRemove;});
$('.productName > option').prop("selected", false);
$('.productName').val(new_data).trigger('change');
splitKeys.forEach(function(item)
{
alert(item);
$('.productName').append("<option value = '" + item.toString().trim() + "' selected>" + item.toString().trim() + "</option>");
});
}
}
});
The onSelect code is the key to solving this problem.
on("select2:select", function(e) {...});
I started by getting the value that is being selected. If this value contains " USE ", I do not want it to be included in the InputField values.
var valueToRemove = e.params.data.id;
I then split this value using " USE " as the delimiter. If the keyword(s) to the right of " USE " do not contain a semi-colon ;, I create an array new_data that holds all of the InputField's current values except the value that is being selected. I then, deselect all of the current selected values using $('.productName > option').prop("selected", false);. Next, I added all of the old selected values back using $('.productName').val(new_data).trigger('change');. Finally, I append the new keyword that was extracted from the original selected value using $('.productName').append("<option value = '" + splitValues[1].toString().trim() + "' selected>" + splitValues[1].toString().trim() + "</option>");. This handles the case of having only one keyword after " USE ". Example keyword: Not smart USE dumb. When this is select only dumb shows up as a keyword in the InputField.
if(valueToRemove.toString().includes(" USE "))
{
var splitValues = valueToRemove.toString().split(" USE ");
if(!splitValues[1].toString().includes(";"))
{
alert("value does not contain ;");
new_data = $.grep($('.productName').val(), function(id){return id !== valueToRemove;});
alert("new data: " + new_data);
$('.productName > option').prop("selected", false);
$('.productName').val(new_data).trigger('change');
$('.productName').append("<option value = '" + splitValues[1].toString().trim() + "' selected>" + splitValues[1].toString().trim() + "</option>");
}
else{
.
.
.
}
}
In the case where the keyword(s) to the right of " USE " contains a semi-colon ;, I first split the string to the right of " USE " on the semi-colon ; using var splitKeys = splitValues[1].toLocaleString().split(";");. This gives me all of the keywords that should be added to the InputField. Next, I take the exact same step to repopulate the InputField's values.
new_data = $.grep($('.productName').val(), function(id){return id !== valueToRemove;});
$('.productName > option').prop("selected", false);
$('.productName').val(new_data).trigger('change');
I then use a loop to add all of the new keywords that should be added to the input field using:
splitKeys.forEach(function(item)
{
alert(item);
$('.productName').append("<option value = '" + item.toString().trim() + "' selected>" + item.toString().trim() + "</option>");
});
This handles the case of having more than one keyword after " USE ". Example keyword: Not smart USE dumb; stupid. When this is select dumb and stupid show up as keywords in the InputField.
if(valueToRemove.toString().includes(" USE "))
{
var splitValues = valueToRemove.toString().split(" USE ");
if(!splitValues[1].toString().includes(";"))
{
.
.
.
}
else{
var splitKeys = splitValues[1].toLocaleString().split(";");
new_data = $.grep($('.productName').val(), function(id){return id !== valueToRemove;});
$('.productName > option').prop("selected", false);
$('.productName').val(new_data).trigger('change');
splitKeys.forEach(function(item)
{
alert(item);
$('.productName').append("<option value = '" + item.toString().trim() + "' selected>" + item.toString().trim() + "</option>");
});
}
}

Datatables row reorder event issue

var table =$("#exampleList").DataTable({
paging:false,
rowReorder:false
}
});
table.on('row-reorder',function(e, diff,edit){
for(var i=0, ien = diff.length ; i<ien ; i++){
var rowData = table.row(diff[i].node).data();
sequence = sequence + "_" + rowData[0];
}
var data = table.rows().data();
data.each(function (value, index) {
alert('Data in index: ' + index + ' is: ' + value);
});
});
Hi,
I am new to datatables. Issue I am having right now is I cant get the latest value in my table after the user reorder the row. The code above only shows the value before the reorder occurs. I need to get the latest reorder sequence so I can update the database.
What you need to do is wait a few milliseconds before trying to read the data.
table.on('row-reorder',function(e, diff, edit){
for(var i=0, ien = diff.length ; i<ien ; i++){
var rowData = table.row(diff[i].node).data();
sequence = sequence + "_" + rowData[0];
}
setTimeout(()=> { lookAtData() }, 10);
});
function lookAtData() {
var data = table.rows().data();
data.each(function (value, index) {
alert('Data in index: ' + index + ' is: ' + value);
});
}
You should use column-reorder not row-reorder.
Please try :
var rdata = table .columns().order().data();
console.log(rdata);
It will get the data after columns ordering.

How to send table column values from a Javascript page to a C# page using Jquery

I have values that come from a dynamically created table from it's selected rows. inside each selected row i want all the td.innerText values that belong to be sent to a C# page, but i don't know how to. I was using JSON but I dont know if i used it properly.
function selectedRows()
{
var selectedItems = $('#ScannedLabelTable').find(':checkbox:checked').parents('tr');
var serial, kanbanNumber, customer, description, quantity;
$.each(selectedItems, function (i, item) {
var td = $(this).children('td');
for (var i = 0; i < td.length; ++i)
{
serial = td[1].innerText;
kanbanNumber = td[2].innerText;
customer = td[3].innerText;
description = td[4].innerText;
quantity = td[5].innerText;
}
console.log(serial + ' ' + kanbanNumber + ' ' + customer + ' ' + description + ' ' + quantity);
});
$.ajax({
url: SEND_TO_TEXTFILE_PAGE
, data: "labelSerial=" + serial + "&kanbanNumber=" + kanbanNumber + "&customer="
+ customer + "&description=" + description + "&quantity=" + quantity
, dataType: 'json'
, success: function (status) {
if (status.Error) {
alert(status.Error);
}
}
, error: Hesto.Ajax.ErrorHandler
});
}
EDIT: sorry I must have read this too quickly. This should do it. create an array and add the data object to it in the loop.
If you just create a json object using key value pairs you can send that object to your c# controller.
function selectedRows() {
var selectedItems = $('#ScannedLabelTable').find(':checkbox:checked').parents('tr');
var serial, kanbanNumber, customer, description, quantity;
var dataArray = new Array();
$.each(selectedItems, function (i, item) {
var td = $(this).children('td');
for (var i = 0; i < td.length; ++i)
{
var InfoObject = {
serial: td[1].innerText;
kanbanNumber: td[2].innerText;
customer: td[3].innerText;
description: td[4].innerText;
quantity: td[5].innerText;
};
dataArray.push(InfoObject);
}
});
$.ajax({
url: SEND_TO_TEXTFILE_PAGE
, data: dataArray
, dataType: 'json'
, success: function (status) {
if (status.Error) {
alert(status.Error);
}
}
, error: Hesto.Ajax.ErrorHandler
});
}

Categories