if statement in ajax append block - javascript

I have an ajax block that is processing a json response from an external API. I have a field for the object called status and depending on the status, I would like to display the corresponding tooltip. Currently, I am trying to do this with an if statement but but I am getting an error.
The error is:
Uncaught SyntaxError: Unexpected token if
Ajax block
<script type="text/javascript">
$.ajax({
url: "pull_overview",
dataType: "json",
cache: false,
success: function(data){
if ( data == null ) {
$('#ajax-loader').hide()
$('#overviewlist tbody').append("<tr><td colspan='100'><h3><center>You have no recent transactions.</center></h3></td></tr>");
}
else {
$('#ajax-loader').hide()
$.each(data, function(index, element) {
$('#overviewlist tbody').append("<tr><td>" + element.name + "</td><td>"
+ element.time + "</td><td>"
+ element.type + "</td><td>"
+ element.change_in_balance + "</td><td>"
+ element.method + "</td><td>"
+
if (element.status == 'New Transaction') {
"<td><button type='button' class='tooltips btn-u btn-u-xs btn-u-purple' data-toggle='tooltip' data-placement='right' title='Your transaction is currently being processed'>Pending</button></td></tr>"
}
});
}
}
});
</script>

Like the error says, you have a SyntaxError. The fixed code is:
$.ajax({
url: "pull_overview",
dataType: "json",
cache: false,
success: function (data) {
if (data == null) {
$('#ajax-loader').hide()
$('#overviewlist tbody').append("<tr><td colspan='100'><h3><center>You have no recent transactions.</center></h3></td></tr>");
} else {
$('#ajax-loader').hide()
$.each(data, function (index, element) {
$('#overviewlist tbody').append("<tr><td>" + element.name + "</td><td>" + element.time + "</td><td>" + element.type + "</td><td>" + element.change_in_balance + "</td><td>" + element.method + "</td><td>" + element.status == 'New Transaction' ?
"<td><button type='button' class='tooltips btn-u btn-u-xs btn-u-purple' data-toggle='tooltip' data-placement='right' title='Your transaction is currently being processed'>Pending</button></td></tr>" : "");
});
}
}
});
What is changed?
some missing parentheses
you cannot have if statement inside of a string (e.g. "foo" + if(something) "bar"). Use ternary operator instead: "foo" + something ? "bar" : ""
Useful resources:
Operator precedence with Javascript Ternary operator
How to find Javascript syntax errors
How do you use the ? : (conditional) operator in JavaScript?

You cannot put an if statement in the middle of a string concatination in your last append call. do this instead
content = "<tr><td>" + element.name + "</td><td>"
+ element.time + "</td><td>"
+ element.type + "</td><td>"
+ element.change_in_balance + "</td><td>"
+ element.method + "</td><td>";
if (element.status == 'New Transaction')
content += "<td><button type='button' class='tooltips btn-u btn-u-xs btn-u-purple' data-toggle='tooltip' data-placement='right' title='Your transaction is currently being processed'>Pending</button></td></tr>";
$('#overviewlist tbody').append(content);

Related

Jquery keyup function doesn't work (using ajax, asp.net mvc)

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) { }
});
});

Loop through ajax values

