I'm trying to build search filter with .keyup function. When i write one char in search textbox its works fine, but when i try to delete char, or add one more then it crushes and throws error "Internal server error". What im i doing wrong? I tried to parse given/taken data to json/html and it didn't help. Here is my script code:
<script>
$(document).ready(function () {
$("#Search").keyup(function () {
var searchby = $("#searchby").val();
var searchVal = $("#Search").val();
var setData = $("#dataSearching");
var catId = $("#categoryID").val();
setData.html("");
$.ajax({
async: true,
type: "get",
url: "/Default/GetSearchingData?categoryID=" + catId + "&searchBy=" + searchby + "&searchValue=" + searchVal,
dataType: "json",
contentType: "html",
success: function (result) {
if (result.length == 0) {
setData.append('<tr><td colspan="7" style="color: red;">Nie odnaleziono szukanej frazy</td></tr>');
} else {
for (var i in result) {
var Data = "<tr>" +
"<td>" + result[i].AlbumID + "</td>" +
"<td>" + result[i].AlbumName + "</td>" +
"<td>" + result[i].BandName + "</td>" +
"<td>" + result[i].AlbumCover + "</td>" +
"<td>" + result[i].Year + "</td>" +
"<td>" + parseFloat(result[i].Price) + "</td>" +
"<td>" +
"<button id=" + result[i].AlbumID + ' type="button" class="btn btn-primary myModals" data-toggle="modal" data-target="#exampleModal-' + result[i].AlbumID + '">' +
"Zobacz </button>" +
'<div class="modal fade" id="exampleModal-' + result[i].AlbumID + '" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel-' + result[i].AlbumID + '" aria-hidden="true">' +
'<div class="modal-dialog" role="document">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<h5 class="modal-title" id="exampleModalLabel-' + result[i].AlbumID + '">' + result[i].AlbumName + ", " + result[i].Year + ", " + result[i].BandName + "</h5>" +
'<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
'<span aria-hidden="true">×</span> </button> </div>' +
'<div id="parent-' + result[i].AlbumID + '" class="modal-body">' +
"</div>" +
'<div class="modal-footer">' +
'<button id="closeModal" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>' +
"</div>" +
"</div>" +
"</div>" +
"</div>" +
"</td>" +
"<td>"+
'<input id="categoryID" class="hidden" type="submit" value="' + result[i].CategoryID + "/>" +
"</td>"+
"</tr>";
setData.append(Data);
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
//alert(xhr.responseText);
alert("Error!!: " + thrownError);
},
xhr: function () {
var xhr = new window.XMLHttpRequest();
return xhr;
}
});
});
});
</script>
And here is my action for searching in DefaultController:
public JsonResult GetSearchingData(int categoryID, string searchBy, string searchValue)
{
var albumsWithCategory = (from album in Album.GetAlbumList()
join category in Category.GetCategoriesList()
on album.CategoryID equals category.CategoryID
where (categoryID == album.CategoryID)
select album).ToList();
List<Album> newAlbumList;
if (searchBy == "AlbumName")
{
newAlbumList = albumsWithCategory.Where(x => x.AlbumName.StartsWith(searchValue, StringComparison.InvariantCultureIgnoreCase) || searchValue == null).ToList();
return Json(newAlbumList, JsonRequestBehavior.AllowGet);
}
else
{
newAlbumList = albumsWithCategory.Where(x => x.BandName.StartsWith(searchValue, StringComparison.InvariantCultureIgnoreCase) || searchValue == null).ToList();
return Json(newAlbumList, JsonRequestBehavior.AllowGet);
}
}
Here is my data model (if it would be useful to find issue):
public class BigViewModel
{
public IEnumerable<Album> Albums { get; set; }
public IEnumerable<Category> Categories { get; set; }
public IEnumerable<Order> Orders { get; set; }
public IEnumerable<Song> Songs { get; set; }
}
Image with error:
enter image description here
I believe that error is due formatting in query parameters. Instead of keyup i would try to use input event and instead of building query url i would use data property.
$("#Search").on("input", function () {
//...
$.ajax({
url: "/Default/GetSearchingData",
type: "get",
dataType: "json",
data: {
categoryID: Number(catId),
searchBy: searchBy,
searchValue: searchVal
},
success: function(result) {
if (result.length > 0)
{
var rows = response.map(item => {
return `
<tr>
<td>${item.AlbumID}</td>
<td>${item.AlbumName}</td>
<td>${item.BandName}</td>
<td>${item.AlbumCover}</td>
<td>...</td>
</tr>
`;
}).join("");
setData.html( `<table>${rows}</table>` );
} else {
setData.html( "<table><tr>Not found</tr></table>" );
}
},
error: function(xhr) { }
});
});
I am a final year student and am creating a food log web application for my major project. I have created a search function that allows me to search and display external API results, but now I wish to display them in a table, can anyone help please?
I would prefer if it would be a table that can be filtered, eg, the columns ordered ascending/descending?
Thanks
function get foodItem(userInput) {
var storedSearchItem;
$('.resultContainer').html('');
$.ajax({
type: 'GET',
async: false,
url: 'https://api.nutritionix.com/v1_1/search/'+userInput+'?'+
'fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=325062a4&appKey=bf1a30b2066602dc6f33db888cd53bd3',
success: function(d) {
storedSearchItem = d.hits;
}
});
storedSearchItem.map(function(item) {
var x = item.fields
$('.resultContainer').append(
'<div class="itemBar">'+
'<h2>' + x.item_name + '<h2>' +
'<h3>Calories: ' + x.nf_calories + '<h3>' +
'<h3>Serving Size: ' + x.nf_serving_size_qty + ' ' + x.nf_serving_size_unit +'<h3>' +
'<h3>Total Fat: ' + x.nf_total_fat + '<h3>' +
'</div>'
);
});
}//ends get result function
function searchValue() {
var formVal = document.getElementById('itemSearch').value; //value from search bar
getFoodItem(formVal);
}
$('#searchForm').submit(function(e) {
e.preventDefault();
});`
You need to append your table in the success function
your code will look like something like this
success: function(d) {
storedSearchItem = d.hits;
storedSearchItem.map(function(item) {
var x = item.fields
$('.resultContainer').append(
'<div class="itemBar">'+
'<h2>' + x.item_name + '<h2>' +
'<h3>Calories: ' + x.nf_calories + '<h3>' +
'<h3>Serving Size: ' + x.nf_serving_size_qty + ' ' + x.nf_serving_size_unit +'<h3>' +
'<h3>Total Fat: ' + x.nf_total_fat + '<h3>' +
'</div>'
);
});
}
I have nested callabcks but resulted output is not ordered correctly. My ajax results are in ascending orders of id but html generated is random. can someone help me out pls?
var formatedhtml = '';
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/read',
dataType: 'json',
success: function(data) {
$.each(data, function(key, value) {
console.log(value);
getdetails(value['id'], function(output) {
formatedhtml = formatedhtml +
'<div class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
' <div class="row">' +
' <div class="orderno">' + value['id'] + '</div>' +
'<div class="tableno">' + value['tableno'] + '</div>' +
'<div class="ordertype">' + value['type'] + '</div>' +
'<div class="timestamp">' + value['created'] + '</div>' +
' </div>' +
'<hr>';
$.each(JSON.parse(output['items']), function(k, val) {
formatedhtml = formatedhtml + '<div class="row">' +
'<div class="quantity">' + val[3] + '</div>' +
'<div class="item">' + '</div>' +
'</div>';
});
formatedhtml = formatedhtml +
'<div class="row">' +
'<div class="notes">' + value['id'] + '</div>' +
'</div>' +
'</div>';
$("#orderlist").html(formatedhtml);
console.log(output);
});
});
}
});
edit:
Here is getdetails function. its an ajax request.
function getdetails(id, callback) {
var result;
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
data: {
id: id,
},
success: function(data) {
callback(data[0]);
}
});
};
There are a lot of ways to achieve this, one is to use a promise and sort by id when all requests are done. Another you could create the template and append the details on callback as each detail request has an id you can define in your template a class like 'id-'+value['id'] and use jquery selector and append detail template.
Another solution would be to create a function loop that calls itself untill orderCount == orderLoaded.
Job is done synchronously (takes more time)
//Mock ajax function
$.ajax = function (param) {
if(param.url.indexOf('readdetails') != -1){
param.success(itemsData);
} else {
param.success(ordersData);
}
};
//Mock data
var ordersData = [
{ id : 1, tableno : 'xyz', type: 'invoice', created: '01/01/2001' },
{ id : 2, tableno : 'xyz', type: 'invoice', created: '01/01/2001' },
{ id : 3, tableno : 'xyz', type: 'invoice', created: '01/01/2001' }
];
var itemsData = [
{ id : 1, orderid: 1, quantity: 5 },
{ id : 2, orderid: 1, quantity: 2 },
{ id : 3, orderid: 1, quantity: 1 }
];
// Globals
var formatedhtml = [];
var orders = [];
var lastOrderLoaded = 0;
var BASE_URL = 'localhost/';
function tpl(order, items) {
var html = '<tr class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
' <td class="orderno">' + order['id'] + '</td>' +
'<td class="tableno">' + order['tableno'] + '</td>' +
'<td class="ordertype">' + order['type'] + '</td>' +
'<td class="timestamp">' + order['created'] + '</td>' +
' </tr>';
$.each(items, function(key, item) {
html += '<tr class="row">' +
'<td class="item">item: ' + item.id + '</td>' +
'<td class="quantity">quantity: ' + item.quantity + '</td>' +
'</tr>';
});
html +=
'<tr class="row">' +
'<td class="notes"> notes </td>' +
'<td class="notes"> order id ' + order['id'] + '</td>' +
'</tr>' +
'</tr>';
formatedhtml.push({ id: order.id, html : html });
}
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/read',
dataType: 'json',
success: function(data) {
lastOrderLoaded = 0;
orders = data;
getdetails(orders[0]);
}
});
function getdetails(order) {
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
data: {
id: order.id,
},
success: function(data) {
tpl(order, data);
if(lastOrderLoaded < orders.length - 1){
lastOrderLoaded++;
getdetails(orders[lastOrderLoaded]);
} else {
formatedhtml.forEach(function(element){
$("#orderlist").append(element.html);
}); // end each
}
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="orderlist" border="1">
<tr><th>id</th><th>no</th><th>type</th><th>date</th></tr>
</table>
Promise Solution:
Job is done asynchronously (might take less time also bombards the server with many requests at once)
var formatedhtml = [];
function tpl(order, items) {
var html = '<div class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
' <div class="row">' +
' <div class="orderno">' + order['id'] + '</div>' +
'<div class="tableno">' + order['tableno'] + '</div>' +
'<div class="ordertype">' + order['type'] + '</div>' +
'<div class="timestamp">' + order['created'] + '</div>' +
' </div>' +
'<hr>';
$.each(JSON.parse(items['items']), function(key, item) {
var html += '<div class="row">' +
'<div class="quantity">' + item[3] + '</div>' +
'<div class="item">' + '</div>' +
'</div>';
});
html +=
'<div class="row">' +
'<div class="notes">' + order['id'] + '</div>' +
'</div>' +
'</div>';
formatedhtml.push({ id: order.id, html : html });
}
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/read',
dataType: 'json',
success: function(data) {
var syncLoad = [];
$.each(data, function(key, value) {
syncLoad.push(getdetails(value, tpl));
});
$.when.apply($, syncLoad).done(function() {
formatedhtml.sort(function(a, b){
return a.id - b.id;
});
formatedhtml.forEach(function(element){
$("#orderlist").append(element.html);
});
});
}
});
function getdetails(order, callback) {
return $.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
data: {
id: order.id,
},
success: function(data) {
callback(order, data[0]);
}
});
};
Use async:false in your getDetails() ajax call.
function getdetails(id, callback) {
var result;
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
async: false,
data: {
id: id,
},
success: function (data) {
callback(data[0]);
}
});
How I can load dynamicly (like $.ajax or getjson) in selectize options list?
Searched thru the forum, looks like nobody did it this way for some reason (?)
Thanks.
The load(fn) method is probably what you are looking for.
Loads options by invoking the the provided function. The function
should accept one argument (callback) and invoke the callback with the
results once they are available.
Here is the first Remote Source example:
$('#select-repo').selectize({
valueField: 'url',
labelField: 'name',
searchField: 'name',
create: false,
render: {
option: function(item, escape) {
return '<div>' +
'<span class="title">' +
'<span class="name"><i class="icon ' + (item.fork ? 'fork' : 'source') + '"></i>' + escape(item.name) + '</span>' +
'<span class="by">' + escape(item.username) + '</span>' +
'</span>' +
'<span class="description">' + escape(item.description) + '</span>' +
'<ul class="meta">' +
(item.language ? '<li class="language">' + escape(item.language) + '</li>' : '') +
'<li class="watchers"><span>' + escape(item.watchers) + '</span> watchers</li>' +
'<li class="forks"><span>' + escape(item.forks) + '</span> forks</li>' +
'</ul>' +
'</div>';
}
},
score: function(search) {
var score = this.getScoreFunction(search);
return function(item) {
return score(item) * (1 + Math.min(item.watchers / 100, 1));
};
},
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: 'https://api.github.com/legacy/repos/search/' + encodeURIComponent(query),
type: 'GET',
error: function() {
callback();
},
success: function(res) {
callback(res.repositories.slice(0, 10));
}
});
}
});
have big problem.
have jquery multiselect plugin from here
$.ajax({
url: 'my url',
type: 'post',
data: {'data': data1, 'data2': 'data2'},
dataType: 'json',
success: function(data){
if(data.length >= 1){
$('#selector').find('option').remove();
$.each(data, function(key, value) {
if ($("#selector option[value='" + value.email + "']").length == 0){
$("#selector").append('<option value="'+ value.email +'" data-id="'+value.id+'" data-name="' + value.name + '" data-surname="' + value.surname + '">'+ value.name + ' ' + value.surname + ' ' + ' (' + value.email + ') sent (' + value.sent + ')' +'</option>').multiselect("destroy").multiselect( { sortable : false } );
}
});
}else{
$('#selector').find('option').remove();
$('#selector').append('').multiselect("destroy").multiselect( { sortable : false } );
}
}
});
and after change (call this function, whitch selecting cantacts from other list) my selected values disapears