Javascript error with sort - javascript

i have this code as shown below,
i got this from a developer who went afk because he has family troubles
basically this code below should grab the json results and form them into a table after sorting the price and then placing it in the table.
heres the code
//first define a function
var sortTable = function () {
$("#tableid tbody tr").detach().sort(function (a, b) {
//substring was added to omit currency sign, you can remove it if data-price attribute does not contain it.
return parseFloat($(a).data('price').substring(1)) - parseFloat($(b).data('price').substring(1));
})
.appendTo('#tableid tbody');
};
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'api link here',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button = "<button class='redirect-button' data-url='LINK'>Compare</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});
//and here is the 2nd js file
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: '2nd api',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});

Accessing the DOM, to get data that needs to be sorted, is a bad practice IMO. Even worse when you had the results in raw JSON form in the first place (in the success callback of the ajax call). Your success function should do something like this
success: function (json) {
//first sort the results - or better store these results somewhere
//and use that as a data store that is responsible for what is rendered in the DOM
json.results.sort(function(a,b) {
//using substring and parseFloat just like it was done in sortTable
//assuming price field has prices as strings with currency symbol in the first place
return parseFloat(a.substring(1)) - parseFloat(b.substring(1))
});
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
}

Related

Javascript query on SharePoint list items returning same results

I'm trying to show the Title field of a SharePoint list using a JavaScript Query but it just keeps returning the same result regardless of the link I click on. So as below, if I click on 'Lenovo T470' that's what its hould show above the image but it keeps showing 'Lenovo X1 Carbon'.
If I change the code:
var DeviceName = result.Title;
to:
var DeviceName = item.Title;
it comes back undefined. Any ideas? Full code below:
function getDevices() {
var txtTitle = "";
var txtTitleName = "";
//var txtDeviceType = "";
var query = "http://example.com/sites/it/ITInfrastructure/_vti_bin/listdata.svc/Devices?select=ID,Title";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function (i, result) {
var tempID = result.Id;
var tempTitle = result.Title;
var DeviceName = result.Title;
txtTitle = txtTitle + "<p><a href='/sites/it/ITInfrastructure/SitePages/Service%20Catalogue%20Devices.aspx?did=" + tempID + "'>" + tempTitle + "</a></p>";
txtTitleName ="<p>" + DeviceName + "</p>";
});
$('#devices').append($(txtTitle));
$('#devicetitle').append(txtTitleName);
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving data: " + jqXHR.responseText);
});
}

JSON.stringify output to display in table