I have some values that are returned to ajax from backend.
The problem in this code is that when I do console.log(myRows) the values in cells are undefined.
$(document).on('click', ".myButton", function () {
$.ajax({
type: "POST",
url: "Administration.aspx/GetMyCollection",
data: JSON.stringify({ 'Parameter': Parameter }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d.length > 0) {
var myRows = "";
$.each(data, function (i, values) {
values.ObjectID;
values.ObjectName;
values.ObjectValue;
values.Object;
console.log(values);
myRows += "<tr><td>" + values[1].ID + "</td><td>" + values[1].ObjectName + "</td><td>" + values[1].ObjectValue + "</td><td>" + values[1].Object + "</td></tr>";
console.log(myRows);
});
}
console.log("Saved!");
},
error: function () {
console.log("Not Saved!");
}
});
});
But when I change the code and add values[1], the values are displayed correctly.
myRows += "<tr><td>" + values[1].ID + "</td><td>" + values[1].ObjectName + "</td><td>" + values[1].ObjectValue + "</td><td>" + values[1].Object + "</td></tr>";
I need help to change the code so it will loop through all 9 (from 1 to 9) values and places the results in myRows cells so all the values can be displayed.
Json code:
d […]
0 {…}
ObjectID 1
ObjectName Vegas
ObjectValue 234
Object Arizona
1 {…}
ObjectID 2
ObjectName Chicago
ObjectValue 211
Object Montana
2 {…}
ObjectID 3
ObjectName Livepool
ObjectValue 123
Object London
...
Thanks in advance !
You're not looping over the right item - $.each(data should be $.each(data.d since d contains the array. Then each time the loop runs values will represent one individual object from the array, and you can removed the [1] from your code.
Also values.ID should be values.ObjectID I think, based on the data sample you give in the question - there's no "ID" property on any of your objects.
Lastly I took the liberty of moving console.log(myRows); to after the end of the loop - then you'll just see the whole string once, not get it repeated each time with an extra bit added, which might be confusing.
$.each(data.d, function (i, values) {
console.log(JSON.stringify(values));
myRows += "<tr><td>" + values.ObjectID + "</td><td>" + values.ObjectName + "</td><td>" + values.ObjectValue + "</td><td>" + values.Object + "</td></tr>";
});
console.log(myRows);
As you are iterating over the array, values will hold the object. Hence, you do not need to use values[i] or values[1]. Additionally, it seems you have data in data.d and hence, should iterate on that.
Hence, you can update your code to following
$.each(data.d, function (i, values) {
myRows += "<tr><td>" + values.ObjectID + "</td><td>" + values.ObjectName + "</td><td>" + values.ObjectValue + "</td><td>" + values.Object + "</td></tr>";
});
console.log(myRows);
Note, add your log after the each block to see complete set of rows.
use function like this to make tr string
var myRows = "";
data.forEach(function (values,key) {
myRows += "<tr><td>" + values.ID + "</td><td>" + values.ObjectName + "</td><td>" + values.ObjectValue + "</td><td>" + values[1].Object + "</td></tr>";
console.log(myRows);
});

How to set dynamic where clause with JSStore while working with IndexedDB?

I am working on IndexedDB using JsStore wrapper. Everything works fine in the code when I set the column name directly in the Where block but if I make it dynamic as shown in the following code then the code doesn't work.
var searchValueType = $('input:radio[name=searchValueType]:checked').val();
var searchValue = $("#searchValue").val();
var column1 = 'Name';
var whereClause = column1+':'+searchValue;
alert ("where clause >> "+whereClause);
DbConnection.select({
From: "Student",
Where: {
whereClause
},
},
function (students) {
var HtmlString = "";
students.forEach(function (student) {
HtmlString += "<tr ItemId=" + student.Id + "><td>" +
student.Name + "</td><td>" +
student.Gender + "</td><td>" +
student.Country + "</td><td>" +
student.City + "</td><td>" +
"<a href='#' class='edit'>Edit</a></td>" +
"<td><a href='#' class='delete''>Delete</a></td>";
}, function (error) {
console.log(error);
})
$('#tblGrid tbody').html(HtmlString);
});
Issue is clearly visible in code, Where expects an object but you are passing a string within curly bracket.
You need to create the object in a variable and assign it to Where option of jsstore.
Please check the below code -
var searchValueType = $('input:radio[name=searchValueType]:checked').val();
var searchValue = $("#searchValue").val();
//var column1 = 'Name';
//var whereClause = column1+':'+searchValue;
//alert ("where clause >> "+whereClause);
// Where clause is now an object
var whereClause = {
Name: searchValue
}
DbConnection.select({
From: "Student",
Where: whereClause,
}, function(students) {
var HtmlString = "";
students.forEach(function(student) {
HtmlString += "<tr ItemId=" + student.Id + "><td>" +
student.Name + "</td><td>" +
student.Gender + "</td><td>" +
student.Country + "</td><td>" +
student.City + "</td><td>" +
"<a href='#' class='edit'>Edit</a></td>" +
"<td><a href='#' class='delete''>Delete</a></td>";
}, function(error) {
console.log(error);
})
$('#tblGrid tbody').html(HtmlString);
});

Sort table column by date in ajax

