<table class="pull-left table table-fill">
<thead>
<tr>
<th class="table-hover">Name</th>
<th class="table-hover">Price</th>
</tr>
</thead>
</table>
</body>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
url: 'api link here',
success: function (json) {
//var json = $.parseJSON(data);
for(var i =0;i < json.results.collection1.length;i++) {
var title = json.results.collection1[i].EventsUK.text;
var href = json.results.collection1[i].EventsUK.href;
$("table").append("<tbody><tr><td>"+title+"</td><td>"+href+"</td></tr></tbody>");
}
},
error: function(error){
console.log(error);
}
});
</script>
I receive the href from the website. How would i get the href into a button link? To display in the same place (the table. I have tried adding all the button commands i could to the code which hasnt worked, I have also tried adding it infront he of href and infront of the plus symbols.
Sam
Links are not resolved by themselves in HTML. You need to use the <a> tag instead. It's very dirty, but the quickest trick to do that, given your code, is changing your append into
$("table").append(""
+ "<tbody>"
+ "<tr>"
+ "<td>" + title + "</td>"
+ "<td>" + href + "</td>"
+ "</td>"
+ "</tr>"
+ "</tbody>"
);
... though I don't get the meaning of the table.
Related
I'm using Ajax for Crud operations in laravel 5.6 and I want to reload my table after insertion of data into the table.
This is how my table looks like without data:
After insertion, table looks like this:
Even after the data is added, when i search it doesn't consider the newly appended data in the table so my search result remains - no data available in the table.
The site.js
$(".complete-table").each(function(){
$(this).DataTable( {
dom: 'Bfrtip',
buttons: [
// 'copyHtml5',
// 'excelHtml5',
// 'csvHtml5',
// 'pdfHtml5'
]
} );
});
I tried a couple of things but it didn't work for me.
The HTML for the table
<table id="asset-{{ $asset_receive->asset_received_id }}" class="complete-table table toggle-circle table-hover" data-page-size="15">
<thead>
<tr>
<th> Tag ID</th>
<th> Asset Category </th>
<th> Manufacturer</th>
<th> Serial Number </th>
<th> Model Number </th>
<th> Colour</th>
</tr>
</thead>
<tbody id="asset-table-{{ $asset_receive->asset_received_id }}">
#foreach($assets->where('asset_received_id', '=', $asset_receive->asset_received_id) as $asset)
<tr>
<td>{{ $asset->tag_id}}</td>
<td>{{ $asset->asset_categories['category']}}</td>
<td>{{ $asset->manufacturers['manufacturer']}}</td>
<td>{{ $asset->serial_number}}</td>
<td>{{ $asset->model_number}}</td>
<td>{{$asset->colour}}</td>
</tr>
#endforeach
</tbody>
Here is my Js function for the adding data into the table.
$(document).on('click', 'button.submit-asset-received', function() {
assetReceivedId = $(this).data('asset-received-id');
assetFormId = 'form#form-assets-record-' + assetReceivedId;
$('.error').addClass('hidden');
$.ajax({
type: 'post',
url: '/addAsset',
indexForm: assetFormId,
indexValue: $(assetFormId + ' input[name=asset_a_category_name]').val(),
indexManufacturer: $(assetFormId + ' select[name=a_manufacturer_id] option:selected').text(),
data: {
'_token': $(assetFormId + ' input[name=_token]').val(),
'tag_id': $(assetFormId + ' input[name=tag_id]').val(),
'asset_category_id': $(assetFormId + ' input[name=asset_a_category_id]').val(),
'manufacturer_id': $(assetFormId + ' select[name=a_manufacturer_id] option:selected').val(),
'serial_number': $(assetFormId + ' input[name=serial_number]').val(),
'model_number': $(assetFormId + ' input[name=model_number]').val(),
'colour': $(assetFormId + ' input[name=colour]').val(),
'asset_received_id': assetReceivedId,
},
success: function(data) {
if((data.errors)){
var errors = data.errors;
$.each(errors, function (key, value) {
$('input[name=' + key + ']').next('p').removeClass('hidden');
$('input[name=' + key + ']').next('p').text(value);
if(key === 'manufacturer_id'){
$('select[name=a_manufacturer_id]').next('p').removeClass('hidden');
$('select[name=a_manufacturer_id]').next('p').text(value);
}
});
}else{
$('#asset-table-'+data.assets.asset_received_id).append("<tr>"+
// "<td>" + data.asset_category_id + "</td>"+
"<td>" + data.assets.tag_id + "</td>"+
"<td>" + this.indexValue + "</td>"+
"<td>" + this.indexManufacturer +"</td>"+
"<td>" + data.assets.serial_number + "</td>"+
"<td>" + data.assets.model_number + "</td>"+
"<td>" + data.assets.colour + "</td>"+
"</tr>");
var aTable = $('#asset-'+data.assets.asset_received_id).parent('table').dataTable();
aTable.ajax.reload();
$('#unassigned').html(data.view_1);
if(data.asset_received.qty_received != data.asset_received.qty_recorded){
$("form#form-assets-record-" + data.assets.asset_received_id).show();
}else{
$("form#form-assets-record-" + data.assets.asset_received_id).hide();
}
//increase quantity recorded of this asset by taking current value and increasing by one
var currentRecordedQuantity = parseInt($("td#qty_recorded_"+data.assets.asset_received_id).text());
console.log(currentRecordedQuantity);
$("td#qty_recorded_"+data.assets.asset_received_id).text(currentRecordedQuantity+1);
$('input[name=tag_id]').val('');
$('select[name=a_manufacturer_id]').val('');
$('input[name=serial_number]').val('');
$('input[name=model_number]').val('');
$('input[name=colour]').val('');
}
}
});
});
I tried using two different ways(in the js function for adding the asset) to solve the problem but they both failed and i don't know whether i did it wrongly.
First method
var aTable = $('#asset-table-'+data.assets.asset_received_id).parent('table').dataTable();
aTable.ajax().reload();
Second method
var aTable = $('#asset-table-'+data.assets.asset_received_id).parent('table').dataTable();
aTable.fnDraw();
is there a better way of reloading the table to notice any newly added data?
Any suggestions will be welcomed, thanks in advance.
I think you are looking for .draw()
https://datatables.net/reference/api/draw()
In success of your ajax call, simply do:
var table = $('.complete-table').DataTable();
table.draw();
There is method called
var table = $('.complete-table').DataTable();
table.ajax.reload();
Ok you first to tell your ajax request what you will receive so
$.ajax({
type: 'post',
url: '/addAsset',
indexForm: assetFormId,
dataType:'html',
now your return will be in separated blade file
in your controller will return
return view('table',compact('data_that_you_fetched_form'));
now in your table.blade file add the html
#foreach($data_that_you_fetched_form as $asset)
<tr>
<td>{{ $asset->tag_id}}</td>
<td>{{ $asset->asset_categories['category']}}</td>
<td>{{ $asset->manufacturers['manufacturer']}}</td>
<td>{{ $asset->serial_number}}</td>
<td>{{ $asset->model_number}}</td>
<td>{{$asset->colour}}</td>
</tr>
#endforeach
and finally add it to your table
success: function(data) {
$(asset-table-'{{ $asset_receive->asset_received_id }}').html(data);
}
I think that will work fine and clean and easy to modify
I am new to this and I want to add a action method on table cell. The problem is Table is generated by java-script(AJAX).
Here's code:
$.ajax({
url: "GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
success: function (obj) {
debugger;
$tbl.empty();
$tbl.append('<tr><th>ID</th><th>Name</th><th>Last Executed Date</th><th>Status</th></tr>');
for (var i = 0; i < obj.length; i++) {
$tbl.append(' <tr><td> ' + obj[i].senderId + '</td><td>' + obj[i].subject + '</td><td>' + obj[i].msg + '</td><td>TESTING</td></tr>');
}
}
});
Now instead of <a href="#"> I want to add Action Method #URL.Action on that <td>. Here's my Action Method:
<a href=#Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+',receiverId='+obj[i].senderId+ })>
But it shows error, I can't use javascript variable obj[i].senderId with c# code #Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+'...
How can I fix this, or is there any other solution to add link or onClick on Table cell and pass data with it ?
David is right, but a simplified way for easy understanding.
var href = #Url.Action("SingleSentShow","Home", new { msgId ="__msgID__" ,receiverId="__receiverID__" });
href = href.replace("__mgsID__",obj[i].senderId).replace("__receiverID__",obj[i].senderId);
$tbl.append(' <tr><td> <a href="' + href + '">' + '... the rest of your line');
Both will work fine.
Update: As per Comment.
Move the value of href to data-href and set href to # and add a new class for script to work. And when the link is clicked we can swap the values.
$tbl.append(' <tr><td> <a href=# class=Test data-href="' + href + '">' + '... the rest of your line');
And add the below script.
$(document).on('click', '.Test', function () {
$(this).attr('href',$(this).attr('data-href'));
});
You can't mix server-side code and client-side code like that.
One option might be to put the base action URL in a JavaScript variable, and then append your query string parameters to it in JavaScript code. Something like this:
var singleSentShowURL = '#Url.Action("SingleSentShow","Home")';
This would result in something like this client-side:
var singleSentShowURL = '/Home/SingleSentShow';
Then in your loop you could use that variable to manually build the URL. Something like this:
$tbl.append(' <tr><td> <a href="' + singleSentShow + "?msgId=" + obj[i].senderId + "&receiverId=" + obj[i].senderId + '">' + '... the rest of your line');
You might split it into multiple lines for readability:
var href = singleSentShow + "?msgId=" + obj[i].senderId + "&receiverId=" + obj[i].senderId;
$tbl.append(' <tr><td> <a href="' + href + '">' + '... the rest of your line');
I'm having trouble outputting a JSON to a HTML table within my tab (for part of a javascript/jQuery evening course assignment).
Please could someone have a look, and advise what sort of amendments I would have to make to output in a table format?
I get the success alert, but the table doesn't populate.
Thanks.
// Tabs
$(function() {
$( "#tabs" ).tabs();
});
// Spanish
$(document).ready(function(){
$.ajax({
url: "http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/spanish.php", // path to file
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsonpCallback',
success: function () {
alert('success');
}
});
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
var row = $("<tr />")
$("#table").append(row);
row.append($("<td>" + rowData.course + "</td>"));
row.append($("<td>" + rowData.name + "</td>"));
row.append($("<td>" + rowData.price + "</td>"));
}
And the HTML:
<div id="tabs">
<ol start="50">
<li>
Italian
</li>
<li>
Spanish
</li>
</ol>
<p id="tab-1"></p>
<p id="tab-2">
<table id='table'>
<thead>
<tr>
<th>Course</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
</p>
<p id="tab-3"></p>
</div>
The main issue with your code was that you didn't call any function after the AJAX request completed successfully. You needed at least call drawTable() to populate the data.
However there are several improvements you can make to your code. Firstly, remove jsonp: 'callback'. It's the default value, and also redundant as you're supplying jsonpCallback. You can also then change jsonpCallback to 'drawTable'. This negates the need for the success handler function and means all the request data will be directly provided to your drawTable() function. Lastly, rather than creating DOM elements in memory and appending in each iteration of the loop it's much quicker to build a single string with all the table's HTML and append it once when finalised.
With all that said, try this:
$(document).ready(function() {
$.ajax({
url: "http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/spanish.php",
dataType: 'jsonp',
jsonpCallback: 'drawTable'
});
});
function drawTable(data) {
var html = '';
for (var i = 0; i < data.length; i++) {
html += '<tr><td>' + data[i].course + '</td><td>' + data[i].name + '</td><td>' + data[i].price + '</td></tr>';
}
$('#table tbody').append(html);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
<thead>
<tr>
<th>Course</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
Note that I reduced the HTML shown here to only the relevant parts.
// Tabs
$(function() {
$( "#tabs" ).tabs();
});
// Spanish
$(document).ready(function(){
$.ajax({
url: "http://learn.cf.ac.uk/ webstudent/sem5tl/javascript/assignments/spanish.php",
// path to file
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsonpCallback',
// The var you put on this func will store data
success: function (data) {
alert('success');
// Call the function passing the data recieved
drawTable(data);
}
});
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
var row = $("<tr />")
$("#table").append(row);
row.append($("<td>" + rowData.course + "</td>"));
row.append($("<td>" + rowData.name + "</td>"));
row.append($("<td>" + rowData.price + "</td>"));
}
As the title says, Im calling a Json and It's "working", but i'm getting an error from jquery. "cannot read property "length" of undefined". I dont know what it could be.
here is my html, js and json
http://jsfiddle.net/vitorboccio/7LUCa/
<div class="wrapper">
<div class="profile">
<table id="userdata" border="2">
<thead>
<th>Name</th>
<th>E-mail</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
JS:
$.ajax({
get: 'people.json',
success: function (data) {
alert('it works');
$.each(data.table, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.name + "</td>" +
"<td>" + f.email + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
},
error: function() {alert('it doesnt work')},
datatype: 'jsonp'
});
update:
You can't use .each on something that doesn't have a length. In your fiddle, at the moment, you are getting back
Object {error: "Please use POST request"}
for data. Which obviously you can't iterate over the .table property, as it has no length because it is undefined.
Edit:
This works on your actual site:
$.getJSON('http://vitorboccio.com/projects/test/people.json',
function (data) {
console.log(data.data);
$.each(data.data.table, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.name + "</td>" +
"<td>" + f.email + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
}
);
You can't use each on the data like that. That is were you are getting the error.
I have this ajax code below which is returning a List of products of a specific category ID which is passed in the data :
THe list is then looped through and displayed one by one.
The code below works in both chrome and firefox, but in IE9 it will only display the first product.
function getProducts(catID) {
$('#ChangeContent').html('');
$.ajax({
type: "POST",
url: "Mainpage.aspx/GetProducts",
data: "{categoryID:" + catID + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
allProducts = msg.d;
$.each(msg.d, function (i, value) {
var desc = "";
if (value.description.length > 70) {
desc = value.description.substring(0, 67);
desc += " ...";
}
else {
desc = value.description;
}
var htmll = "<div class='OutsideDiv' onclick='displayProduct(" + value.productID + " )'><table class='DivBorder'> <tr > <td class='imageBox'><img alt='' src='" + value.image + "' /></td> </tr> <tr > <td class='title'>" + value.name + "</td>";
htmll += " </tr> <tr> <td class='desc'>" + desc + " </td> </tr> <tr> <td class='price'>€" + value.price + "</td> </tr> </table></div>";
htmll += " <script type='text/javascript'>$('.DivBorder').mouseover(function (){$(this).css('border-color', '#cb510a');$(this).css('background-color', '#e2e2e2');});$('.DivBorder').mouseout(function (){$(this).css('border-color', '#bdbdbd');$(this).css('background-color', '#f6f6f6');});";
$('#ChangeContent').append(htmll);
});
},
error: function (error) {
alert("Errorrrrrr");
}
});
};
I did try searching for this problem, but couldnt find this same problem which includes .each inside .ajax
Any help would be much appreciated.
...maybe because the element you're appending has no closing
. Why are you appending a script like that anyway? You're
going to bind the same events to the same .DivBorder elements over and
over again.
As cookie monster said