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);
}
Related
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
});
});
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.
I have a local text file that I am trying to populate a select dropdown with that data. I have installed IIS to get past the local restrictions and have gotten past CORS. I have used the xhttp method to retrieve the text file data from the file located on the IIS server. I am able to display it in a div as you can see from the below code. I am trying to get this data into a dropdown that I can easily get a value from. For example, if the user selects "Part1" I get an integer value from like 1 as I would from any other dropdown that I specifically declared. I would prefer a javascript solution if possible as that is what the code I have been using for the most part.
I have looked at Google for solutions with nothing really matching.
<body onload="pList();">
<div id="PartList"></div>
<script>
function pList() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("PartList").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "http://127.0.0.1:8080/PartList.txt", true);
xhttp.send();
}
</script>
You have to split your data into an array and then add to the select this way:
<script>
function pList() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var options = this.responseText.split(delimiter);
var select = document.getElementById("PartList");
for (var i = 0; i < options.length; i++) {
var option = document.createElement("option");
option.text = options[i];
option.value = i;
select.add(option);
}
}
};
xhttp.open("GET", "http://127.0.0.1:8080/PartList.txt", true);
xhttp.send();
}
</script>
If you want to clear the select before load use this:
document.getElementById("PartList").innerHTML = "";
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;
}
});
});
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());