I am developing a mobile app using Phonegap and jQuery Mobile. Basically for the first time when the app loads the data which gets populated using AJAX comes fine but It doesn't update.
Example: If there are 5 rows of data coming from the database and with some users action 1 more row has been added in the database but it still displays 5 rows. Currently it updates only if I exit app fully.
Also to solve this problem I have tried the following:
tbody.append(tableCells).load();
tbody.append(tableCells).trigger('create');
tbody.append(tableCells).trigger('refresh');
Any solution/idea how can I update it live or something without a user exits the app completely? Please see the below code.
Code:
HTML:
<table id="myPendingChallenges-table" width="100%">
<thead>
<tr>
<th>Game Type</th>
<th>Team Name</th>
<th>Initiator Name</th>
</tr>
</thead>
<tbody></tbody>
</table>
to append rows inside the
JS: tbody.append(tableCells);
AJAX:
var currentUser = window.localStorage.getItem("currentUser");
user = JSON.parse(currentUser);
var username = user.username; //User name
//alert (username+', '+t_name+', '+formAction);
$.ajax({
type: 'POST',
url: 'http://www.example.com/webservice/index.php',
data: {username: username},
dataType : 'json',
success: function(data){
var json = JSON.stringify(data);
window.localStorage.setItem("teamChallenges", json);
challengePopulate();
},
error: function(){
alert('error!');
}
});
return false;
function challengePopulate()
{
var json = window.localStorage.getItem("teamChallenges");
var data = null;
if(!json)
data = JSON.stringify(window.teamChallenges);
var data = JSON.parse(json);
if(!data)
return;
var fields = ["game_type", "t_name", "ini_name"];
populatePCTable("#myPendingChallenges-table", fields, data);
}//end challengePopulate
function populatePCDTable(tableId, fields, data)
{
var tbody = $(tableId + " tbody");
var row = null;
for(var i in data) {
row = data[i];
if(!row)
continue;
var tableCells = "";
var fieldName = "";
for(var j in fields){
fieldName = fields[j];
teamName = row[fields[1]];
gameParam = row[fields[3]];
if(row[fieldName] == 'weighin'){
game_type = 'weighin';
row[fieldName] = '<img src="images/weightGame.png" width="100%" />';
}else if (row[fieldName] == 'activity'){
game_type = 'activity';
row[fieldName] = '<img src="images/activityGame.png" width="100%" />';
}
tableCells += "<td onClick=\"setPendingChallTitle('"+teamName+"');pendingchallengeDetails('"+teamName+"');\"><a href='#pendingChallengesDetailsPage'>"+row[fieldName]+"</a></td>";
}
tbody.append("<tr>" + tableCells + "<td onClick=\"ignorePendingChallenge(this,'"+teamName+"');\"><a href=''><img src='images/close_button.png' title='Ignore Challenge' /></a></td></tr>");
}
}//end function populatePCDTable
Related
I'm trying to use an editable bootstrap table where in data can be inserted on the database. However, I find it difficult since I'm only new with this field. I can load the data from the database and edit the table field but I don't know how can I insert it on the database.
Below is my code for the table. For the <tbody, I used javascript and ajax to load the data from the database. Note that, it only loads the CATEGORY ID and DESCRIPTION. The AMOUNT must be inserted by the user.
<div id="table" class="table-editable">
<table class="table table-sm table-striped table-hover" id="tbl-fees">
<thead>
<tr>
<th>CATEGORY</th>
<th style="display:none">CATEGORY ID</th>
<th scope="col">DESCRIPTION</th>
<th scope="col" class="text-right">AMOUNT</th>
</tr>
</thead>
<tbody id= "fees_table"></tbody>
</table>
</div>
As per the resources online, it says that I can use contenteditable="true" for me to have an editable table.
<script>
function load_fees_list()
{
var sy_id=2;
$.ajax({
method:"GET",
url: "<?php echo site_url(); ?>Get-FCP/"+sy_id,
success: function(response){
$.each(response.fcp_data, function(key, value){
$('#fees_table').append('<tr>\
<td style="display:none">'+value["fc_desc"]+'</td>\
<td id="fc_id">'+value["fc_id"]+'</td>\
<td id="fcp_description">'+value["fcp_description"]+'</td>\
<td id="fmf_amount" class="text-right" contenteditable="true">'+0+'</td>\
</tr>');
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
}
});
}
</script>
I found a script online where it shows the output of the live table when button is clicked.
var $TABLE = $('#table');
var $BTN = $('#export-btn');
var $EXPORT = $('#export');
// A few jQuery helpers for exporting only
jQuery.fn.pop = [].pop;
jQuery.fn.shift = [].shift;
$BTN.click(function () {
var $rows = $TABLE.find('tr:not(:hidden)');
var headers = [];
var data = [];
// Get the headers (add special header logic here)
$($rows.shift()).find('th:not(:empty)').each(function () {
headers.push($(this).text().toLowerCase());
});
// Turn all existing rows into a loopable array
$rows.each(function () {
var $td = $(this).find('td');
var h = {};
// Use the headers from earlier to name our hash keys
headers.forEach(function (header, i) {
h[header] = $td.eq(i).text();
});
data.push(h); //adds new items to the end of an array
});
// Output the result
$EXPORT.text(JSON.stringify(data));
});
However, I can't insert it on the database. I'm planning of inserting the data in a new MySQL table in which it stores the description and amount. Can someone help me on how can I insert it?
I want to display data in table on inserting data as well as when the page is loaded. Storing data successfully works with the code but the issue is;
When I use POST, the form data is completely visible in the URL.
How do i display all data passed in json format in html table.
HTML:
<table class="table table-striped table-bordered" id="myTable">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Match</th>
<th scope="col">Match Date</th>
<th scope="col">Winner</th>
<th scope="col">Loser</th>
<th scope="col">Man of the Match</th>
<th scope="col">Bowler of Match</th>
<th scope="col">Best Fielder</th>
</tr>
</thead>
</table>
JAVASCRIPT:
<script>
$(function() {
$("#submit").on("click", function(e) {
var team_one = $('#team_one').val();
var team_two = $('#team_two').val();
var match_summary = $('#match_summary').val();
var match_date = $('#match_date').val();
var winner = $('#winner').val();
var loser = $('#loser').val();
var man_of_the_match = $('#man_of_the_match').val();
var bowler_of_the_match = $('#bowler_of_the_match').val();
var best_fielder = $('#best_fielder').val();
$.ajax(
{
type: "POST", //HTTP POST Method
url: '<?php echo base_url(); ?>/MatchController/storeMatch',
data: { //Passing data
'team_one': team_one,
'team_two': team_two,
'match_summary' : match_summary,
'match_date' : match_date,
'winner' : winner,
'loser' : loser,
'man_of_the_match' : man_of_the_match,
'bowler_of_the_match' : bowler_of_the_match,
'best_fielder' : best_fielder
},
success: function (response) {
console.log("Response: " + response);
alert("Data stored successfully");
},
});
});
});
//FETCH ALL MATCH DATA USING PASSED API IN CONTROLLER
$(document).ready(function (){
getData();
function getData(){
$.ajax({
url : "<?php echo base_url(); ?>/MatchController/fetchMatchData",
method : 'get',
dataType: "json",
success: function(data){
}
});
}
});
CONTROLLER:
public function storeMatch()
{
$team_one = $_POST['team_one'];
$team_two = $_POST['team_two'];
$match_date = $_POST['match_date'];
$match_summary = $_POST['match_summary'];
$winner = $_POST['winner'];
$loser = $_POST['loser'];
$man_of_the_match = $_POST['man_of_the_match'];
$bowler_of_the_match = $_POST['bowler_of_the_match'];
$best_fielder = $_POST['best_fielder'];
$data = array(
'team_one' => $team_one,
'team_two' => $team_two,
'match_date' => $match_date,
'match_summary' => $match_summary,
'winner' => $winner,
'loser' => $loser,
'man_of_the_match' => $man_of_the_match,
'bowler_of_the_match' => $bowler_of_the_match,
'best_fielder' => $best_fielder
);
$this->MatchModel->saveMatchData($data);
}
public function fetchMatchData()
{
$match_data = $this->MatchModel->fetchMatchList();
return $match_data;
}
Try to pass the result to <tbody> use JQuery
success: function(data){
//delete old tbody block
$('#myTable tbody').remove()
//add tbody block
$('#myTable').append('<tbody><tr><td>'+data.someValue+'</td></tr></tbody>')
}
And when you want add new data just call your getData().
success: function (response) {
getData()
console.log("Response: " + response);
alert("Data stored successfully");
},
Also look at e.preventDefault for your ajax call. If you use ajax needlessly reload page
I loop through some data dynamically via Ajax and than display them in table. As you see I have multiple row or <tr> , HeaderLine and Customerinfo. which I'm interesting in is CustomerInfo and the thing I'm trying do is when button is clicked, check which input fields is Empty or has no value than give an alert and for finding input fields or elements I used jQuery find() and closest() Method, but for some reason it can't find any elements.
Can anyone please help me to solve the issue?
JavaScript for checking Empty input fields before sending to server:
<script>
function AnmodomRMA(e) {
var tr = $(e).closest("table").find(".CustomerInfo");
var email = tr.find('input.Email').val();
var telefon = tr.find('input.Telefonnummer').val();
if (email === "") {
alert("Input is Empty:" + email);
return false;
}
if (telefon === "") {
alert("Input is Empty:" + telefon);
return false;
}
var formdata = $("select, textarea,input").serializeArray();
$.ajax({
"url": '#Url.Action("AutoRMAAnmoding", "User")',
"method": "POST",
"data": formdata,
"dataType": "json",
success: function (data) {
console.log(data);
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
</script>
JavaScript for Load Data (dynamically into table):
<div class="card-body">
<table class="table">
<tbody id="ResultProduct"></tbody>
</table>
<div id="AppendBtnRMA">
</div>
</div>
<script>
$.ajax({
type: "GET",
url: "/User/serializeItemLineByID" + 1,
dataType: 'json',
success: function (result) {
$.each(result.findclosedorders, function (ii, e) {
var guid = uuidv4();
rows += '<tr class="HeaderLine">';
rows += '<td>some data</td>';
rows += '</tr>';
rows += '<tr class="CustomerInfo">'
rows += '<input type="hidden" name="model.InsertRMALists.Index" value="' + guid + '" />';
rows += '<td><label>Telefonnummer</label><input name="model.InsertRMALists[' + guid + '].Telefonnummer" id="Telefonnummer" type="tel"></td>';
rows += '<td><label>E-mail</label><input name="model.InsertRMALists[' + guid + '].Email" id="Email" type="text"></td>';
rows += '</tr>';
});
var btnAppend = "";
btnAppend += '<button onclick="AnmodomRMA(this);">Create RMA</button>';
$("#AppendBtnRMA").append(btnAppend);
$("#ResultProduct").append(rows);
},
})
</script>
Thanks for all help :)
Here is how did i solve the problems:
- Add a class to input fields.
- beacuse button it was out side the table, i have to select closest element around table and than find <tr> like:
var tr = $(e).closest(".card-body").find("tr.section");
and than loop through that element i want to check if it is Empty:
$(tr).each(function (i, el) {
var t = $(el).find('input.Telefonnummer').val();
if (t ==="") {
alert("empty");
}
});
In the function AnmodomRMA(e) e refers to the event itself and not the clicked button, try to use e.target:
var tr = $(e.target).closest("tr");
Controller: In my controller I am getting data from sap b1if service.
I want to get json data from controller to view.
[HttpGet]
[AllowAnonymous]
public ActionResult Index()
{
ServiceReference1.ipostep_vP001sap0003in_WCSX_comsapb1ivplatformruntime_INB_WS_CALL_SYNC_XPT_INB_WS_CALL_SYNC_XPTipo_procClient B1ifSerPro
= new ServiceReference1.ipostep_vP001sap0003in_WCSX_comsapb1ivplatformruntime_INB_WS_CALL_SYNC_XPT_INB_WS_CALL_SYNC_XPTipo_procClient();
ServiceReference1.SelectQueryType request = new ServiceReference1.SelectQueryType();
request.Query = "Select TOP 1000 r.U_JobNr as U_JobNr,r.Code as Code,r.U_HlSQty as U_HlSQty,r.U_JobTp as U_JobTp,r.U_RDate as U_RDate,r.U_RTime as U_RTime,r.U_ASDate as U_ASDate,r.U_ASTime as U_ASTime,r.U_AEDate as U_AEDate,r.U_Lorry as U_Lorry,r.U_Driver as U_Driver,e.U_ZpCd as U_ZpCd,e.U_City as U_City,e.U_Phone1 as U_Phone1,e.U_SiteTl as U_SiteTl,r.U_ConNum as U_ConNum,r.U_CstWgt as U_CstWgt,r.U_Price as U_Price,r.U_TCTotal as U_TCTotal,r.U_SLicCh as U_SLicCh,r.U_PayMeth as U_PayMeth,r.U_JCost as U_JCost,r.U_RTimeT as U_RTimeT,r.U_SLicNr as U_SLicNr,r.U_VehTyp as U_VehTyp,r.U_IDHRTCD as U_IDHRTCD,r.U_IDHSEQ as U_IDHSEQ,r.U_CustRef as U_CustRef,r.U_Rebate as U_Rebate,r.U_WROrd as U_WROrd,r.U_WRRow as U_WRRow,e.U_Status as U_Status,r.U_RowSta as U_RowSta,r.U_LnkPBI as U_LnkPBI,r.U_AddCost as U_AddCost,r.U_AddCharge as U_AddCharge,r.U_ValDed as U_ValDed,e.U_PCardCd as U_PCardCd,e.U_SCardCd as U_SCardCd,r.U_OrdTot as U_OrdTot,r.U_PCTotal as U_PCTotal FROM[#IDH_JOBSHD] r ,[OCRD] bp ,[#IDH_JOBENTR] e WHERE r.U_JobNr = e.Code AND (r.U_CustCd = bp.CardCode Or (r.U_CustCd = '' AND r.U_ProCd = bp.CardCode)) ";
ServiceReference1.SelectQueryResponseType Response = B1ifSerPro.ZSelectQuery(request);
Response.SelectQueryResult.ToList();
//ServiceReference1.SelectQueryResponseTypeRow row = (ServiceReference1.SelectQueryResponseTypeRow)Response.SelectQueryResult.GetValue(1);
return Json(Response.SelectQueryResult.ToList(), JsonRequestBehavior.AllowGet);
//return Json("",JsonRequestBehavior.AllowGet);
}
My view as is follow:
JS is not working in my case. I want to get data as json form Controller and render in HTML using Bootstrap or simple will work.
#Model IEnumerable<BusinessLayer.OSM>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var osmlist;
$.ajax({
url:'#Url.Action("Index", "OSM")' , // '/OSM/Index/',
type: 'Get',
Data:{},
cache: false,
async: false,
DataType: 'Json',
success: function (data) {
osmlist = data;
var row = '';
$.each(data, function (i, item) {
row += "<tr>"
row += "<td>" + item.Code + "<td>"
row += "<td>" + item.U_JobNr + "<td>"
row += "<tr>"
$("#listRows tbody").html(row);
})
},
error: function (error) {
alert("Error : " + error.responseText);
}
});
});
</script>
<h2>Get OSM Rows</h2>
<table id="listRows" style="background-color: lightcoral">
#*<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Category</th>
<th>Price</th>
</tr>
</thead>*#
<tbody></tbody>
</table>
<hr />
Is it the typo error while putting the question here or you have forgotten to correctly close the tr and td tags in the javascript.
I have a simple HTML table within a cshtml page. It is basically a single column, where I want to programmatically insert rows from the result of an ajax call.
<table class="table" id="notestedtable">
<tr>
<th>
Not Tested
</th>
</tr>
<tr>
<td>
Unit#1
</td>
</tr>
</table>
I use the document.onload = NotTested("Site 001", "17/06/2015"); to call the function which then executes the ajax.
function NotTested(SiteId,TestDate) {
$.ajax({
url: '/Home/NotTested',
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify({
siteid: SiteId, testdate: TestDate
}),
success: function (result) {
for (var i = 0; i < result.Tubs.length; i++) {
alert(result.Tubs);
}
}
})
}
The returned Tubs is a string[] where Tubs[0] = "Tub 1"; Tubs[1] = "Tub 2" ... and so on. I want each of the Tub[] to form a row in my table.
This is the C# in the controller:
[HttpPost] // can be HttpGet
public ActionResult NotTested(string siteid, string testdate)
{
int i = 0;
//this could be populated first by reading for this "site" how many tubs to be expected
string[] UnTested = new string[8];
SqlConnection conn = new SqlConnection(#"Server=****;Database=****;User Id=****;Password=****;");
SqlCommand cmd = new SqlCommand("select * from TubsNotTested(#siteid,#testdate)", conn);
cmd.Parameters.AddWithValue("#siteid",siteid);
cmd.Parameters.AddWithValue("#testdate", testdate);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
for(i=0; i<dt.Rows.Count; i++)
{
UnTested[i] = dt.Rows[i][0].ToString();
}
return Json(new
{
Tubs = UnTested,
}, JsonRequestBehavior.AllowGet);
}
Modify the ajax success callback to
success: function (result) {
$.each(result.Tubs, function(index, item) {
var cell = $('<td></td>').text(item); // create the table cell
var row = $('<tr></tr>').append(cell); // create the table row
$('#notestedtable').append(row); // append the row to the table
});
}
Side note: It would be better to include var table=$('#notestedtable'); at the top of your script to cache the element and then use table.append(row); so avoid traversing the DOM again.
Try the following:
var table = document.getElementById("notestedtable");
for (var i = 0; i < result.Tubs.length; i++) {
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
cell.innerHTML = result.Tubs[i];
}