Reload Table getting its name instead id - javascript

i use javascript to reload my table after i input some data, my table goes like this
BEFORE INPUT
AFTER INPUT
u can see that after i input some data the table reload its id instead of its name like on the image, how can i make a way for javascript to reload its name instead of id, below are my code
JS
//reload table data
function reloadTableDataBasedOnVal(result){
var table = tableProject.dataTable(),
oSettings = table.fnSettings();
table.fnClearTable(this);
var contents = result.content;
for(var i = 0 ; i < contents.length ; i++){
var project = contents[i];
var item=[project.cv_id,project.cv_name,project.cv_client_id,project.cn_invoice_method,project.cn_project_rate,project.cn_note,btn];
table.oApi._fnAddData(oSettings, item);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
table.fnDraw();
}
function reloadTableData(){
$.ajax({
url : 'get-all-project',
type : 'GET',
dataType : 'json',
success: function(result,status){
if(status == successStatus){
reloadTableDataBasedOnVal(result);
}
},
errror: function(result,status){
errorNotification("Unknown error, Please contact your administrator!");
}
});
}
VIEW
#foreach($projects as $project)
<tr class="odd gradeX">
<td>{{$project->cv_id}}</td>
<td>{{$project->cv_name}}</td>
<td>{{$project->client['cv_name']}}</td>
<td>{{$project->invoice['cv_method']}}</td>
<td>{{$project->cn_project_rate}}</td>
<td>{{$project->cn_note}}</td>
</tr>
#endforeach
in the view i can do something like this <td>{{$project->client['cv_name']}}</td> since it was a simple php but in javascript i did something similar its show an error, the main code in JS is this line var item=[project.cv_id,project.cv_name,project.cv_client_id,project.cn_invoice_method,project.cn_project_rate,project.cn_note,btn]; that code is the one make the output when the tables reloaded

Related

How to set json data into a html table

i want to display these json data into a html table. i am trying to do many things but i cant figure out how can i do it. So anyone can please help me to fix it.
the json data set will appear in the console. but i cant set it to a table.
this is my model
public function displayRecords()
{
$this->db->select('A.*');
$this->db->from('rahu AS A');
$this->db->where('A.status',1);
return $this->db->get()->result_array();
}
this is my controller
public function allrecodes()
{
/*script allow*/
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed here.');
}
$response= array();
$response['result'] = $this->RahuModel->displayRecords();
echo json_encode($response);
}
this is my js
var get_rec = function(){
//alert("WWW");
$.ajax({
//request ajax
url : "../dashbord/allrecodes",
type : "post",
contentType: "application/json",
dataType : "json",
success: function(dataset) {
//var myobject = JSON.stringify(result);
//alert(myobject[0]);
console.log(dataset);
console.log(dataset.result[0]['id']);
},
error: function() { alert("Invalide!"); }
});
};
the json dataset will appear in console.
And also this get_rec() in js file will called top of the page.
$(document).ready(function() {
//alert("Hello, world!");
get_rec();});
can anyone please help me to fix it.. thank you !!
There is no "simple" way to do it. You will have to loop through the resultset and render the html.
function renderTable(data) {
var result = ['<table>'];
var header = false;
for (var index in data) {
var row = data[index];
if (!header) {
// Create header row.
header = Object.keys(row);
var res = ['<tr>'];
for (var r in header) {
res.push("<th>" + header[r] + "</th>");
}
res.push('</tr>');
result.push(res.join("\n"));
}
// Add data row.
var res = ['<tr>'];
for (var r in header) {
res.push("<td>" + row[header[r]] + "</td>");
}
res.push('</tr>');
result.push(res.join("\n"));
}
result.push('</table>');
return result.join("\n");
}
document.getElementById('output').innerHTML = renderTable(data);
Have a div tag with id output on your HTML
<div id="output"></div>

How to update data in SQL for an html table row using Input Button, in JS or C#?

