Replace DataTables data and column headers - javascript

I can successfully replace the DataTable's data, but not the columns. I am sure I can figure out how to change the column header text, however, this will not work should the column count change. How should one replace both the data and the column header names?
var dataTables;
document.getElementById('query-form').addEventListener('submit', function(event){
event.preventDefault();
var url = getUrl();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.response);
if (dataTables) {
console.log(dataTables)
dataTables.clear();
dataTables.rows.add(json.results.data);
//dataTables.columns.add(json.results.columns);
dataTables.draw();
}
else {
dataTables = $('#datatables').DataTable( {
data: json.results.data,
columns: json.results.columns,
} );
}
}
};
xhttp.open("GET", url);
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhttp.send();
});

You can manage your data call response like data and column array then put my code in your ajax call or any other calls and solve your dynamic column problem in DataTables.
jQuery(document).ready(function() {
var dataObject = eval('[{"COLUMNS": [{ "title": "Col1"}, { "title": "Col2"}], "DATA":[["RP","1"],["Billy","2"],["GP","3"],["MM","4"]]}]');
var columns = [];
$('#demoexample').dataTable({
"data": dataObject[0].DATA,
"columns": dataObject[0].COLUMNS
});
});

Related

JS: HTML is not dynamically changing

I am building an web that allows user to like a post when they click a button. CreateLike function calls API and creates a like object however, I would like to have the number of likes updated right away without reloading. I built another API that returns the number of likes for a post. Function LikeCount should put the number of likes into the p tag. It works initially when I load the page however, the value does not change when I click the button even though I can see that the API is called. (After reloading the page the number changes as expected) What am I doing wrong?
I have this HTML:
<p class="like-count" id={{post.id}}></p>
<script>LikeCount({{post.id}});</script>
<button type="button" class="btn-like" onclick="CreateLike({{user.id}},{{post.id}})"></button>
with JS functions:
function CreateLike (userid,postid) {
xhr = new XMLHttpRequest();
var url = "{% url 'likes' %}";
var csrftoken = getCookie('csrftoken')
xhr.open("POST", url, true);
xhr.setRequestHeader("X-CSRFToken",'{{ csrf_token }}')
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.name)
}
}
var data = JSON.stringify({csrfmiddlewaretoken:csrftoken,"user":userid,"post":postid});
xhr.send(data);
LikeCount(postid);
}
function LikeCount(postid) {
var xmlhttp = new XMLHttpRequest();
var url = "{% url 'likecount' id=112233 %}".replace("112233", postid);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = arr.like_count;
document.getElementById(postid).innerHTML = out;
}
}
Like count API looks like this:
{
"like_count": 1
}
if(xhr.readyState === XMLHttpRequest.DONE) {
var status = xhr.status;
if (status === 0 || (status >= 200 && status < 400)) {
LikeCount(); //Put your get like count here
} else {
// Handle Errors
}
}
Call LikeCount only after receiving the response of your POST request. Right now you're immediately sending a GET request without ensuring if the previous POST request got completed.
Added
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 201) {
var myArr = JSON.parse(this.responseText);
LikeCount(myArr.post);
}
};
before
xhr.send(data);
and it fixed the issue.

Dynamically filling drop downs on each row of table

I have a table with n number of rows depending on results. There is a drop down on the top of the page. Depending on the selection of that drop down I want to dynamically fill a column on each row with a drop down of its own, based off of an xhttp.response.
This is what I have so far:
function getJobs(taskID){
var xhttp = new XMLHttpRequest();
var url = "dynamicdd.php";
var data = new FormData();
data.append('taskID', taskID);
xhttp.open('POST', url, true);
xhttp.send(data);
$('#cTable tr').each(function(){
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("testSelect").innerHTML = xhttp.responseText;
}
}
});
}
I'm able to change the first row successfully, but subsequent rows don't. I've tried $(this).find(select:eq(0)).html() in replace of the document.getElementById() but no luck. I feel like I'm close but lack expertise in jquery/javascript. Thanks for your help.
You are re-assinging onreadystatechange function for each table row which is wrong,
First assing the function for what it must do,
then send the request
then wait for the response ready
then seek the element you want and replace element html with response text as below,
function getJobs(taskID){
var xhttp = new XMLHttpRequest();
var url = "dynamicdd.php";
var data = new FormData();
data.append('taskID', taskID);
xhttp.open('POST', url, true);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
$('#cTable tr').each(function(index, element){
$(element).find('#testSelect').html(xhttp.responseText);
}
}
});
xhttp.send(data);
}

