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
Related
I would like to have the database table id on each row as checkbox value of a dynamic html table
I am using ajax to fetch data from mysql database and create a new variable as html text to append on tbody of table
Code of HTML
<div class="col-sm-6" id="ftbl">
<label for="urbandata">View urban data</label>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Check</th>
<th>ID</th>
<th>Type</th>
<th>Master</th>
<th>Slave</th>
<th>Orbit</th>
<th>Mode</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Code of JS
$.ajax({
url: "fetchurban.php",
method: "POST",
data:{id:id},
dataType: "JSON",
success: function(data){
if (data){
var trHTML = '';
$.each(data, function (i, item) {
trHTML +='<tr><td><input type="checkbox" id="checkview" onclick="QuickView()" name="'+ item.TblID +'"></td><td>' + item.Type + '</td><td>' + item.Master + '</td><td>' + item.Slave + '</td><td>' + item.Orbit + '</td><td>' + item.Mode + '</td><td><span class="glyphicon glyphicon-download"> </span><span class="glyphicon glyphicon-cloud-download"></span></td></tr>' ;
});
$('#ftbl tbody').append(trHTML);
}
}
})
})
If the user select the checkbox I would like to have the id of database table.
Now with this code I have the same id to all rows of table
You could set the identifier as a data- element of the input:
function QuickView(element) {
var rowId = $(element).data('id');
// here comes the rest of your code.
}
$.ajax({
url: "fetchurban.php",
method: "POST",
data:{id:id},
dataType: "JSON",
success: function(data){
if (data){
var trHTML = '';
$.each(data, function (i, item) {
trHTML +='<tr><td><input type="checkbox" data-id="'+ item.TblID +'" onclick="QuickView(this)"></td><td>' + item.Type + '</td><td>' + item.Master + '</td><td>' + item.Slave + '</td><td>' + item.Orbit + '</td><td>' + item.Mode + '</td><td><span class="glyphicon glyphicon-download"> </span><span class="glyphicon glyphicon-cloud-download"></span></td></tr>' ;
});
$('#ftbl tbody').append(trHTML);
}
}
})
})
Here's a demo of the above.
EDIT:
I removed the initial sentence regarding not being allowed to use an integer for the ID attribute as it is no longer valid as Quentin pointed out in the comments. It's sometimes hard to forget what you once learned.
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
<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.
Guys I have a html table in my ASP.net MVC home view. Now the table is being filled initially through the data present in model. Now upon clicking certain buttons on the homepage, I want to update the data present in the table i.e. clear the data present in the table and update it with the one from ajax call.
This is my table from view :
<article class="scrlable">
<table>
<tr>
<td>#</td>
<td>Name</td>
<td>Status</td>
<td>Since</td>
</tr>
#{
int srno = 1;
foreach (var pendingResponseModel in Model.hrPendingResponseList)
{
<tr>
<td>#srno</td>
<td>#pendingResponseModel.CandidateName</td>
<td>#pendingResponseModel.CandidateLifeCycleStatusName</td>
#if (pendingResponseModel.DayDifference == "1")
{
<td>#(pendingResponseModel.DayDifference) day</td>
}
else
{
<td>#(pendingResponseModel.DayDifference) days</td>
}
</tr>
srno++;
}
}
</table>
</article>
And this is my ajax call :
function GetStatusWise(control, departCode) {
$.ajax(
{
type: "GET",
url: "...URL..." + departCode,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (data) {
$.each(data.data, function (index, value) {
// UPDATE TABLE HERE...
});
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
}
}
);
}
The data returned from ajax call is in JSON. It has Name, Status and Since elements. They can be viewed by using value.CandidateName, value.Status etc
Now I want to update the values of above table with the values I am getting through AJAX call. How would I go about doing that? Is it possible to replace the whole article ?
Note : I am getting multiple values through ajax call so that is why I put a loop on the function.
I have solved my problem by the following code
function GetStatusWise(control, departCode) {
$.ajax(
{
type: "GET",
url: WebApiURL + ".....URL...." + departCode,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (data) {
var srno = 1;
$('#tblPendingHrResponse').find($('.trTblPendingHrResponse')).remove();
$.each(data.data, function (index, value) {
random(value, srno);
srno++;
});
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
}
}
);
}
.
function random(values, srno) {
var daydifference = values.DayDifference == 1 ? '<td>' + values.DayDifference + ' day </td>' : '<td>' + values.DayDifference + ' days </td>';
var tr = '<tr class="trTblPendingHrResponse">' +
'<td>' + srno + '</td>' +
'<td>' + values.CandidateName + '</td>' +
'<td>' + values.CandidateLifeCycleStatusName + '</td>' +
daydifference + '</tr>' + srno++;
$('#tblPendingHrResponse').append(tr);
}
You can use jQuery append.
success: function (data) {
$.each(data.data, function (index, value) {
$("table").html("Your HTML to updated");
});
},
Have your controller method return a partial which contains your table or article.
[HttpPost]
public virtual ActionResult GetTable(ArticleViewModel viewModel)
{
// do stuff
return PartialView("_ArticleTable", viewModel);
}
Then update the table or article in jQuery:
ou can use jQuery append.
success: function (data) {
$("table").html(data);
},
Currently I have a site that when a button is clicked it returns the lastest movies and tv shows that are airing.
Right now the api I am using returns a whole page of values up to 20 results from my research of the api there is no limit function all i want to do is have 5 of those results be returned
I have been told that the slice() function may work.
Also any other why that you think my work would be nice aswell if you can figure out another way
I have included a jsfiddle but removed my api key
jsfiddle - http://jsfiddle.net/xvTe9/
Here's all my code just without my api key
<html>
<head>
<title>Sample Seach</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'movie/now_playing',
input,
movieName,
key = '?api_key=API KEY HERE';
$('#search').click(function() {
var input = $('#titlesearch').val(),
movieName = encodeURI(input);
$.ajax({
url: url + mode + key + '&query='+movieName' ,
dataType: 'jsonp',
success: function(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td class="results-img"><img src="http://image.tmdb.org/t/p/w500' + value.poster_path +'" alt="" width="130" height="150"></td><td class="results-title"><h4>' + value.original_title + '</h4></td></tr>';
});
$('#searchresult').html(table);
}
});
});
});
// tv show search
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'tv/on_the_air',
input,
tvName,
key = '?api_key=API KEY HERE';
$('#search').click(function() {
var input = $('#titlesearch').val(),
tvName = encodeURI(input);
$.ajax({
url: url + mode + key + '&query='+tvName,
dataType: 'jsonp',
success: function(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td class="results-img"><img src="http://image.tmdb.org/t/p/w500' + value.poster_path +'" alt="" width="130" height="150"></td><td class="results-title"><h4>' + value.original_name + '</h4></td></tr>';
});
$('#searchresulttv').html(table);
}
});
});
});
</script>
<script text="text/javascript">
// When the more button is click this runs a search using the title of the movie it is next to
$('.results-img').live('click', '.results-img', function() {
getImdbInfo( $(this).closest('tr').find('.results-title').text());
});
//The function below takes the entered title and searchs imdb for a match then it displays as followed
function getImdbInfo(Title) {
var url = "http://www.omdbapi.com/?t=" + Title + "&plot=full";
$.ajax({
url: url,
cache: false,
dataType: "jsonp",
success: function(data) {
var str = "";
str += "<h2><center>Title :" +data.Title+ "</center></h2>";
str += "<center><img src='" + data.Poster + "' /></center><br />";
str += "<h4><center>Plot :</center></h4><p>" +data.Plot+ "</p>";
$("#chosenresult").html(str);
},
error: function (request, status, error) { alert(status + ", " + error); }
});
}
</script>
</head>
<body>
<center>
<h1>Movie and Tv Search</h1>
<button id="search">Search</button>
</center>
<div id="chosenresult"></div>
<div id="searchresult" style="float:left;"></div>
<div id="searchresulttv" style="float:right;"></div>
</body>
</html>
Screenshot of results that i want just the 5
Use slice to first reduce the array which must be iterated in the callback function of ajax.
var results = data.results.slice(0,5);
$.each(results, function( key, value ) {
table += '<tr><td class="results-img"><img src="http://image.tmdb.org/t/p/w500' + value.poster_path +'" alt="" width="130" height="150"></td><td class="results-title"><h4>' + value.original_name + '</h4></td></tr>';
});
Assuming you've stored the results in an array,
arr.slice(0,5)
will return the first five elements.
Using your current $.each you could do:
$.each(data.results, function (index, value) {
table += '<tr>
<td class="results-img">
<img src="http://image.tmdb.org/t/p/w500' + value.poster_path + '" alt="" width="130" height="150">
</td>
<td class="results-title">
<h4>' + value.original_name + '</h4>
</td>
</tr>';
return (index !== 6);
});