Fetched data from database with php and ajax, Everything is ok except note variable is empty.Can somebody find out the issue why note value is not going to display. How can i fix it.
success: function(response) {
var cats = {};
response.results.forEach(function(element) {
cats[element.team] = cats[element.team] || [];
cats[element.team].push(element);
});
var i = 0;
Object.keys(cats).forEach(function(team) {
let html = '';
// Append the category header
html = '<tr>';
html += '<td>' + team + '</td>';
html += '</tr>';
$('table').append(html);
// Loop through the results for this category
cats[team].forEach(function(element) {
var id = element.id;
var teamId = element.team_id;
var names = element.player;
var result = element.result;
var note = element.note;
html = '<tr>';
html += '<input type="hidden" name="Id[]" value="' + id + '"/>';
html += '<input type="hidden" name="data[' + i + '][team_id]" value="' + teamId + '"/>';
html += '<td>' + names + '</td>';
html += '<td><input type="text" name="result[]" value="' + result + '"></td>';
html += '</tr>';
$('table').append(html);
});
// Append the textarea at the end of the results
html = '<tr>';
html += '<td><textarea placeholder="note..." name="data[' + i + '][Note]">' + note + '</textarea></td>';
html += '</tr>';
$('table').append(html);
i++;
});
}
This is the output
database table
JSON output
{"groupData":{"id":"23","group_name":"Group B"},"results":
[{"id":"2","team_id":"4","team":"Team
B","player":"Deno","result":"14","note":"Lost"},
{"id":"3","team_id":"4","team":"Team
B","player":"Niob","result":"26","note":"Lost"},
{"id":"4","team_id":"4","team":"Team
B","player":"Skion","result":"76","note":"lost"},
{"id":"5","team_id":"5","team":"Team
C","player":"Bela","result":"47","note":"won"},
{"id":"6","team_id":"5","team":"Team
C","player":"yomi","result":"57","note":"won"}]}
You should set note value infront of cats[team].forEach(function(element) {}). Hope to help, my friend :))
success: function(response) {
var cats = {};
response.results.forEach(function(element) {
cats[element.team] = cats[element.team] || [];
cats[element.team].push(element);
});
var i = 0;
Object.keys(cats).forEach(function(team) {
let html = '';
// Append the category header
html = '<tr>';
html += '<td>' + team + '</td>';
html += '</tr>';
$('table').append(html);
var note;
// Loop through the results for this category
cats[team].forEach(function(element) {
var id = element.id;
var teamId = element.team_id;
var names = element.player;
var result = element.result;
note = element.note;
html = '<tr>';
html += '<input type="hidden" name="Id[]" value="' + id + '"/>';
html += '<input type="hidden" name="data[' + i + '][team_id]" value="' + teamId + '"/>';
html += '<td>' + names + '</td>';
html += '<td><input type="text" name="result[]" value="' + result + '"></td>';
html += '</tr>';
$('table').append(html);
});
// Append the textarea at the end of the results
html = '<tr>';
html += '<td><textarea placeholder="note..." name="data[' + i + '][Note]">' + note + '</textarea></td>';
html += '</tr>';
$('table').append(html);
i++;
});
}
Related
when i display the table my web app display undefined can someone help me please [realtime database
var database = firebase.database().ref().child('contact-#bluejetengineering/blue_jet/DB object Sensor');
database.once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var Sensor_1 = data.val().Sensor_1;
var Sensor_2 = data.val().Sensor_2;
var Sensor_3 = data.val().Sensor_3;
var Sensor_4 = data.val().Sensor_4
//content += '<tr>';
content += '<td>' + Sensor_1 + '</td>'; //column1
content += '<td>' + Sensor_2 + '</td>';//column2
content += '<td>' + Sensor_3 + '</td>';//column3
content += '<td>' + Sensor_4 + '</td>';//column4
content += '</tr>';
});
$('#ex-table').append(content);
}
});
</script>
I have a firebase database set up that I need to create an HTML table with that necessary info. Below is how I have set up my firebase data.
{
"Markets" : {
"Athens" : {
"Item" : {
"name" : "Beef",
"price" : 10,
"salePrice" : 3
}
}
}
}
This is how I have my HTML table set up and my code to attempt to retrieve the data. The table is appropriately being created but I am not seeing any data. Any help would be greatly appreciated.
<table style="width:100%" id="ex-table">
<tr id="tr">
<th>Name:</th>
<th>Price:</th>
<th>Sale Price:</th>
</table>
<script>
var database = firebase.database();
database.ref().once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var val = data.val();
content +='<tr>';
content += '<td>' + val.name + '</td>';
content += '<td>' + val.price + '</td>';
content += '<td>' + val.salePrice + '</td>';
content += '</tr>';
});
$('#ex-table').append(content);
}
});
</script>
Right now you're reading the root node. There are a few more levels of data in your JSON before you get to the name, price and salesPrice properties. You'll either need to navigate those levels in your callback, or in your query. An example of the latter:
var database = firebase.database();
database.ref('Markets/Athens').once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var val = data.val();
content +='<tr>';
content += '<td>' + val.name + '</td>';
content += '<td>' + val.price + '</td>';
content += '<td>' + val.salePrice + '</td>';
content += '</tr>';
});
$('#ex-table').append(content);
}
});
I have problem binding data in dropdown for adding data in grid. I want to pass airline name in the agent column. The dropdown value can't be changed How do I change the value of dropdown. Only the first index airline is shown in the dropdown.
Controller:
public ActionResult Create()
{
ViewBag.AID = db.Airlines.ToList();
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(FormCollection frmcoll, ICollection<string> hddrowpindex)
{
foreach (var row in hddrowpindex)
{
InternationalArrival stock = new InternationalArrival();
stock.AgentName = How to take selected textvalue Name from dropdown???;
stock.AgentCode = (frmcoll["AgentCode-" + row]).ToString();
stock.ArrivalDate = DateTime.ParseExact(frmcoll["ArrivalDate-" + row], "yyyy-MM-dd", null);
stock.ForPAX = Convert.ToInt32(frmcoll["ForPAX-" + row]);
stock.IndPAX = Convert.ToInt32(frmcoll["IndPAX-" + row]);
db.InternationalArrivals.Add(stock);
db.SaveChanges();
}
return RedirectToAction("Index");
}
View:
var sectorlist=(List<CompetitorAnalysis.Models.Airline>) ViewBag.AID;
string sectorddl= "";
foreach(var sector in sectorlist)
{
sectorddl = "<option value='"+sector.Name+"'>"+sector.Name+"</option>";
<input type="hidden" id="hddsector" value="#sectorddl" />
}
<script>
var d = new Date();
var rowindex = 1;
function addItem() {
msg = '<tr><input type="hidden" name="hddrowpindex" value="' + rowindex + '" class="rowcount"/>';
//added for bringing dropdown
msg += '<td class="center-fix" >';
msg += '<select>';
msg += document.getElementById("hddsector").value;
msg += '</select>'
msg += '</td>';
msg += '<td class="nocap-col-sm-2">';
msg += '<input type="text" class="form-control" style="text-transform:uppercase" name="AgentCode-' + rowindex + '" id="AgentCode-' + rowindex + '" placeholder="Code"/>';
msg += '</td>';
msg += '<td class="nocap-col-sm-2">';
msg += '<input type="text" class="form-control datepicker" name="ArrivalDate-' + rowindex + '" id="ArrivalDate-' + rowindex + '" placeholder="YYYY/MM/DD"/>';
msg += '</td>';
msg += '<td class="nocap-col-sm-2">';
msg += '<input type="text" class="form-control" name="ForPAX-' + rowindex + '" id="ForPAX-' + rowindex + '" placeholder="ForPAX" value="0" />';
msg += '</td>';
msg += '<td class="nocap-col-sm-2 center-fix">';
msg += '<input type="text" class="form-control" name="IndPAX-' + rowindex + '" id="IndPAX-' + rowindex + '" placeholder="IndPAX" value="0" />';
msg += '</td>';
msg += '<td class="nocap-col-sm-2 center-fix" style="text-align:center;"><i class="fa fa-trash"></i>Remove</span>';
msg += ' <span id="perror-' + rowindex + '" style="display:none"><i class="fa fa-exclamation-triangle faa-exclamation-triangle animated"></i></span></td>';
msg += '</tr>';
$('table#portfolio tbody').append(msg);
rowindex++;
}
</script>
How do I make the dropdown populated. In this case the first data of Airline table is shown in the dropdown. And how do i get the selected value in the Post method of controller.
Your immediate problem is inside of your loop:
var sectorlist=(List<CompetitorAnalysis.Models.Airline>) ViewBag.AID;
string sectorddl= "";
foreach(var sector in sectorlist)
{
sectorddl = "<option value='"+sector.Name+"'>"+sector.Name+"</option>";
<input type="hidden" id="hddsector" value="#sectorddl" />
}
It appears to me that you are attempting to build an html string for a select list dropdown. However, on each pass of the loop, you are overwriting the value in sectorddl by using sectorddl = "some value" Perhaps you mean sectorddl += "some value"?
As an aside, this really isn't a good way to build a dropdown in ASP.NET MVC.
You can simplify your code by doing something like this:
Controller
var items = from aid in db.Airlines
select new SelectListItem
{
Text = aid.Name, //or whatever the field names are
Value = aid.Id
};
ViewBag.AID = items.ToList();
View
#Html.DropDownList(model => model.SelectedAirlineId,
new SelectList(ViewBag.AID, "Value", "Text"))
I have a php scripts which shows data from worldoftanks api server. I show this data in table so I would like to add image near every user whos rank is "Recruit".
This is my javascript for table:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "clan_info.php",
success: function(data){
var htmlString = '<table cellpadding="0px" class="menu1"><tr><th>Username</th><th>Rank</th><th>PR</th><th>BTL</th><th>W/B</th><th>E/B</th><th>Days</th></tr>';
var clanData = JSON.parse(data);
i = 0;
for(userID in clanData){
userData = clanData[userID];
var extraClass = '';
if(i < 3) {
extraClass = 'class="rank' + (i+1) + '"';
}
htmlString += '<tr>';
htmlString += '<td '+extraClass+'>' + userData['name'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['role'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['rating'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['battles'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['w_p_b'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['xp_p_b'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['days'] + '</td>';
htmlString += '</tr>';
i++;
}
htmlString += '</table>';
console.log(htmlString);
$("#wot").html(htmlString);
}
});
});
</script>
AND MY PHP SCRIPT:
<?php
$clanID = "500006494";
$clanApiPage = "https://api.worldoftanks.eu/wgn/clans/info/?application_id=demo&clan_id=$clanID";
$userApiPage = "https://api.worldoftanks.eu/wot/account/info/?application_id=demo&account_id=";
$clanStrongHoldPage = "https://developers.wargaming.net/reference/all/wot/stronghold/info?application_id=demo&clan_id=$clanID";
$getAndDecode = function($url) {
$jsonData = file_get_contents($url);
$dataArray = json_decode($jsonData, true);
return $dataArray;
};
$determineDays = function($date) {
$datediff = time() - $date;
return floor($datediff/(60*60*24));
};
$jsonData = $getAndDecode($clanApiPage) , ($clanStrongHoldPage);
$clanAccounts = array();
foreach($jsonData["data"][$clanID]["members"] as $memberArray) {
$accountID = $memberArray["account_id"];
$clanAccounts[$accountID]['id'] = $memberArray["account_id"];
$clanAccounts[$accountID]['role'] = $memberArray["role_i18n"];
$clanAccounts[$accountID]['name'] = $memberArray["account_name"];
$clanAccounts[$accountID]['days'] = $determineDays($memberArray["joined_at"]);
}
$accountIDs = implode(",", array_keys($clanAccounts));
$apiPage = $userApiPage . $accountIDs;
$userJsonData = $getAndDecode($apiPage);
foreach($userJsonData["data"] as $userID => $dataArray) {
$playerStatistic = $dataArray["statistics"]["all"];
$clanAccounts[$userID]['rating'] = $dataArray["global_rating"];
$clanAccounts[$userID]['battles'] = $playerStatistic["battles"];
$clanAccounts[$userID]['w_p_b'] = $playerStatistic["wins"]/$playerStatistic["battles"] * 100;//wins per battle
$clanAccounts[$userID]['xp_p_b'] = $playerStatistic["battle_avg_xp"]; //experience per battle
}
$w_p_b = array();
foreach ($clanAccounts as $userID => $row) {
$w_p_b[$userID] = $row['w_p_b'];
}
array_multisort($w_p_b, SORT_DESC, $clanAccounts);
die(json_encode($clanAccounts));
?>
my table sample here: http://www.slovenian-army.tk/members.html
I would like to put image near every user like this:
sloa_clan
Depends on what rank is user. If user is Comander he gets comanders icon
If user is Recruit he gets Recruit icon.
Thank you!
I find out how to do this.
by adding this var:
var username = '<img src="images/' + userData['role'] + '.png" height="25" width="25" />' + userData['name'];
and code now looks like:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "clan_info.php",
success: function(data){
var htmlString = '<table cellpadding="0px" class="menu1"><tr><th>Username</th><th>Rank</th><th>PR</th><th>BTL</th><th>W/B</th><th>E/B</th><th>Days</th></tr>';
var clanData = JSON.parse(data);
i = 0;
for(userID in clanData){
userData = clanData[userID];
var extraClass = '';
if(i < 3) {
extraClass = 'class="rank' + (i+1) + '"';
}
var username = '<img src="images/' + userData['role'] + '.png" height="25" width="25" />' + userData['name'];
htmlString += '<tr>';
htmlString += '<td '+extraClass+'>' + username + '</td>';
htmlString += '<td '+extraClass+'>' + userData['role'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['rating'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['battles'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['w_p_b'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['xp_p_b'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['days'] + '</td>';
htmlString += '</tr>';
i++;
}
htmlString += '</table>';
console.log(htmlString);
$("#wot").html(htmlString);
}
});
});
</script>
In the below i have a a div with employee names and ahave to assign a grade for them,my question is that i have get the empid for all the selected values in getgrade_values function.Using jquery how to get the ids of the drop down box with its value where the values are selected when on click of evaluate function
function getgrade_values(empid)
{
var ele='<select id="'+ empid +'" name="emp" style="width:40px;margin:0px 0pt;" >';
ele += '<option value=""></option>';
ele += '<option value="A">A</option>';
ele += '<option value="B">B</option>';
ele += '<option value="C">C</option>';
ele += '<option value="D">D</option>';
ele += '<option value="E">E</option>';
ele += '<option value="F">F</option>';
ele += '</select>';
return ele;
}
function sendparams(data)
{
if(data.status == 1)
{
var ele='<tr id="std"><td><b>Evaluate:</b></label> </td></tr>';
for(var l=0;l<data.emparr.length;l++)
{
ele += '<tr><td><div id="'+ data.emparr[l].id +'">' + data.emparr[l].name + "</td><td>" + getgrade_values(data.emparr[l].id) + '</div></td></tr>';
ele+= '<input type="button" value="Evaluate" onclick="evaluate();"';
}
}
var select = $('select[name="emp"]')
var empId = select.attr('id')
alert('empId = '+empId)
select.children('option:selected').each(function() {
alert('grade selected = ' + $(this).val())
})
DEMO : http://jsfiddle.net/hdTEP/
Currently, you will have 2 elements with id="<employeeId>". As ids should be unique across an entire page, you should consider appending the type of element you are representing, for example id="<employeeId>_gradeInput" for your grade dropdown. Next, for each user it seems like you have a button to submit a grade. I would call evaluate with the employee id associated with that button.
function getgrade_values(empid){
var ele='<select id="'+ empid +'_gradeInput" name="emp" style="width:40px;margin:0px 0pt;" >';
..//Remaining code
}
function sendparams(data) {
if (data.status == 1) {
var ele =
'<tr id="std">' +
'<td>' +
'<b>Evaluate:</b>' +
'</td>' +
'</tr>';
for (var l = 0; l < data.emparr.length; l++) {
var employeeId = data.emparr[l].id;
ele +=
'<tr>' +
'<td>' +
'<div id="' + employeeId + '_divContainer">' +
data.emparr[l].name +
'</div>'
'</td>' +
'<td>' +
getgrade_values(employeeId)
'</td>' +
'</tr>';
ele += '<input type="button" value="Evaluate"
onclick="evaluate(' + employeeId + ');"';
}
}
function evaluate(employeeId){
var gradeValue = $('#' + employeeId + '_gradeInput').val();
..//Your other evaluate code here
}