How to retrieve only one row with getJSON - javascript

I'm pretty new to web dev and I have a hard time here to retrieve some info from the database... I'm doing this:
function readLine(i) {
$.getJSON('../php/database.php', function(data) {
$.each(data, function (key, value) {
var output = "";
var borderBegin = "<td style='border-left: 1px solid black;border-right:1px solid black;'> ";
var borderEnd = " </td>";
key = i;
output = "<tr>" + borderBegin + key + borderEnd + borderBegin + value.name + borderEnd + borderBegin + value.firstname + borderEnd + borderBegin + value.tel + borderEnd + "</tr>";
$("#resultsAdm").append(output);
});
});
}
I try to display only the row with the i index passed in argument to the function. I know the $.each(..) retrieves rows one by one (but displays all). I cannot figure how to do it with only one row... Thanks for the help!

I try to display only the row with the i index passed in argument to
the function
If you only want to render the line from the index equal to i don't append unless you have a match.
At the start of each iteration, check if the key matches i and if not skip to the next item.
if(key != i){return true;}
Ones key matches i, process the lines, append it and then break out of the .each loop using return false.
I also commented out key = i as that doesn't seem right.
function readLine(i) {
$.getJSON('../php/database.php', function(data) {
$.each(data, function (key, value) {
if(key != i){return true;}
var output = "";
var borderBegin = "<td style='border-left: 1px solid black;border-right:1px solid black;'> ";
var borderEnd = " </td>";
//key = i; Not sure what this is for?
output = "<tr>" + borderBegin + key + borderEnd + borderBegin + value.name + borderEnd + borderBegin + value.firstname + borderEnd + borderBegin + value.tel + borderEnd + "</tr>";
$("#resultsAdm").append(output);
return false;
});
});
}

So your data contains multiple rows but you only want the first? Then $.first() should work.

Related

How to loop through and print out correctly

I Know why I'm getting undefined but i have no idea how to solve.
Tried to put null, but it is taking in as a text
var text ='{"employees":[' +
'{"name":"Tony","mobile":"99221111","email":"tony#json.com"},' +
'{"name":"Linda","mobile":"98981111","email":"linda#json.com"},' +
'{"name":"Patrick","mobile":"90902222","email":"patrick#json.com"},' +
'{"name":"Isabella","mobile":"99552222"}]}';
obj = JSON.parse(text);
for(var i in obj.employees)
{
document.getElementById("table").innerHTML += "<tr><td>" + obj.employees[i].name + "</td>" + "<td>" + obj.employees[i].mobile + "</td>"
+ "<td>" + obj.employees[i].email + "</td></tr>";
}
Hi, for Isabella there is no email, hence I'm getting undefined when I loop through to print out their details on html, however what I'm expecting is for the email portion to be empty in the table for Isabella. Is there a way to solve it?
You can use logical OR (|| in JavaScript), which will use the second value (empty string in this case) if the first value (email) is undefined:
var text = '{"employees":[' +
'{"name":"Tony","mobile":"99221111","email":"tony#json.com"},' +
'{"name":"Linda","mobile":"98981111","email":"linda#json.com"},' +
'{"name":"Patrick","mobile":"90902222","email":"patrick#json.com"},' +
'{"name":"Isabella","mobile":"99552222"}]}';
obj = JSON.parse(text);
for (var i in obj.employees) {
document.getElementById("table").innerHTML += "<tr><td>" + obj.employees[i].name + "</td>" + "<td>" + obj.employees[i].mobile + "</td>" +
"<td>" + (obj.employees[i].email || '') + "</td></tr>";
}
<table id="table"></table>

How can I use each loop variable (item) outside of loop

