Displaying data in table(view) passed from Controller - Codeigniter - javascript

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

Related

Updating the values attribute of a table inside a JSP page after an AJAX call

I have problem in displaying the content of a table which will be available once an AJAX request is made on click of some row of another table in the same page.
Following is my code for the table in my JSP page.
<table id="previousList" class="table">
<thead>
<tr>
<th colspan="6">Previous Billing Records</th>
</tr>
<tr>
<th>Bill Number</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<c:forEach var="lastBill" items="${previousBills}" varStatus="status">
<tr>
<td>${lastBill.billingId}</td>
<td>${lastBill.billAmount}</td>
</tr>
</c:forEach>
</tbody>
</table>
var jsonData;
var patientTable = $('#patientsList').DataTable();
var table = document.getElementById("selectedPatient");
$('#patientsList tbody').on('click', 'tr', function() {
var data = patientTable.row(this).data();
console.log("Data " + data);
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/billing/lastBill",
data: "patientId=" + data[0],
success: function(response) {
console.log("Showing the LastBill Details: " + response);
jsonData = response;
},
error: function(e) {
alert('Error: ' + e);
}
});
});
My controller code is as follows.
#RequestMapping(value="/lastBill")
public #ResponseBody String lastBill(ModelMap model, String patientId)
{
System.out.println("ID: " + patientId);
Gson gson = new Gson();
Bill b = new Bill();
b.setBillAmount(1000);
b.setBillingId("12345SDf");
Collection<Bill> bills = new ArrayList<Bill>();
bills.add(b);
model.addAttribute("previousBills",bills);
String jsonBills = gson.toJson(bills);
model.addAttribute("jsonBills", jsonBills);
return jsonBills;
}
I am able to get the JSON data but failed to bind the values to the table. Any suggestions/answers would be appreciable. Thanks in advance.
try this it should work.
var jsonData;
$('#patientsList tbody').on('click', 'tr', function() {
var data = patientTable.row(this).data();
console.log("Data " + data);
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/billing/lastBill",
data: "patientId=" + data[0],
success: function(response) {
console.log("Showing the LastBill Details: " + response);
jsonData = JSON.parse(response);
$.each(jsonData, function(i, bill) {
var newRowContent = "<tr><td>"+bill.billingId+"</td><td>"+bill.billAmount+"</td></tr>";
$("#previousList tbody").append(newRowContent);
});
},
error: function(e) {
alert('Error: ' + e);
}
});
});

How to send parameters to Action from javascript function?

I have a simple view that show a table of data, I want to sort one of its columns when the header is clicked by AJAX, I'm new to AJAX and JS, so this was my try in the view:
<table id="tbl" class="table">
<tr>
<th>
<a style="cursor: pointer" onclick="getData('desc')" id="sort">Title</a>
</th>
<th>
Author
</th>
<th></th>
</tr>
</table>
#section scripts{
<script type="text/javascript">
$(document).ready(getData('asc'))
function getData(sort) {
var srt = sort;
$.ajax({
type: 'GET',
url: '/Book/BooksData/' + srt,
dataTtype: 'json',
success: function (data) {
$("#tbl > tr").remove();
$.each(data, function (index, val) {
$('#tbl').append('<tr><td>' + val.Title + '</td><td>' + val.Author.Name + '</td></tr>')
});
}
});
}
</script>
}
but when I click the header the sort parameter goes null in the action,
public JsonResult BooksData(string sort)
{
var books = new List<Book>();
if (sort == "asc") books = db.Books.Include(b => b.Author).OrderBy(b => b.Title).ToList();
else books = db.Books.Include(b => b.Author).OrderByDescending(b => b.Title).ToList();
return Json(books, JsonRequestBehavior.AllowGet);
}
Yes I'm doing it wrong, but I revised it many times, I can't see logical error except that passing parameters in JavaScript is different than C#
Here is the simpliest way.You need to concatenate sort value to url, using query string.
Now, when you click header the sort parameter must goes with your value in the action.
Please try this:
$.ajax({
type: 'GET',
url: '/Book/BooksData?sort=' + srt,
dataType: 'json',
success: function (data) {
$("#tbl > tr").remove();
$.each(data, function (index, val) {
$('#tbl').append('<tr><td>' + val.Title + '</td><td>' + val.Author.Name + '</td></tr>')
});
}
});
Another way is to use this:
url: '#Url.Action("BooksData","Book")?sort=' + srt
The #Url.Action returns just a string.
In Razor every content using a # block is automatically HTML encoded by Razor.

how send table content to controller