I have a table that's displayed on button click using ajax. Here's a code snippet:
myBtn.on("click", function() {
displayTable();
});
function displayTable(){
$.ajax({
url:'url to a function in controller',
type: "GET",
//data: {val : val},
dataType: 'json',
success: function(data){
// some codes here
$.each(data.documents, function(key, value){
$("#myTable")
.append(
"<tr class='" + rowClass + "'><td class='text-center'>" +
value.title +
"</td><td class='text-center'>" +
value.time1.replace(/-/g, "/") +
"</td><td class='text-center'>" +
value.time2.replace(/-/g, "/") +
"</td></tr>"
);
});
}
});
}
After this, a table is displayed but it is not sorted by date (value.time2). I tried this but not working:
$("#myTable thead tr").find('th').eq(3).sort(function(a,b){
return new Date($(a).value.time2) > new Date($(b).value.time2);
});
Do you have any idea how to do this? How do I sort it by date (value.time2)?
The best way would be to request the server to sort the values for you. However, if you need to perform this on client side, you can simply sort data.documents before adding it to the page. For example:
data.documents = data.documents.map(function(item) {
// Fix display
item.time1 = item.time1.replace(/-/g, "/");
item.time2 = item.time2.replace(/-/g, "/");
return item;
});
data.documents.sort(function(a, b) {
// Custom sorting function
return new Date(a.time2) > new Date(b.time2);
});
$.each(data.documents, function(key, value){
$("#myTable")
.append(
"<tr class='" + rowClass + "'><td class='text-center'>" +
value.title +
"</td><td class='text-center'>" +
value.time1 +
"</td><td class='text-center'>" +
value.time2 +
"</td></tr>"
);
});

How to append row data to table one by one?

Here is my html code
<tr id="tHead">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
Here is my js code
$(document).ready(function(){
$.ajax({
url: "data.json",
dataType: "json",
success: function(obj) {
for(i=0;i<obj.data.length;i++){
$("#tHead").after("<tr>" +
"<td>" + obj.data[i].name1 +
"</td><td>" + obj.data[i].name2 +
"</td><td>" + obj.data[i].name3 +
"</td><td>" + obj.data[i].name4 +
"</td><td>" + obj.data[i].name5 +
"</td></tr>");
}
}
});
});
Now I can append data after "tHead" tr.
Because I use .after in my js code, so the data row will append one by one after"tHead" which will make my first data row become the last one in table.
I need first data row will be first row on table when I append it.
What can I do to make it correct?
I try to use .append but not work, the new row will directly append in the end of "tHead" row.
You simply need to use .append() on the parent table, instead of using .after() on the #tHead
success: function(obj) {
for(var i = 0; i < obj.data.length; i++) {
$("#tHead").parent("table").append("<tr>" +
"<td>" + obj.data[i].name1 +
"</td><td>" + obj.data[i].name2 +
"</td><td>" + obj.data[i].name3 +
"</td><td>" + obj.data[i].name4 +
"</td><td>" + obj.data[i].name5 +
"</td></tr>");
}
}
your rows will now be appended in chronological order.
A second solution would be to use .after() on the :last psuedo selector together with the .siblings() selector used with #tHead.
success: function(obj) {
for(var i = 0; i < obj.data.length; i++) {
$("#tHead").siblings("tr:last").after("<tr>" +
"<td>" + obj.data[i].name1 +
"</td><td>" + obj.data[i].name2 +
"</td><td>" + obj.data[i].name3 +
"</td><td>" + obj.data[i].name4 +
"</td><td>" + obj.data[i].name5 +
"</td></tr>");
}
}
Invert your loop , and it will work as you want
$(document).ready(function()
{
$.ajax(
{
url: "data.json",
dataType: "json",
success: function(obj)
{
for(i=obj.data.length-1;i>=0;i--)
{
$("#tHead").after("<tr>" +
"<td>" + obj.data[i].name1 +
"</td><td>" + obj.data[i].name2 +
"</td><td>" + obj.data[i].name3 +
"</td><td>" + obj.data[i].name4 +
"</td><td>" + obj.data[i].name5 +
"</td></tr>");
}
}
});
});
Something like this maybe:
$(document).ready(function(){
$.ajax({
url: "data.json",
dataType: "json",
success: function(obj) {
$("#tHead").append("<tr>");//----------- open new row.
obj.forEach(function(row) {
$("#tHead").append("<td>");
$("#tHead").append(row);//---------- actual info.
$("#tHead").append("</td>");
});
$("#tHead").append("</tr>");//---------- close new row.
}
}
});
});
An excellent read can be found here : https://stackoverflow.com/a/9329476/2645091
on the different ways to iterate arrays.

Categories