Sort table values that have been imported from Google Sheets using Javascript

When I am importing data into a table, I am not able to use the table-sorter feature that allows me to click on table headings and automatically sort data ascending/descending. The code I use for table sorting is:
$(function(){
$('#grades').tablesorter();
});
Is there any way that I am able to sort data that is pulled in from Google Sheets? I am assuming it is not working because the data being pulled in isn't actually being displayed in my code editor so there aren't any values to sort. I'd appreciate the help! Thanks
Here is an example of the code I am using to import cell data from Google Sheets:
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
httpGetAsync('https://spreadsheet.glitch.me/?key=1JBbAHH1DFtO1r56lr94lUqd8H7qPcHncJskcPq0r96o', function(response) {
var json = JSON.parse(response);
document.getElementById("Title").innerHTML = json[0].Title;
document.getElementById("Name").innerHTML = json[0].Name;
document.getElementById("Car").innerHTML = json[0].Car;
let divs = Array.prototype.slice.call(document.querySelectorAll("#Name, #Car"));
divs.forEach(function(div) {
// Convert text to number and test for positive/negative
if ((+div.textContent) >= 0) {
div.textContent = "+" + div.textContent;
}
});
});

XMLHttpRequest don't include GET request

I'm trying to retrieve JSON data using XMLHttpRequest but it seems like it won't include any of my field data.
var fields = ["ID", "item_id", "item_tag", "item_name", "item_default_price", "item_quantity", "item_comment"];
function loadTable(json_items) {
alert(json_items);
}
var frm = document.querySelector("form.inventory-search-form");
frm.onsubmit = function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (this.readyState === DONE && this.status == 200){
try {
loadTable(JSON.parse(this.responseText));
} catch(err) {
}
}
};
request.open('GET', '/api/inventory/list', true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // Tells server that this call is made for ajax purposes.
// Most libraries like jQuery/Prototype/Dojo do this
var data = new FormData(frm);
for (i=0; i<fields.length; i++) {
data.append(fields[i], frm.querySelector("[name='" + fields[i] + "']").value);
}
request.send(data);
}
frm.onsubmit(document.createEvent("Event"));
What did I do wrong?
I have checked the FormData and it contained the fields, but it didn't make the required GET request such as /api/inventory/list?ID=2 instead it only issued /api/inventory/list.
Thanks!

how to create radio buttons by JS.

i have some problrm creating the radio buttons dynamically. in my problem i am requesting data from server in json formate than i check if it contains options i have to create the radio buttons otherwise simply creates the txt area of field to submit the answer. than again i parse it in json formate and send to the server and if my question is write i get new url for next question and so on...
my question is how can i create the radio buttons and read the data from it and than parse that data like {"answer": "something"}.my code is bellow:
enter code herefunction loadDoc(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
var data = JSON.parse(this.responseText);
document.getElementById("my_test").innerHTML = data.question;
// Send the answer to next URL
if(data.alternatives !== null){
createRadioElement(div,);
}
var answerJSON = JSON.stringify({"answer":"2"});
sendAnswer(data.nextURL, answerJSON)
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function sendAnswer(url, data) {
xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(this.responseText);
console.log(this.responseText);
loadDoc(data.nextURL);
}
}
// var data = JSON.stringify({"email":"hey#mail.com","password":"101010"});
xhr.send(data);
}
function createRadioElement(name, checked) {
var radioHtml = '<input type = "radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
}
I'm only guessing since you have some things in your posted code that won't even run, but createRadioElement returns a detached node which you never actually inject into your document.
E.g.,
document.body.appendChild(createRadioElement());

Categories

Resources