I am trying to fetch the data from files using Ajax by clicking row of table (passing row values to button on clicking rows) or by entering the variables in text box and pressing button. But it does not seem to be working.(Pls don't downvote as i am C++ programmer and learning web development.)
<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script>
<table bodrder=1 class='list'>
<thead>
<tr>
<th class='A'>ID</th>
<th class='B'>Value</th>
<th class='C'>Name</th>
<th class='D'>Cell #</th>
<th class='E'>Nickname</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>54235</td>
<td>Benjamin Lloyd</td>
<td>(801) 123-456</td>
<td>Ben</td>
</tr>
<tr>
<td>2</td>
<td>44235</td>
<td>XXXXXX</td>
<td>642363673</td>
<td>TRE</td>
</tr>
</tbody>
</table>
<div id="tabs" class="plots-tabs" style="padding-top: 10px; padding-bottom: 10px">
<table>
<tr><td>ID:<input id="id" type="text" class="inputbox" /></td></tr>
<tr><td>Value:<input id="value" type="text" class="inputbox" /></td></tr>
</table>
This is DIV element which will be filled by div element on clicking button or by clicking table row which also generate the event and click the button by passing values to ajax and fetchign data.
<p style="width: 100%; text-align: right;"><button type="button" id="button">Submit</button></p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
//here ID and value are parsed through table click event or from text box on clicking button
$.ajax({
url:filename,
data: {
ID: $("input#id").val(),
Value: $("input#value").val()
},
success:function(result){
$("#tabs").html(result);
}});
var filename= "Data_"+ID+"_"+Value+".txt";
$("#tabs").load(filename);
});
});
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < 2; i++) {
data.push(cells[i].innerHTML);
}
}
alert(data);
};
</script>
</body>
</html>
cat Data_2_54235.txt
Nice Work! Your code is working with first file.
cat Data_2_44235.txt
Nice Work! Your code is working with second file.
how can i implement the above code.
I see you generate a filename based on input values. That means that the ajax call will be made upon that filename, which is odd, becouse you have to create a file with that name.
Anyway, i don't see nowhere in your code that by clicking table rows you make an ajax call, you only save the innerHTML text to a variable data = [] and then alert it. But the problem is not here (if you don't expect to make ajax call when clicking table-rows), but it is inside the ajax call you are making when clicking the button.
first
url:filename
var filename= "Data_"+ID+"_"+Value+".txt";
I strongly suggest you don't do that. It will work if you make an ajax call to a php script which creates that txt file with filename name, and then make another ajax call to that file and fetch it.
second
data: {
ID: $("input#id").val(),
Value: $("input#value").val()
}
look here at data, the doc explains it. the code above means that to filename it will pass parameters (GET parameters, i.e. x?=...), but becouse your file is .txt, this doesn't make sense.
third
$("#tabs").load("demo_test.txt");
This will add the text inside demo_test.txt to $("#tabs") , like innerHTML does or .html() does. Do you have demo_test.txt on your host? i suppose this should work.
just change you ajax call and load call with this. this should work :
$("button").click(function() {
$.ajax({
url : "demo_test.txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
}
});
});
For clicking the table-rows, just add an event listener to table-rows, and make an ajax call. read the link i send you, as they are important to understand better what is ajax.
You can see no unnecessary data parameter is thrown to ajax call, and i put there an dataType, meaning that we expect text data to be recieved. If this doesn't work, you have to be sure that you are working on localhost server(for ajax to work...) and you have demo_test.txt , and the url is passed correctly
example using input values to fetch from ajax:
$("button").click(function() {
var id = $("input#id").val();
var value = $("input#value").val();
$.ajax({
url : "Data_" + id + "_" + value + ".txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
},
error: function (data) {
#("#tabs").html('No such file found on server');
}
});
});
example of event handler click <tr>
$("table tbody").on("click", "tr", function() {
var id = $(this).find("td")[0].text(); // gets the first td of the clicked tr (this is the ID i suppose)
var value = $(this).find("td")[1].text(); // gets the second td of the clicked tr (this is the VALUE i suppose)
$.ajax({
url : "Data_" + id + "_" + value + ".txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
},
error: function (data) {
#("#tabs").html('No such file found on server');
}
});
});
Related
I have some complication with service removing. I have function that removes service on the server but I have to reload page to update table. I found way how to remove row by click-binding but there is the issue beacuse I can only remove row or get ID for delete service from server NOT both. :/
This is example of code that removes service on the server but doesn't remove table row.
HTML:
<table id="serviceView" class="fixed_header" border: 1>
<thead>
<tr>
<th>Name</th>
<th>Adress</th>
<th>Notification</th>
</tr>
</thead>
<tbody data-bind="foreach: services">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: address"></td>
<td data-bind="text: serviceId"></td>
<td ><button data-bind="click: $parent.DeleteService.bind(this, serviceId)">Remove</button></td>
</tr>
</tbody>
</table>
JS:
self.services = ko.observableArray([]);
self.lastCheck = ko.observable();
$.getJSON("http://localhost:55972/api/status", function (data) {
self.services(data.services);
self.lastCheck = data.lastCheck;
}); //////This is loading data to the table from server
self.DeleteService = function (serviceId) {
$.ajax({
type: "GET",
url: "http://localhost:55972/api/services/remove/" + serviceId,
}).done(function () {
self.services.remove(serviceId)
})
};
This is example of code that removes table row
When I use click-binding like this:
<button data-bind="click: $parent.DeleteService">Remove</button>
And change delete function to this:
self.DeleteService = function (serviceId) {
self.services.remove(serviceId)
$.ajax({
type: "GET",
url: "http://localhost:55972/api/services/remove/" + serviceId,
}).done(function () {
// here I want to remove row but i doesnt goes here without service ID.
})
};
It removes row but instead serviceId I got [object, object] in the URL.
Can you help me with it ? I got idea to use jquery to just update the table but it's seems unnecessarily complicated for me when I can use knockout.
I know the solution is not that hard but I'am just unable to solve it..... -_-
I'am sorry for taking time with this bullshit but this is my first real project and I'am so desperate at this point beacuse I have lot of things to do and I'am stucked on this.
In your Js code, you can try this:
self.services = ko.observableArray([]);
self.lastCheck = ko.observable();
$.getJSON("http://localhost:55972/api/status", function (data) {
self.services(data.services);
self.lastCheck = data.lastCheck;
}); //////This is loading data to the table from server
var serviceIdRemoved;
self.DeleteService = function (serviceId) {
serviceIdRemoved = serviceId; // now you can do whatever you need more with this value
$.ajax({
type: "GET",
url: "http://localhost:55972/api/services/remove/" + serviceId,
}).done(function () {
self.services.remove(serviceId)
})
};
With this way of work you can user the content of the variable and donĀ“t loose it. Also if you get [Object, Object], you can:
console.log(serviceId) // to see the content in the console.
JSON.stringify(data) //to see the content in html
This source could help you to understand it better.
The [object, object] you are seeing is actually the data and event objects which are secretly added to the JS function parameters by Knockout. If you want to add your own parameter to the click binding then you should do it like this:
<button data-bind="click: function(data, event) { $parent.DeleteService(serviceId, data, event) }">Remove</button>
You can then define your JS function as follows:
self.DeleteService = function (serviceId, data, event) {
[code here...]
}
You can read up on the exact details of it in the excellent Knockout documentation here:
http://knockoutjs.com/documentation/click-binding.html
It's about half-way down under the heading that reads Note 2: Accessing the event object, or passing more parameters
I'm trying to edit a table by adding rows, but running into an issue with the the partial view not being fully rendered (This is my assumption)
I'm loading the partials into their divs via page load and ajax calls;
<div id="preTestSteps">
</div>
<div id="mainTestSteps">
</div>
<div id="postTestSteps">
</div>
Scripts;
$(document).ready(function() {
var testSuiteExecutionId = #(Model.TestSuiteExecutionId);
var testSuiteId = #(Model.TestSuiteId);
loadTestStepResultsPartialView(testSuiteExecutionId, testSuiteId, 1, "preTestSteps");
loadTestStepResultsPartialView(testSuiteExecutionId, testSuiteId, 0, "mainTestSteps");
loadTestStepResultsPartialView(testSuiteExecutionId, testSuiteId, 2, "postTestSteps");
});
function loadTestStepResultsPartialView( testSuiteExecutionId, testSuiteId, testStepType, divId) {
$.ajax({
type: 'POST',
url: '#Url.Action("DetailsTestStepResults", "TestSuiteExecutions")',
data: { 'testSuiteExecutionId': testSuiteExecutionId, 'testSuiteId': testSuiteId, 'testStepType': testStepType },
success: function(data) {
$("#" + divId).html(data);
}
});
In the partial view, the table has a unique ID which is accessed to append (view model is a list of viewmodels, using the first index is to get data which is unique for the list of logs);
<div id="#collapseStepItemName" class="collapse col-sm-12" role="tabpanel" aria-labelledby="headingOne">
<div class="card-body">
<table class="table" id="logTable_#Model[0].TestStepId#Model[0].MessageType">
<thead>
<tr>
<th width="5%"></th>
<th width="20% !important">Time</th>
<th width="75%">Message</th>
</tr>
</thead>
<tbody>
#foreach (var logEntry in Model)
{
<tr id="tableRow_#logEntry.TestStepId#logEntry.MessageType">
<td><img width="20" height="20" src="~/Content/Images/#HtmlUtilities.GetTestSuiteExecutionIconName(logEntry.LogType)" /></td>
<td><i>#logEntry.TimeStamp</i></td>
<td><i>#Html.Raw(HtmlUtilities.GetHtmlFormattedString(logEntry.Message))</i></td>
</tr>
}
</tbody>
</table>
</div>
The current test code (with hard coded tableID for the sake of testing) is the following;
var tableId = "logTable_" + 44 + "False";
var newRow = document.getElementById(tableId).insertRow();
newRow.innerHTML="<td>New row text</td><td>New row 2nd cell</td><td>Please work</td>";
The following error is thrown in the browser debug;
Uncaught TypeError: Cannot read property 'insertRow' of null
Is there a way to execute the script after the partial views are fully rendered? Or is this issue something else and not due to the views being loaded in?
I made sure the table appending script actually works by testing it on a table in the main view, and it worked as intended.
Since you're using jQuery, place this code inside document.ready function:
$(document).ready(function() {
// other stuff
var tableId = "logTable_" + #Model[0].TestStepId + #Model[0].MessageType;
var row = $('<tr>').append('<td>New row text</td><td>New row 2nd cell</td><td>Please work</td>');
$('#' + tableId).find('tbody').append(row);
});
If you insist using vanilla JS to add rows, make sure that all DOM objects are already loaded as given in example below:
document.addEventListener("DOMContentLoaded", function (ev) {
var tableId = "logTable_" + #Model[0].TestStepId + #Model[0].MessageType;
var newRow = document.getElementById(tableId).insertRow();
newRow.innerHTML="<td>New row text</td><td>New row 2nd cell</td><td>Please work</td>";
}
The reason behind insertRow has null value is that table DOM elements may not fully loaded when adding row script executes, hence row addition script should run when all required DOM elements are complete.
Demo example: JSFiddle
<script type="text/javascript">
function LoadData(){
var url = serverURL+"/List.php";
$.ajax({
type: "GET",
url: url,
dataType: "json",
success: function(data){
$.each(data.data, function (key, value) {
var doc_id=value['id'];
var doc_name=value['name'];
var doc_speci = value['specialize'];
$("#myTable").append("<tr><td>"+doc_name+"</td><td>"+doc_speci+"</td><td class='retrieve' data-did="+doc_id+" style='cursor: pointer;'>EDIT</td></tr>");
});
},
error: function(data){
toastr.error("Opps! Something went wrong");
$(".se-pre-con").fadeOut("slow");
},
});
}
</script>
The above appends a tr to my html table below.
The HTML TABLE is as follows:
<table id="myTable" class='table table-bordered table-hover table-striped'>
<tr>
<th>Name</th>
<th>Specialization</th>
<th>Action</th>
</tr>
</table>
Now i want to retrieve the id from the data attribute from td class retrieve so that i can send the id and redirect it to other page for editing.
// Clicks the edit field
$("td.retrieve").on("click", function(e) {
var id = $(e.currentTarget).attr("data-did");
// do with the ID what you want
alert(id);
});
I'm aware that jQuery has a "data(...)" function but I've run into issues with that sometimes in the past. "attr(...)" will do something similar but relies specifically on the attribute instead of stored objects.
First, to add your data attribute you should make sure you add quotes around the value:
data-did='"+doc_id+"'...
So the rendered cell must look something like this:
<td class='retrieve' data-did='n' style='cursor: pointer;'>EDIT</td>
(where n is some value)
Then you can easily retrieve this value with jQuery:
$('specific-td').data('did'); //specific-td referes to a specific cell in a row, you must write that, this is just an example
To get all of the rows:
var ids = [];
$('.retrieve').each(function() {
ids.push($(this).data('did'));
});
Example:
If you have a button for example:
$('#myTable').on('click', '.retrieve input[type="button"]', function() {
var id = $(this).parent().data('did');
alert(id);
});
JSFiddle: https://jsfiddle.net/y2an0fu7/1/
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm looking to add a page to my website that will have a table that will display the products that are available.
What I would like to be able to do, is make it so that the contents of the table can be changed from another page (say an admin page). Is it possible to do something like this using JavaScript or something similar? If so can you please point me in the right direction.
Much appreciated thanks.
There are few ways.
Not involving server-side
You need a reference to the other window. You can get that e.g. by opening the window - window.open().
Then you use the HTML DOM methods, e.g. the document.getElementById(...) and then the specific element's API:
https://developer.mozilla.org/en/docs/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces
http://www.w3schools.com/jsref/dom_obj_table.asp
Involving server-side
This means that one page would send some data to the server and the other would read them.
You can use the AJAX concept for that - see the answer with XMLHttpRequest.
The other page would have to check periodically, or the first page would have to give it some signal - call some JavaScript method you wrote, or reload the window. Other option would be to use the push concept, but that's currently an advanced technique.
You could use XMLHttpRequest for this , but I would recommend that you use jQuery which would then be the $.ajax() function. What this does is send data to the server without refreshing the page or without anybody knowing about it really.
So what you could do is on the admin side is send some changes data to the server and on the client side unless you use a Web Socket you would have to contact the server every so many seconds to see if there are any changes. then the server would send you any changes that would have been made by the admin then you would work with that result with javascript to display changes on the web page.
What is Ajax
jQuery Ajax
Here is the requested example using jQuery
in your php you would have something like this
if($_POST['type'] === 'updateProduct') {
// update database with new price
// You could have a field in the database that now say's
// that the product has been updated
// send the response
echo 'done';
}
// And the admin ajax something like this
$.ajax({
type: 'POST',
url: 'linkToYourFile.php', // The php file that will process the request
data: {
type: 'updateProduct', // This is all the data you wan't to send to your php file
productID: 8484737,
newPrice: '$100.99'
},
success: function( result ) { // if we get a response
if(result === 'done') {
// The product has been updated from the admin side
}
}
});
// on the client side
if($_POST['type'] === 'checkForUpdates') {
// Contact the database and check that $_POST['productID']
// has been updated
// use php's json_encode function to echo the result
}
var checkForUpdates = function() {
$.ajax({
type: 'POST',
url: 'LinkToYourFile.php',
dataType: 'JSON',
data: {
type: 'checkForUpdates',
productId: 8484737
},
sucess: function ( result ) {
if( result.updated === true ) {
someElementPrice.textContent = result.newPrice;
}
}
});
};
window.setInterval(checkForUpdates, 3000); // Send's the update request every 3 seconds
Note - it's not easy to do this stuff if your not familiar with it. but you will learn.
Thats the fun part. and there is a lot more to it behind the scenes, but this is the idea of it
Possible solution
Using an AJAX call, you could store the table itself in an HTML file.
Here is an example page. If you have any questions, do not hesitate to ask them. I added a few functions such as Add Row.
LIVE DEMO
Admin management page (index.html)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery AJAX</title>
<link type="text/css" rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<style rel="stylesheet" type="text/css">
tr, td,th{
border-collapse: collapse;
border:1px solid;
}
td{
height:22px;
min-width:125px;
}
</style>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">"http://jquery.com"</script>
<script type="text/javascript">
/* ---------------------------------- */
/* See the SCRIPT part of this answer */
/* ---------------------------------- */
</script>
</head>
<body>
<h1>jQuery AJAX Table</h1>
<section>
<article>
<div id="myTable" contenteditable></div>
<nav data-type="table-tools">
<ul>
<li>
New row
</li>
<li>
New column
</li>
<li>
Save table
</li>
</ul>
</nav>
</article>
</section>
</body>
</html>
SCRIPT
/* On page load */
$(document).ready(function () {
var getTable = function () {
/*We empty the div */
$('#myTable').html('');
/*We load the table */
$.get('myTable.html', function (callback_data) {
var table = callback_data;
document.getElementById('myTable').innerHTML = table;
});
};
getTable();
/* ----- */
/* New row button */
$('#addRow').click(function (event) {
/* Prevents the real anchor click event (going to href link)*/
event.preventDefault();
/* We get the number of columns in a row*/
var colNumber = $($('#myTable tbody tr')[0]).children('td').length;
var tr = document.createElement('tr');
var td = "";
for (var i = 0; i < colNumber; i++) {
td = document.createElement('td');
td.appendChild(document.createTextNode("\n"));
tr.appendChild(td);
}
$('#myTable tbody').append(tr);
});
$('#addColumn').click(function (event) {
event.preventDefault();
$.each($('#myTable table thead tr'), function () {
$(this).append('<th></th>');
})
$.each($('#myTable table tbody tr'), function () {
$(this).append('<td></td>');
});
});
$('#saveTable').click(function (event) {
event.preventDefault();
var table = $('#myTable').html();
$.post('saveTable.php', {
'myTable': table
}, function (callback_data) {
console.log(callback_data);
$('#myTable').slideToggle('fast');
setTimeout(function () {
getTable();
$('#myTable').slideToggle();
}, 100);
});
});
});
saveTable.php
<?php
if(!isset($_POST['myTable']))
die('No data provided.');
$table = $_POST['myTable'];
$handle = fopen('myTable.html','w');
$result = fwrite($handle,$table);
if($result)
fclose($handle);
else
die('Error writing file');
?>
myTable.html
<table>
<thead>
<tr>
<th>Lorem ipsum dolor.</th>
<th>Velit, vero, quis.</th>
<th>Id, dolore, commodi!</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lorem ipsum.</td>
<td>Voluptatibus, maiores.</td>
<td>Quod, et.</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Ex, assumenda!</td>
<td>Qui, pariatur!</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Alias, amet.</td>
<td>Delectus, itaque!</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Praesentium, quod.</td>
<td>Dolor, praesentium?</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Beatae, perferendis!</td>
<td>Voluptates, earum!</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Ratione, quis.</td>
<td>Cupiditate, repellendus.</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Porro, labore.</td>
<td>Eligendi, nemo!</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Soluta, suscipit.</td>
<td>Dolorem, dolores.</td>
</tr>
</tbody>
</table>
This is possible with some limitations:
You should change the table that displays the products, to fetch the values beeing displayed using ajax. Then you have 2 possibilities: (I'm pretty sure there are more but I only think of those 2 at the moment)
create a timer which will fetch the values for a product every X seconds
create a listener that will be called when a value in the db gets updated
This way you can change the values in an backend and the will be automatically updated in your frontend view.
You can have a look at the meteor framework where they use 'Live HTML' excessive.
I have a table list of companies with a [+] button next to each company name in my table list.
When user clicks [+], a javascript function uses jquery ajax to get and append a new table row below the row clicked, which will then display an indented list of departments.
All works great.. until we get to our beloved IE. I'm using IE 8, not tried this on prev versions.
Table list item HTML before a click:
<tr id="row1">
<td align="center">
<div id="button1" class="on" onclick="javascript:expandDepartments(1)"></div>
</td>
<td>Company 1</td>
</tr>
The onClick function:
<script>
function expandDepartments(s_cid) {
if ($('#button'+s_cid+'').hasClass('on')) {
$('#button'+s_cid+'').removeClass('on').addClass('off');
if ( document.getElementsByName('rowafter'+s_cid+'').length == 0) { //if the department list does not exist for this company (first time getting departments)
$.ajax({
type: 'POST',
url: 'ajax/common.php',
dataType: 'html',
data: 'a=getHomePageDepartments&cid='+s_cid+'',
success: function(txt){
setTimeout(function(){
$('#homeCompaniesList tbody').find('#row'+s_cid+'').after(txt);
},1000);
}
});
}else{ //otherwise, just re-show the row again, no need to request it again
setTimeout(function(){
var x = document.getElementsByName('rowafter'+s_cid+'');
for(var k=0;k<x.length;k++)
x[k].style.display = '';
},1000);
}
} else if ( $('#button'+s_cid+'').hasClass('off') ) { //hide the row when MINUS image clicked
$('#button'+s_cid+'').removeClass('off').addClass('on');
var x = document.getElementsByName('rowafter'+s_cid+'');
alert(x.length);
for(var k=0;k<x.length;k++)
x[k].style.display = 'none';
}
}
</script>
The HTML output for a company containing multiple departments:
<tr style="display:;" name="rowafter1"><*td data not important*..
<tr style="display:;" name="rowafter1">
<tr style="display:;" name="rowafter1">
<tr style="display:;" name="rowafter1">
<tr style="display:;" name="rowafter1">
Now, look at javascript function, line:
alert(x.length);
In Firefox, it alerts 5
In IE it alerts 0
Which tells me, the HTML elements injected into the page using jquery ajax are not accessible in IE and I have no idea why. Do I need to set an ajax parameter for ie?? Not sure.. please assist.
ta
IE has an issue with getElementsByName
Alternatively, why not use jQuery?
var x = $('*[name="rowafter'+s_cid+'"]'); //get all elements with name rowafterN
getElementsByName() does not work in < IE9. If you are using jQuery, use the attribute selector:
var x = $('[name="rowafter' + s_cid + '"]');
alert(x.length);