I POST my table data using ajax in database. Now I want to get back when I give click the open button.
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
debugger;
//var p = JSON.stringify('[' + data + ']');
// alert(p.GetPageInfoResult[0])
//var k = data.main[0];
//alert(data.length);
//var jsonObj = $.parseJSON('[' + data + ']');
//alert(JSON.parse(data));
var jsonPretty = JSON.stringify(JSON.parse(data), null, 2);
},
error: function () {
alert('Error');
When I give my file name I want to display my pageinfo. I get data like
[{"main":{"sub":[],"tittle":"oops","startvalue":"21","stopvalue":"45","status":"","accumalated":"","comment":""}}]
You have not cleared where you want place your resultant Json. Below is that Success result placed in div having table . It is just a sample you may change as per your requirement:
function OnSuccess(response) {
debugger;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var page = xml.find("Table");
var row = "";
$('#popupdiv tbody').html('');
page.each(function () {
var page = $(this);
row = " " + page.find("tittle").text() + " " + page.find("startvalue").text() +
" " + page.find("stopvalue").text() + " " + page.find("status").text() +
" " + page.find("accumalated").text() + " " + page.find("comment").text() + "";
$('#popupdiv tbody').append(row);
});
}

Why isn't my code getting the JSON values?

function getResults(){
var text = encodeURIComponent(searchField.val().trim());
$.ajax({
type: "GET",
url: "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&format=json&titles=" + text,
dataType: "jsonp",
success: function(data){
showResults(data, text);
}
});
}
function showResults(data, text) {
results.show();
var query = "https://en.wikipedia.org/wiki/" + text;
for (var id in data.query.pages) {
var code = "<a href=" + query + " class='results'>" + "<div class='results'>";
code = code + "<strong>" + id.title + "</strong>";
code = code + "<br>";
code = code + id.extract;
code = code + "</div></a>"
$(code).appendTo(results);
}
}
In the showResults function, its showing the id.title and id.extract as undefined. Why is that? What am I doing wrong?
When you do this:
for (var id in data.query.pages)
The, id variable is filled with a property name which is simply a string. If you want to get that value of that property, you have to reference the value of that property as in:
data.query.pages[id]
Or, if that's an object that you then want .title from, then you would need
data.query.pages[id].title
and
data.query.pages[id].extract
That's because when iterating over an object (using for-var-in-object loop), the var (id in this case) is the key, but if you need value, use object[key] syntax. Check the following code
$.ajax({
type: "GET",
url: "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&format=json&titles=newton",
dataType: "jsonp",
success: function(data) {
for (var id in data.query.pages)
document.write(data.query.pages[id].title);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In your case, you are using just key=> '321123'. To get value of object use key. To get object data.query.pages[id].
for (var id in wiki = data.query.pages){
wiki[id].title;
wiki[id].extract;
}
This one should work.
function showResults(data, text) {
results.show();
var query = "https://en.wikipedia.org/wiki/" + text;
for (var id in wiki = data.query.pages) {
var code = "<a href=" + query + " class='results'>" + "<div class='results'>";
code = code + "<strong>" + wiki[id].title + "</strong>";
code = code + "<br>";
code = code + wiki[id].extract;
code = code + "</div></a>"
$(code).appendTo(results);
}
}

Javascript Sort Error with sort function possible simple fix

Probably a simple fix, The rest of the table is sorted excpet this part here
(right at the top)
The table will work now and again in the right order (data from source does not change) but is really dicey when it does or not
Ideas?
Sam
Heres the code
//first define a function
var sortTable = function() {
$("#tableid tbody tr").detach().sort(function(a, b) {
var dataA = $(a).find("td:eq(3)").text().trim();
var dataB = $(b).find("td:eq(3)").text().trim();
return parseFloat(dataA.substring(1)) - parseFloat(dataB.substring(
1));
}).appendTo('#tableid');
};
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'url1',
success: function(json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button =
"<button class='redirect-button' data-url='LINK'>Compare</button>";
$("#tableid").append("<tr ><td>" + section +
"</td><td>" + no + "</td><td>" + price +
"</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function() {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function(error) {
console.log(error);
}
});
//and here is the 2nd js file
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'url2',
success: function(json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button =
"<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid").append("<tr><td>" + section +
"</td><td>" + no + "</td><td>" + price +
"</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function() {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function(error) {
console.log(error);
}
});
The sorting as to do with spaces but is also linked to your jquery selector.
As often, array are 0 index based in Jquery, then if you want to sort on your price your 2nd column (0-index based) you need to do as below :
var sortTable = function() {
$("#tableid tbody tr").detach().sort(function(a, b) {
var dataA = $(a).find("td:eq(2)").text().replace(/\s/g, "");
var dataB = $(b).find("td:eq(2)").text().replace(/\s/g, "");
return parseFloat(dataA.substring(1)) - parseFloat(dataB.substring(
1));
}).appendTo('#tableid');
};
var json = {results:[{price:"$12 .45"}, {price:"$13 .45"}, {price:"$12 .05"}, ]}
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
$("#tableid").append("<tr ><td>section</td><td>no</td><td>" + price);
}
sortTable();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableid"></table>
`

While appending divs, delete older appended divs when there are more than 10

Consider the following JQuery loop. It appends this:
"<div id='1'>" + feedback + "</div>"
1st Question.
I want to increment the id of the appended div after the first one has been appended so that the first appended div's id is 1, the second div's id is 2 and so on.
2nd Question.
When the number of divs reaches 10, I want to delete the first appended div. Which in our case is:
<div id="1">php result</div>
This should keep looping and deleting older divs.
Here's the Jquery ajax loop:
new get_fb();
function get_fb(){
var feedback = $.ajax({
type: "POST",
url: "algorithm.php",
async: false
}).success(function(){
setTimeout(function(){get_fb();}, 8000);
}).responseText;
$('#BuzFeed').append("<div id='1'>" + feedback + "</div>");
}
For counting:
var get_fb = (function() {
var counter = 1;
return function(){
var feedback = $.ajax({
...
}).responseText;
$('#BuzFeed').append("<div id='" + counter + "'>" + feedback + "</div>");
}
})();
get_fb();
and for automatic removal, after
var $buzfeed = $('#BuzFeed').append("<div id='" + counter + "'>" + feedback + "</div>");
add
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.first().remove(); }
Additionally, your code uses some not-so-good practices. The re-write, including my additions would be:
var get_fb = (function() {
var counter = 0;
var $buzfeed = $('#BuzFeed');
return function(){
$.ajax({
type: "POST",
dataType: "html", // based on chat
url: "algorithm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>");
$buzfeedresults.text(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.first().remove(); }
setTimeout(get_fb, 8000);
}).fail(function(jqXhr, textStatus, errorThrown) {
var $buzfeedresults = $("<div id='BuzFeedError'></div>");
$buzfeedresults.text('Error: ' + textStatus);
if (typeof console !== 'undefined') {
console.error(jqXhr, textStatus, errorThrown);
}
});
};
})();
get_fb();

Categories

Resources