I want to make a switch for declaring variables inside each loop, like this
switch (label) {
case "Users":
content = item.username+ ' ' + item.firstname + ' '
+ item.lastname + '('+ item.organization + ')';
break;
default:
}
$.each(result, function (i, item) {
html += "<option value ='" + item.id + "'>" + content + "</option>";
});
But since item variable hasn't defined yet I will get an ReferenceError.
Moving switch inside loop will make It really slow.
Is this even possible to declare loop variables outside of scope?
function selectorAddEdit(label, tag, result, labelconf) {
var idtag = tag+"s";
var none = "<option value='None'>None</option>";
var labelHead = (labelconf=="head") ? "<div class='selectTitles'><label>"+label+"</label></div>" : "";
switch (label) {
case "Users":
var content = item.username + ' ' + item.firstname + ' ' + item.lastname + '('+ item.organization + ')';
break;
default:
}
var html = labelHead + "<select name='" + tag + "' class='" + tag + "'>";
$.each(result, function (i, item) {
html += "<option value ='" + item.id + "'>" + content + "</option>";
});
html += "</select></div>";
$("." + idtag).html(html);
}
Declare the content as a global variable
var content="";
switch (label) {
case "Users":
content = item.username+ ' ' + item.firstname + ' ' + item.lastname + '('+ item.organization + ')';
break;
default:
}
$.each(result, function (i, item) {
html += "<option value ='"+item.id+"'>"+content+"</option>";
});
This is assuming that item is distinct/unique and therefore you want the switch statement to be re-evaluated at each iteration of loop. What you can do is to use a method/function that returns the value, after evaluating a given condition:
var getOptionContent = function(item) {
switch (label) {
case "Users":
return item.username + ' ' + item.firstname + ' ' + item.lastname + '(' + item.organization + ')';
default:
return '';
}
}
var html = labelHead + "<select name='" + tag + "' class='" + tag + "'>";
$.each(result, function(i, item) {
html += "<option value ='" + item.id + "'>" + getOptionContent(item) + "</option>";
});

jquery $.each not giving all the information in the table

Fiddle
I want to put the names of all record in my array into a table my array isn't index correctly so i used $.each instead of iterating over the using for loop. My problem is I only get to show the last element but if i try to show a value that is existing to both the array it is showing correctly.
What am i missing in this code.
Any idea is appreciated
This is my javascript
for (var i = 0; i < name.length; i++) {
var names = name[i].Names;
$.each(names, function (item, names) {
tr = $('<tr class=""/>');
//console.log(complainant[obj]);
//var names = complainant[obj];
//if(names.hasOwnProperty('fname')){
console.log(names.suffix);
var acronymc;
var upper = names.mname.toUpperCase();
if (upper) {
var matches = upper.match(/\b(\w)/g);
//var matches = upper.replace(/^(\S+)\s+(\S).*/, '$1 $2.');
//acronym = upper.slice(0,1);
var acronym1 = matches.join('');
acronymc = acronym1.slice(-1);
} else {
acronymc = '';
}
tr.append("<td id=''>" + "<span id='fname'>" + names.fname + "</span>" + " " + "<span id='mname'>" + acronymc + "</span>" + " " + "<span id='lname'>" + names.lname + "</span>" + " " + "<span id='suffix'>" + names.suffix + "</span>" + "</td>");
tr.append("<td id=''>" + '<span id="street">' + names.street + '</span>' + " " + '<span id="brgy">' + names.brgy + '</span>' + " " + '<span id="town">' + names.town + '</span>' + " " + '<span id="city">' + names.city + '</span>' + "</td>");
tr.append("<td id=''>" + names.contactnum + "</td>");
tr.append("<td id=''>" + "<a href='#' class='editcomplainant'>Edit</a>" + "/" + "<a href='#' class='delete'>Delete</a>" + "</td>");
//}
});
$("#nameslist").append(tr);
}
Put the $('#nameslist').append(tr); call inside the $.each block.
Here is a way of improving the creation of tds:
var html =
"<td>" +
"<span id='fname'/> " +
"<span id='mname'/> " +
"<span id='lname'/> " +
"<span id='suffix'/>" +
"</td>";
var td = $(html);
td.find('#fname').text(names.fname);
td.find('#mname').text(acronymc);
td.find('#lname').text(names.lname);
td.find('#suffix').text(names.suffix);
tr.apppend(td);
Why is this better (imho)?
You will not create unintentional html tags by having < and > inside the variables.
Appropriate escaping (auml codes) will be automatically generated
It is easier to read

Passing JQuery Arrays to Nested Function