I have a datatable in C# and I am converting it to html table like below.
public static string ConvertDataTableToHTML(DataTable dt)
{
StringBuilder html = new StringBuilder();
html.Append("<table id='example' class='table table-striped table-bordered' cellspacing ='0' width ='100%' font size='8' aria-hidden='true'>");
//add header row
html.Append("<thead>");
html.Append("<tr>");
for (int i = 0; i < dt.Columns.Count; i++)
html.Append("<td>" + dt.Columns[i].ColumnName + "</td>");
html.Append("<td>" + "Action" + "</td>");
html.Append("</tr>");
html.Append("</thead>");
//add rows
for (int i = 0; i < dt.Rows.Count; i++)
{
html.Append("<tr>");
for (int j = 0; j < dt.Columns.Count; j++)
html.Append("<td>" + dt.Rows[i][j].ToString() + "</td>");
html.Append("<td><input type=\"button\" value=\"Delete\" onclick=\"deleteRow(this)\"/></td>");
html.Append("</tr>");
}
html.Append("</table>");
return html.ToString();
}
This is showing a table in my aspx page like below:
Name City Quantity Action
A X 5 Delete
B Y 10 Delete
C Z 15 Delete
When I click "Delete" button for a row, the function below works and the row is gone from the result table.
<script>
function deleteRow(btn)
{
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
</script>
What I want is that, in addition to the current process, I need to run a SQL query to update IsRemoved flag for this data in my SQL Server 2014 table.
The query I need to run: Update MyTable set IsRemoved=1 where Name='A' and City='X'
I could not manage to run it in JavaScript function, and could not find a way to execute another function in C# after the JS function. OnClientClick is not working since it is not an asp:Button, and when I try to use asp:Button instead of input element, it does not show it on the screen.
How can I change data in DB here for such an example? Please note that I am trying not to use a GridView. Any help would be appreciated.
EDIT: By using Ajax, how can I send paramaters from my ajax call to c#:
I am trying:
$.ajax({
type: 'POST',
url: 'mypage.aspx/DeleteRowFromDB',
data: JSON.stringify({ name: **<nameshouldcomehere>**, city:**<cityshouldcomehere>** }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
});
I can't find how to set name and city dynamically based on the row clicked the delete button, any tips?
In your .cs page create a WebMethod which will mark the Database entry as IsRemoved=1 as:
[System.Web.Services.WebMethod]
public static string DeleteRowFromDB(string name,string city)
{
var status = "0";
//Your code to mark `IsRemoved=1` for the selected entry goes here and set the `status` variable as status="1" if the DB command successed.
return status;
}
And then create a function with an ajax call to invoke the created WebMethod and remove the row from HTML if the status is true as:
function deleteRow(btn)
{
var row = btn.parentNode.parentNode;
var cells = row.getElementsByTagName("td");
var reqData = JSON.stringify({ name: cells[0].innerText, city:city=cells[1].innerText });
//now make a call to the `WebMethod` via `ajax`.
$.ajax({
type: 'POST',
url: 'mypage.aspx/DeleteRowFromDB',
contenttype: 'application/json; charset=utf-8',
data: reqData,
datatype: 'json',
success: function (response) {
if(response === "1") {
row.parentNode.removeChild(row);
}
else
{
//do other stuff
}
},
error: function (error) {
//handle the error
}
});
}
Note: if the response variable in the ajax success function doesn't have the desired value try to look for its response.d property value.

how to make a variable to echo this data on ajax

I have ajax code:
<script type="text/javascript">
$(".monitor").click(function(){
$("#list-format").html("");
let nama_puskesmas = $(this).data('nama');
let id_puskesmas = $(this).data('id');
let nomor = $(this).data('nomor');
let base_url = '<?php echo base_url();?>'
$.ajax({
url : 'get_data',
method : 'post',
dataType: 'json',
data : {id_puskesmas:id_puskesmas},
success : function(response){
$.each(response, function(i, obj){
$("#list-format").append("<li>"+obj.format+"</li>");
});
$("#title-modal").html(nama_puskesmas);
$("#exampleModalCenter").modal('show');
$("#button-submit").html(`Lihat data`)
$("#button-submit2").html(`Kirim Pesan`)
}
})
})
</script>
If I run this program, it will view like this:
Data yang belum diupload
1.Form Lap PTM
2.Form Lap Posbindu
3.Form Lap IVA
4.Form Lap Jiwa
5.Form Lap Indera dan Gimul
6.Form Lap Diare
7.Form Lap LROA
8.Form Lap Thypoid
9.Form Lap Laporan Hiv Aids dan IMS
10.Form Laporan Hepatitis
I will then echo this data to my another function.
How can I make a variable from this code?
$.each(response, function(i, obj){
$("#list-format").append("<li>"+obj.format+"</li>");
});
To echo on this :
$("#button-submit2").html(`Kirim Pesan`)
Or can I make an echo to this #button-submit2?
<script type="text/javascript">
// this var contains a new element, which is not yet appended to the DOM
var $receivedItems = $('<div></div>');
$(".monitor").click(function(){
$("#list-format").html("");
let nama_puskesmas = $(this).data('nama');
let id_puskesmas = $(this).data('id');
let nomor = $(this).data('nomor');
let base_url = '<?php echo base_url();?>'
$.ajax({
url : 'get_data',
method : 'post',
dataType: 'json',
data : {id_puskesmas:id_puskesmas},
success : function(response){
$.each(response, function(i, obj){
// instead of echoing it directly by appending it to the DOM, store your list items in the hidden or not-appended element in your variable
$receivedItems.append("<li>"+obj.format+"</li>");
$("#list-format").append("<li>"+obj.format+"</li>");
});
// ..... your other stuff
var buttonHtml = `Kirim Pesan`;
var $button2 = $(buttonHtml);
$button2.on('click', function(e) {
// be aware to use href only as a fallback if js does not work. otherwise your url will change and js won’t be executed
e.preventDefault();
// on click, you can append the list items stored in $receivedItems
$("#list-format").append($receivedItems.children());
});
// be aware of nesting a and button tags, you shouldn’t
$("#button-submit2").append($button2);
}
})
})
</script>
I put some comments in the code. In this approach you can store all received items in a jQuery object which is not yet appended to a DOM node. It will be by triggering the on-click event which is added to the submit2 button.

How can I check if any links are clicked on a page?

So I have a page with several modes drawn based on a php variable (view, edit, add). I have some jquery adding info to td tags, but it would always post to the ajax target php file (and block some links/behavior). So to fix it, I had to add a check to only show on view mode.
However, now the edit mode for some reason also shows view for the same variable I am checking and I can't change the class that does it. What I'd like to do is execute my code by default, except when any link is pressed (so it will always follow the link). How can I do that?
<script>
$(document).ready(function(e){
var msg ='<?php echo $mode; ?>';
if(msg == 'view'){
//get all appointment numbers
count=0;
appointment_nums = [];
$('.mgrid_table > tbody > tr').each(function() {
appointment_nums.push($(this).find('td').eq(3).find('label').html());
});
appointment_nums = appointment_nums.filter(function(n){ return n != undefined });
appointments = appointment_nums.length;
function ajax() {
return $.ajax({
type:"post",
url: "../testrequest.php",
data : {appointment_nums:appointment_nums},
dataType:'json',
});
};
ajax().done(function(result){
$('table:nth-of-type(2) > tbody > tr > td:nth-of-type(2)').each(function() {
if($(this).children().length < 1){
if (result[count] == false){
$(this).append('Schedule Appointment ');
}else{
$(this).append('<span>Waiting For Doctor to Schedule</span>');
}
}
count = count + 1 ;
});
});
}
});
</script>

Javascript / JQuery loop through posted ajax data string to assign new values to

I have a function which updates a database via ajax. My issue is then how to update the data displayed on the page to show updated details. The POST data can vary and therefore the datastring would be something like this:
var dataString = '[name resource we are editing]=1' +
'&para1='+ para1 +
'&para2=' + para2+
'&para3=' + para3
I want the function below to split or loop through each of the POST variables in the datastring to update the text of an element on the page. I cannot figure out how.
function editAccount(dataString, details, form){
status = $(".status");
$.ajax({
type: "POST",
url: "<?php echo BASE_PATH; ?>/edit/",
data: dataString,
success: function(response) {
$.each(response, function(key, value) {
success_code = key;
message = value;
});
if(success_code == 1){
status.text(message).addClass("valid");
//show details and hide form
$("#" + details).show();
$("#" + form).hide();
//HOW to do below?
//update details being displayed with datasource data
//loop through dataString to assign eg. $('#para1')text(para1);
} else {
status.text(message).addClass("invalid");
}
},
error: function(response){
status.text("There was a problem updating your details into our database. Please contact us to report this error.").addClass("invalid");
}
});
}
As mentioned in a previous comment, I would suggest declaring the dataString variable as an object:
var dataString = { '[name resource we are editing]' : 1,
'para1': para1,
'para2': para2,
'para3': para3
}
Now it'll be much easier to loop over the params, just using the function each, for instance, which you already use in your code:
$.each(dataString, function(key, value) {
// Do stuff with each param
});
EDIT:
As #Qpirate suggests, you also can use the javascript for loop:
for(var key in dataString){
// value => dataString[key]
}

Categories

Resources