Appending DB records into Buttons - javascript

I am attempting to append DB records retrieved into buttons which I can click on to go to the next page.
function mywall(){
$("#wallcontentset").empty();
var xmlhttp = new XMLHttpRequest();
var url = serverURL() + "/category.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
mywallresult(xmlhttp.responseText);
};
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function mywallresult(response) {
var arr = JSON.parse(response);
var i;
$("#wallcontentset").empty();
for(i = 0; i < arr.length; i++) {
var a = document.createElement("a");
a.setAttribute("href", "#");
a.setAttribute("onclick","listitembycategory.html?categoryid=" + arr[i].categoryid);
a.setAttribute("class","ui-btn");
a.innerHTML = arr[i].categoryname.toString();
$("#wallcontentset").append(a);
}
}
The above are the set of functions that I had coded and placed in the script. The function mywall() is working fine, it retrieves every record in my database.
However I had some issues with the function mywallresult().
It creates a button for every record retrieved, however the button does not link to the next page when clicked. I couldn't identify what's wrong with my a.setAttribute.
Anyone could help me out please?

You have to merely replace this:
a.setAttribute("href", "#");
a.setAttribute("onclick","listitembycategory.html?categoryid=" + arr[i].categoryid);
by this:
a.setAttribute("href", "listitembycategory.html?categoryid=" + arr[i].categoryid);

Related

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);
}

Dynamically Populating Dropdown from xhttp.open("Get"); response

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 = "";

Calling different JSON files using AJAX via several buttons

I am working on a small project for University using JavaScript, JSON and AJAX to pull information from 3 seperate restaurant menus (stored in JSON files) and displaying them in a list once the relevant button has been clicked.
This worked using one menu, having a button with an event listener that ran the loadAjax function and displayed the relevant menu information.
I've tried to expand this using 3 buttons, with an event listener on each that passes the name of the JSON file through the function parameter. This no longer works, and only the last JSON file is displayed, on window load, without clicking a button.
I'm pretty stuck at this stage and want to avoid having three separate functions (for obvious reasons). The code is below, any help would be much appreciated! I may have made a minor error so apologies if this is a silly question.
var weekdayBtn = document.getElementById("weekdayBtn"),
saturdayBtn = document.getElementById("saturdayBtn"),
sundayBtn = document.getElementById("sundayBtn");
weekdayBtn.addEventListener("click", loadAjax("weekday.json"), false);
saturdayBtn.addEventListener("click", loadAjax("saturday.json"), false);
sundayBtn.addEventListener("click", loadAjax("sunday.json"), false);
function loadAjax(menuData) {
var request = new XMLHttpRequest();
request.open('GET', menuData);
request.onreadystatechange = function() {
if ((request.readyState === 4) && (request.status === 200)) {
var menu = JSON.parse(request.responseText);
var output = "";
for (var key in menu) {
output += "<li>" + menu[key]["Title"] + ", " + menu[key]["Description"] + ". " + menu[key]["Price"] + " </li>";
}
var menu = document.getElementById('menu');
menu.innerHTML = output;
}
}
request.send();
}
The addEventListener methods requires a function as second argument so your loadAjax method must return a function:
function loadAjax(menuData) {
return function () {
var request = new XMLHttpRequest();
request.open('GET', menuData);
request.onreadystatechange = function() {
if ((request.readyState === 4) && (request.status === 200)) {
var menu = JSON.parse(request.responseText);
var output = "";
for (var key in menu) {
output += "<li>" + menu[key]["Title"] + ", " + menu[key]["Description"] + ". " + menu[key]["Price"] + " </li>";
}
var menu = document.getElementById('menu');
menu.innerHTML = output;
}
}
request.send();
}
}
in this way the inner function will be used as event listener with the menuData variable in its scope.

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());

Concurrent AJAX requests not working. Newest request overwrites previous request

My webpage features a table where each row has a "+" button so that a mini table appears. The mini table houses data from a super slow database so I am having the data come in through ajax requests. My problem is rooted in a certain situation. Suppose you pressed a plus button causing an AJAX request and while waiting you press another plus button. The second ajax request causes the first request to never come back. In other words the newest request overwrites all previous pending requests. Any idea why this might be happening? I feel like this might just be what happens when you don't use jQuery to handle AJAX but I am not sure and I couldn't find anything that said that was the case. I am appending my code below. Any help is appreciated!
function fetchSINamesForVariantAJAX(latestBuild, variantToExpand){
if (latestBuild == "") {
//document.getElementById(subTableId).innerHTML = "";
return;
}
else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
spinner.stop();
var variantRow = variantToExpand + "Row";
if (document.getElementById(variantRow).rows.length == 1){
var json = JSON.parse(xmlhttp.responseText);
var SINames = json['SIs'];
var locations = json['locations'];
var SIBuilds = json['SIBuilds'];
for (var i = 0; i < SINames.length ; i++){
var row = document.getElementById(variantRow).insertRow(-1);
var cell = row.insertCell(-1);
var SILinkURL = "exampleWebsite.com/name.php?names=" + SINames[i];
cell.innerHTML = "" + SINames[i] + "";
cell = row.insertCell(-1);
var fullLocation = locations[i] + "\\" + SIBuilds[i];
cell.innerHTML = "" + fullLocation + "";
cell = row.insertCell(-1);
cell.innerHTML = "";
}
}
}
}
//create the GET message to be sent using AJAX window
var stateToSend = "SITableGeneratorFromVariant.php?";
stateToSend += "latestBuild=" + latestBuild;
xmlhttp.open("GET", stateToSend, true);
xmlhttp.send();
}
}
I think the reason is that you overwrite your xmlhttp variable with a new one each time a new AJAX call gets done try declaring it inside the function:
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

Categories

Resources