I'm having problems with dynamically adding a row to a table using data stored in two arrays (categories and treatments). The arrays are fine, I've determined that.
When passing just the categories array the new row displays but the select box reads [object:object], it's clearly blank.
When I pass a second array with it, as shown below, the console reads 'undefined is not a function'.
Any help would be hugely appreciated!
// Add an extra row when button is clicked
var counter = 1;
$('input.add').click(categories, treatments, function(){
counter++;
var newRow = '<tr><td><label for="category' + counter + '">Category</label></td><td><select id="category' + counter + '" name="category' + counter + '" required="required">';
$.each(categories, function(key, value) {
$('#category' + counter)
newRow += '<option value ="' + key + '">' + value + '</option>';
});
newRow += '</select></td><td><label for="treatment' + counter + '">Treatment</label></td><td><select id="treatment' + counter + '" name="treatment' + counter + '">';
$.each(treatments, function(key, value) {
$('#treatment' + counter)
newRow += '<option value ="' + key + '">' + value + '</option>';
});
newRow += '</select></td></tr>';
$('table.treatments').append(newRow);
});
});
The first parameter for the jQuery .click() is an Object, and you're trying to pass two arrays.
This should work for you (remember to check for the missing semi-colons):
// Create an Object obj containing the two arrays.
$('input.add').click(obj = { categories: categories, treatments: treatments }, function () {
counter++;
var newRow = '<tr><td><label for="category' + counter + '">Category</label></td><td><select id="category' + counter + '" name="category' + counter + '" required="required">';
// Use the obj.
$.each(obj.categories, function (key, value) {
$('#category' + counter);
newRow += '<option value ="' + key + '">' + value + '</option>';
});
newRow += '</select></td><td><label for="treatment' + counter + '">Treatment</label></td><td><select id="treatment' + counter + '" name="treatment' + counter + '">';
// Use the obj.
$.each(obj.treatments, function (key, value) {
$('#treatment' + counter);
newRow += '<option value ="' + key + '">' + value + '</option>';
});
newRow += '</select></td></tr>';
$('table.treatments').append(newRow);
});
Demo
jQuery .click()

Passing a hidden field to a javascript function

I need to pass in the selector a hidden field to a javascript function.
This is my function
function deleteAttachments(id,selector){
$('#proof' + id).remove();
//show warning about save
var tmp = selector.val();
var sep = "";
if (tmp != "")
sep = ",";
selector.val(tmp + sep + id);
}
The above function call is inside the following method,
function listAttachments(proofs,selector,hiddenField,after){
//alert(hiddenField.id);
var rows = "<table width=\"70%\">";
for(var i=0; i<proofs.length; i++) {
var proof = proofs[i];
rows += "<tr id=\"proof" + proof["ID"] + "\" width=\"40%\">"
rows += "<td><input type=\"hidden\" value=\"" + proof["filename"] + "\" id=\"Proof" + i + "\" />Uploaded: " + proof["uploaded"] + "</td>"
rows += "<td width=\"90px\"><input type=\"button\" value=\"View...\" onclick=\"viewProof('" + proof["URL"] + "'); \" id=\"btnProof" + i + "\" class=\"btn\"></td>"
rows += "<td width=\"90px\"><input type=\"button\" value=\"Delete\" id=\"btnDelete" + i + "\" onclick=\"deleteAttachments(" + proof["ID"] + "," + hiddenField + ");\" class=\"btn\"/></td></tr>";
}
rows += "</table>";
if(after){
selector.after(rows);
}else{
selector.html(rows);
}
}
Please find the listAttachments function calls (I am using asp.net and tried different ways) below,
listAttachments(visualIds,$('#tblProofs'),$('#hidDeletedAttachments'),true)
or
listAttachments(visualIds,$('#tblProofs'),$('#' + <%= hidDeletedAttachments.ID%>'),true)
When this is rendered the deleteAttachments function accepts the argument as an object (as displayed in the image below).
My question is how I can pass the selector to the function and use it with in the calling function.
You are not passing the selector, you are passing a collection of elements that match the selector.
Instead of passing the hiddenField to listAttachments, pass the hiddenField id.
listAttachments(visualIds,$('#tblProofs'), 'hidDeletedAttachments'),true)
Then create the object in the deleteAttachment function
function deleteAttachments(id,hiddenFieldId){
var selector = $('#' + hiddenFieldId);
$('#proof' + id).remove();
//show warning about save
var tmp = selector.val();
var sep = "";
if (tmp != "")
sep = ",";
selector.val(tmp + sep + id);
}

Categories

Resources