I have a problem to send table global from view to controller the table in controller is full but in controller affect a null for the composant of table
and this is the controller method :
public Boolean ajoutermodule(string nom, modules[] global, int cv)
{
return true;
}
And this the view and method ajax how i append my table global and how i sent this table global from view to controller :
function Addmodule() {
var nom = $("#nomprojet_I").val();
var cv = global.length;
$.ajax({
url: "/Module/ajoutermodule",
type: "POST",
dataType: 'json',
data: {
"nom": nom,
"global": global,
"cv": cv,
},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});
}
var global = [];
function OnGetSelectedFieldValues(s, e) {
var SelectedUsers = $("#teamlist_I").val() + " " + $("#teamid_I").val();
listbox.AddItem(SelectedUsers);
var nom = $("#teamlist_I").val();
var id = $("#teamid_I").val();
global.push({ "id": id, "nom": nom });
debugger;
}
and when i added the length it send him correctly to controller.
but method ion your controller like this:
public Boolean ajoutermodule(string nom, stirng s, int cv)
{
return true;
}
and add this to your method ajax
var s = JSON.stringify(global);
function Addmodule() {
var nom = $("#nomprojet_I").val();
var s = JSON.stringify(global);
var cv = global.length;
$.ajax({
url: "/Module/ajoutermodule",
type: "POST",
dataType: 'json',
data: {
"nom": nom,
"s": s,
"cv": cv,
},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});
}
it will work inchallah
Please try this code for ASP.NET MVC –
View.cshtml
<table id="StepsTable">
<tr>
<td>Step 1</td>
<td>#Html.TextBox("step1")</td>
</tr>
<tr>
<td>Step 2</td>
<td>#Html.TextBox("step2")</td>
</tr>
<tr>
<td>Step 3</td>
<td>#Html.TextBox("step3")</td>
</tr>
</table>
<input id="SendToControllerButton" type="button" value="Send to the server"/>
<script>
$(document).ready(function () {
$("#SendToControllerButton").click(function () {
var data = {};
//Collects the data from textboxes and adds it to the dictionary
$("#StepsTable tr").each(function (index, item) {
var tds = $(this).find("td");
var textBoxTitle = $(tds).eq(0).text();
var textboxValue = $(tds).eq(1).find("input").val();
data["stepsDictionary[" + index + "].Key"] = textBoxTitle;
data["stepsDictionary[" + index + "].Value"] = textboxValue;
});
//Makes ajax call to controller
$.ajax({
type: "POST",
data: data,
url: "/Home/ProcessStepsValues",
success: function (message) {
alert(message);
}
});
});
});
</script>
And then sends the data to controller
Controller.cs
[HttpPost]
public string ProcessStepsValues(Dictionary<string, string> stepsDictionary)
{
string resultMessage = string.Empty;
if (stepsDictionary != null)
{
resultMessage = "Dictionary data passes to controller successfully!";
}
else
{
resultMessage = "Something goes wrong, dictionary is NULL!";
}
return resultMessage;
}
Please refer the site for more details
https://alexkuznetsov.wordpress.com/2013/05/08/asp-net-mvc-pass-dictionary-data-from-view-to-controller/

populating data to html table using ajax, jquery and making it searchable

I'm loading data dynamically to html table as below. I'm using Datatable for ssearch.
Technology stack used is:
Spring MVC
Hibernate
Ajax
JQuery
function getdata()
{
$.ajax({
type: "GET",
url: "/controllerURL.html", //controller URL
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (results) {
console.log(results)
var success = results.success;
if(success){
var finaldata = "<tbody><thead><tr><th>ID</th><th>data1</th><th>data2</th><th>Update</th></tr></thead>"; //data
var data = results.message;
data = jQuery.parseJSON(data);
alert(data);
for(var i = 0; i < data.length; i++){
var value = data[i];
finaldata = finaldata+ "<tr><th>"+value.ID+"</th><th>"+value.variable1+"</th><th>"+value.variable2+"</th></tr>";
}
finaldata = finaldata + "</tbody>";
$("#tableID").html(finaldata);
}
},
error: function (data) {
alert("fail");
console.log('ajax call error');
}
});
}
I'm now be able to load data into table. but can someone explain how to add search option to it.
You can use datatables click here
It will provide you various inbuilt functionality that you may want to integrate
<!--dependencies for data table -->
<script src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js" type="text/javascript"></script>
Your html should look like this
<table id="stable" class="display table-responsive table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Data1</th>
<th>Data2</th>
<th>Data3</th>
<th>Data4</th>
</tr>
</thead>
finally write this script
$(document).ready(function () {
$('#table').DataTable();
});

Load table with updated data via ajax

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

Categories

Resources