<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/
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
A user can search for people included in a database introducing the search terms in an input text.
I am using following Ajax script to show the database objects received from JSON:
<script type="text/javascript">
$(document).ready(function() {
// With JQuery
$("#ex6").slider();
$("#ex6").on("slide", function(slideEvt) {
$("#ex6SliderVal").text(slideEvt.value);
});
$('#keyword').on('input keyup change', function() {
var searchKeyword = $(this).val();
if (searchKeyword.length < 3) {
$('ul#content').empty()
}
if (searchKeyword.length >= 1) {
$.post('search.php', { keywords: searchKeyword }, function(data) {
$('#content').empty()
$('#content').append('<table class="table table-hover"><thead><tr><th>First Name</th><th>Last Name</th><th>Username</th></tr></thead><tbody>')
if (data == ""){
$('#content').append('No hay resultados para su búsqueda')
}
$.each(data, function() {
$('#content').append('<tr><td>'+this.nombre_doctor +'</td><td>'+ this.apellido1_doctor + '</td><td>'+ this.apellido2_doctor+'</td></tr>');
});
$('#content').append('</tbody></table>')
}, "json");
}
});
});
</script>
And this is the output when a user introduces a search term:
As you may see in the picture, the objects are not shown on the expected column.
What is wrong in the script?
When you call append with a string, jQuery constructs an object and appends that. In other words, append('<foo>') is really append($('<foo'>). The assumption in this code that append appends raw HTML is incorrect.
You want something like
var $table = $('<table class="table table-hover"><thead><tr><th>First Name</th><th>Last Name</th><th>Username</th></tr></thead></table>').appendTo('#content');
var $tbody = $('<tbody></tbody>').appendTo($table);
$.each(data, function() {
var $tr = $('<tr>').appendTo($tbody);
$('<td>').text(this.nombre_doctor).appendTo($tr);
$('<td>').text(this.apellido1_doctor).appendTo($tr);
$('<td>').text(this.apellido2_doctor).appendTo($tr);
});
// Nothing with </tbody></table> , those elements already exist
Note that your current code includes a significant vulnerability as it allows everybody who controls your data to inject arbitrary HTML and JavaScript into your website. The use of text avoids this.
You used a concate (+) function which packed all data into one column as a string. You should define 3 distinct columns to force a proper table layout.
<table width="100%" rules=groups border="0" cellspacing="0" cellpadding="0" class="table table-hover">
<colgroup>
<col width="33%" />
<col width="33%" />
<col width="33%" />
</colgroup>
Now you have a solid structure to insert your data, by column. The <th> will line up the way you have written the code.
Try building your table html as a string first, then use jquery's .html() to set it.
var htmlContents = "<table><tr><td>First column data</td><td>2nd column
data</td><td>etc</td></tr></table>";
$('#content').html(htmlContents);
That should do it.
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');
}
});
});
I am adding a button that will "approve" all rows in the table (call a URL to process the record). I generate the table then attach the DataTable to the prefilled table. On each tr I have the id number of the record.
<tr id="11309742">
<td>blah</td>
<td>blah</td>
<td>blah</td>
</tr>
<tr id="11309743">
<td>blah</td>
<td>blah</td>
<td>blah</td>
</tr>
Here is what I have so far:
$.each(table.fnGetData(), function (i, row) {
var id = $(this).attr("id");
$.get(myUrl, { id: id },
function (json) {
if (json.Sucess) {
// TODO remove from the page
}
}, "json");
});
var id = $(this).attr("id"); worked before I switched to the datatable plugin (and I know it won't work now). Everything I have seen is either setting the id or getting the index from a click in the row. How do I get that id attribute in a loop?
Instead of using .fnGetData(), I should have used .fnGetNodes().
$.each(table.fnGetNodes(), function (i, row) {
var id = $(this).attr("id");
$.get(myUrl, { id: id },
function (json) {
if (json.Sucess) {
//table.fnDeleteRow(i);
}
}, "json");
});
Now it works as expected.
HTML
<tr>
<td>No.</td>
<td id="2" class="editable">data1</td>
<td id="2" class="editable">data2</td>
<td>Usage Left</td>
</tr>
<!-- Multiple rows with different ids -->
javascript
<script type="text/javascript">
$(function () {
$('.editable').editable({ onSubmit: Update });
function Update() {
var id = $(this).parent('td').attr('id');
var title = $(this).text();
$.ajax({
type: 'post',
url: 'update.php',
data: 'title=' + title + '&id=' + id,
success: function (response) {
$('#response').fadeIn('1000').empty().append(response);
}
});
}
});
</script>
I want to get the value of the ids of class editable, this is an inline edit plugin i am using I am able to collect the data1 and data2 values but for id, I am getting undefined.
What is wrong with my code.
Thank You.
Shouldn't it be just $(this).attr('id')?
You are attaching the event to td. So this inside the event handler refers to the td itself.