jquery (server side) search and sorting using ajax - javascript

I tried to create search and sort from live URL using Ajax , i used do search function and i managed to retrieve the data from the URL .
I am showing Ajax response in select options as below code. I want to sort the select options in order of values (level values),the values are retrieved randomly in the results.
How can I combine search and sort function for that ?I used lots of tutorials to do that. To anyone who knows please help me to do that. Thank you.
Please provide a solution to automate sort data with the current search function on values basis (by level) . Sample of the current results like :
So far I have this code:
function doSearch() {
$.Ajax({
URL: 'https://live.ksmobile.net/live/BOYS',
data: {
page_size: 10,
page_index: current_page
},
cache: false,
type: 'GET',
datatype: 'JSON',
success: function(r) {
var max = $('#limit').VAL();
if (r.data.video_info.length < max) max = r.data.video_info.length;
for (index = 0; index < max; index++) {
var entry = r.data.video_info[index];
var level = parse Int(entry.level);
if ((level > $('#min').val()) && (level < $('#max').val())) {
count++;
var HTML = '<div class="entry ' + '"><h="' + entry + '">';
HTML += '<h3>Level: <span>' + entry.level + '</span> <span>' + entry.name + '' + '</span>id:<span>' + entry.heat;
HTML += '</div>';
$('#main').append(HTML);
}
}

You could write a custom sort function which would look something like:
function sortResults(array) {
array.sort(function(x, y) {
if (parseInt(x.level, 10) < parseInt(y.level, 10)) {
return -1;
}
if (parseInt(x.level, 10) > parseInt(y.level, 10)) {
return 1;
}
return 0;
});
}
and then call it before your for loop:
sortResults(r.data.video_info);
You could also use a library like lodash to save some trouble and then use:
r.data.video_info = _.sortBy(r.data.video_info, item => {
return _.parseInt(item.level);
});

Related

Utilising the same ajax data for a "refresh all" event (wanting to prevent multiple calls)

So I have a page where multiple containers are dynamically added and filled with html, some of which are populated with data pulled via ajax from a json file. Every 5 minutes the page runs a function that gets every container (marked with class) and for each of them works out its id/index (probably not very efficiently) and does the ajax post.etc.
But the ajax call resulting data is the same essentially for every instance (no limit but on average there would be ~30 ajax calls of the same data for one whole page), it grabs it, decodes it, sorts it, updates html and that is it really.
This feels clunky and im sure will cause issues down the line, is there anything I can do to prevent these 30+ ajax posts without disabling it being 'Asynchronous'/lessen the impact of it?
setInterval(function() {
$('.fill').each(function() {
var selectId = this.id;
var selectIdNum = selectId.replace(/\D/g, '');
selectedId = 'selectedcoin' + selectIdNum;
var index = document.getElementById(selectedId).selectedIndex;
$.ajax({
url: 'array-to-json.php',
type: 'POST',
dataType: 'json',
success: function(data) {
data.sort(function(a, b) {
return (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0);
});
result = data;
var php1 = [result[index].name, result[index].symbol, result[index].price_btc, result[index].percent_change_24h, result[index].price_usd, result[index].id, result[index]['24h_volume_usd']];
var myCoinCost = parseFloat($('#buyprice' + selectIdNum).val());
var myPercCoin = (parseFloat(php1[2]).toPrecision(20) - myCoinCost) / myCoinCost * 100;
var myCoinTotal = parseFloat($('#coins' + selectIdNum).val());
var myUsdCoin = myCoinTotal * parseFloat(php1[4]).toPrecision(20);
$("#price" + selectIdNum).html(php1[2]);
$("#pricePercent" + selectIdNum).html(php1[3]);
$("#priceUsd" + selectIdNum).html(php1[4] + "</span>");
$("#volDay" + selectIdNum).html("$" + php1[6] + "</span>");
$("#myPercent" + selectIdNum).html(myPercCoin.toFixed(2) + "%");
$("#myEarnings" + selectIdNum).html(myUsdCoin.toFixed(2));
},
error: function() {
alert("error");
}
});
});
}, 300 * 1000);
It seems like your call returns all the data for all the containers already. You don't pass any specific ID into it, and you are filtering the results when you get them, so I will make that assumption.
In that case, all you need to do is move your .each loop inside the ajax success function. That way the ajax runs once, and you just loop through the data when it's received to apply it to the HTML.
I think this should do it:
setInterval(function() {
$.ajax({
url: 'array-to-json.php',
type: 'POST',
dataType: 'json',
success: function(data) {
data.sort(function(a, b) {
return (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0);
}); //is this really necessary? The server-side could probably sort it more efficiently, esp if it's the result of the SQL query.
result = data;
$('.fill').each(function() {
var selectId = this.id;
var selectIdNum = selectId.replace(/\D/g, '');
selectedId = 'selectedcoin' + selectIdNum;
var index = document.getElementById(selectedId).selectedIndex;
var php1 = [
result[index].name, result[index].symbol,
result[index].price_btc, result[index].percent_change_24h,
result[index].price_usd, result[index].id,
result[index]['24h_volume_usd']
];
var myCoinCost = parseFloat($('#buyprice' + selectIdNum).val());
var myPercCoin = (parseFloat(php1[2]).toPrecision(20) - myCoinCost) / myCoinCost * 100;
var myCoinTotal = parseFloat($('#coins' + selectIdNum).val());
var myUsdCoin = myCoinTotal * parseFloat(php1[4]).toPrecision(20);
$("#price" + selectIdNum).html(php1[2]);
$("#pricePercent" + selectIdNum).html(php1[3]);
$("#priceUsd" + selectIdNum).html(php1[4] + "</span>");
$("#volDay" + selectIdNum).html("$" + php1[6] + "</span>");
$("#myPercent" + selectIdNum).html(myPercCoin.toFixed(2) + "%");
$("#myEarnings" + selectIdNum).html(myUsdCoin.toFixed(2));
});
},
error: function(jqXHR) {
alert("Error while fetching data");
console.log("Error while fetching data: " + jqXHR.status + " " + jqXHR.statusText + " " + jqXHR.responseText); //improved error logging
}
});
}, 300 * 1000);

Jquery array.length is shorter than the real array length

I'm new to jquery and a I've got the problem as mentioned in the title.
My controller code looks like:
[HttpPost]
public JsonResult getProjectList()
{
List<Project> projectList = new List<Project>();
foreach (IML.ProjectInfo pr in getProjectArray())
{
Project x = new Project(pr.Name, pr.ID, pr.OwnerID, pr.CreatedBy, pr.CreatedAt, "", pr.Deleted, pr.Closed);
projectList.Add(x);
}
return Json(projectList.ToArray());
}
When I check the projectList under debugger mode it has 6 elements.
In my webpage I have the following ajax call:
$.ajax({
url: '#Url.Action("getProjectList")',
type: "POST",
//enumerowanie projektów
success: function (data) {
projekty = data;
var wyswietl ="<table><tbody>";
var tabelka = "";
var wybranyProjekt;
alert($.data.length);//this alert tells me that data.length is 3
for (i = 0; i < 6; i++)//even if $.data.length is 3 the data[i].Name holds values for 6 elements
{
tabelka += "<tr class=\"enumeracjaProj\" id=\"" + i
+ "\"><td class=\"projekty\" id=\"" + i + "\"> " + data[i].Name + " </td></tr>"
}
wyswietl += tabelka;
wyswietl += "</tbody></table>";
$('#projekty_div').append(wyswietl);
})
Even if I Post an array of 6 elements ajax result tell me that its length is 3. If I go over it in loop which was 6 iterations hard-coded I get properly displayed name.
Small correction, You should change your alert($.data.length); to alert(data.length);
$.data is jQuery function and your data is response result

embedding ondblclick in generated TR

i'm converting an html table from plain old MVC3 to ajax, and wish to keep some of the functionality from the MVC version. specifically the users currently double-click anywhere on a row to get a detailed view of the record associated with the row. this was accomplished with an ondblclick='' in the tag.
#<tr class="#CSSclass" ondblclick="window.location='/Request/Details/#item.ID'">
that's the old MVC
$.ajax({
url: "/request/DRequest",
type: "GET",
dataType: "json",
success: function (response) {
for (i = 0; i < response.length; i++) {
var accepted
var cssclass
var datestr
var highlite
var trstr
if (response[i].NeededByDate - Date.now() / (1000 * 60 * 60 * 24) < 2) {
datestr = '<span class="attention">' + response[i].NeedByDate + '</span>'
alert(datestr)
}
else {
datestr = response[i].NeedByDate
}
if (response[i].AcceptedBy != null) {
accepted = response[i].AcceptedBy
highlite = '<td>'
}
else {
accepted = 'Accept'
highlite = '<td style="background-color: #eecc88;">'
}
if (response[i].Priority == true) {
trstr = '<tr class="attention" ondblclick="window.location="/Request/Details/' + response[i].ID + '">'
}
else {
trstr = '<tr ondblclick="window.location=\'/Request/Details/' + response[i].ID + '\'>'
}
var $tr = $(trstr).append(
$('<td>').html(datestr),
$('<td>').text(response[i].RequestedBy),
$('<td>').text(response[i].UserName),
$('<td>').text(response[i].RequestedPC),
$('<td>').text(response[i].RequestType),
$('<td>').text(response[i].Division),
$(highlite).html(accepted),
$('<td>').html(unescape(response[i].ReqTypeIcon))
).appendTo('#requestTable');
}
}
});
and that's the javascript handling the row creation now. this crashes. returns no rows. if i remove the ondblclick from the trstr variable it runs. any way around this? maybe i'm escaping incorrectly. thanks!

pagination with AJAX url

Im beginner in AJAX & JS so please bear with me.
I use this AJAX for the pagination :
$(function () {
var keyword = window.localStorage.getItem("keyword");
//pagination
var limit = 3;
var page = 0;
var offset = 0;
$("#btnLoad").on('click', function () {
page++;
if (page != 0)
offset = (page - 1) * limit;
$.ajax({
url: "http://localhost/jwmws/index.php/jwm/search/msmall/" + keyword + "/" + limit + "/" + offset, //This is the current doc
type: "GET",
error: function (jq, st, err) {
alert(st + " : " + err);
},
success: function (result) {
alert("offset=" + offset + " page =" + page);
//generate search result
$('#search').append('<p style="float:left;">Search for : ' + keyword + '</p>' + '<br/>' + '<p>Found ' + result.length + ' results</p>');
if (result.length == 0) {
//temp
alert("not found");
} else {
for (var i = 0; i < result.length; i++) {
//generate <li>
$('#list').append('<li class="box"><img class="picture" src="images/HotPromo/tagPhoto1.png"/><p class="name"><b>Name</b></p><p class="address">Address</p><p class="hidden"></p></li>');
}
var i = 0;
$(".box").each(function () {
var name, address, picture, id = "";
if (i < result.length) {
name = result[i].name;
address = result[i].address;
picture = result[i].boxpicture;
id = result[i].mallid;
}
$(this).find(".name").html(name);
$(this).find(".address").html(address);
$(this).find(".picture").attr("src", picture);
$(this).find(".hidden").html(id);
i++;
});
$(".box").click(function () {
//alert($('.hidden', this).html());
window.localStorage.setItem("id", $('.hidden', this).html());
$("#pagePort").load("pages/MallDetail.html", function () {});
});
}
}
});
}).trigger('click');
});
Please notice that i use the variables for pagination in the url:. I tried to alert the page and offset variable, and its working fine.
However, the AJAX only working for the first page (when page load). The rest is not working even though the page and offset variable's value is true.
Theres no warning/error in console. The data just not shown.
Any help is appreciated, Thanks :D
It is a bit hard to debug your code when the whole HTML is missing.
Could you put your code into JSFiddle, both HTML and JS.

Parsing the json data from google and twitter differences

I am new to javascript. I have worked on twitter API. In twitter API i used jQuery.ajax function to get json data from twitter servers. But when i use the same option with google maps server, my app isn't giving any response the moment it enters the jQuery.ajax. I tried to debug it using jslint, but it came out clean. I used debugging using alert, and it stops when it enters jQuery.ajax function. Is meathod to retrieve data varies with the source ?
If not why isn't my code responding ?
Twitter running function ::
var twitterapi = "http://search.twitter.com/search.json?";
jQuery.ajax(
{
type: "GET",
url: twitterapi,
data:
{
"q": hashtag,
"rpp": 1000
},
dataType: 'jsonp'
}).done(function (response)
{
var results = response.results;
for (var i = 0; i < results.length; i++)
{
$("#tweet").prepend("<li class='tweet'>" +
"<img src='" +
results[i].profile_image_url +
"'/>" +
"<span class='username'>" +
results[i].from_user +
"</span> <span class='tweet_content'> " +
results[i].text +
"</span></li>");
}
});
My google maps API(not working)
var j = 2;
var friends = [];
var distance =[];
$(document).ready(function () {
alert("function started");
$('#button').click(function () {
if (j < 11) {
$('#friends').append('Friend' + j + ':<input type="text" id="friend' + j + '"/><br/><br/>');
j++;
}
else {
alert("Limit reached");
}
});
$('button').click(function(){
var a =[];
alert("button clickede");
for(i=1;i<=j;i++)
{
a[i] = $("#friend" + i).val();
}
var gurl = "http://maps.googleapis.com/maps/api/distancematrix/json?"+
"origins=" +
a.join('|').replace(/ /g,'+') +
"&destinations=" +
a.join('|').replace(/ /g,'+') +
"&sensor=false";
alert("making request to" +gurl);
jQuery.ajax(
{
type: "GET",
url: gurl,
dataType: 'jsonp'
}).done(function (response)
{
alert("request made to"+gurl);
var rows = response.rows;
alert(row[0].elements[0].value);
for(var i=0;i<rows.length;i++)
{
for(var j=0;j<elements.length;j++)
{
distance[i][j] = row[i].elements[j].distance.value;
}
}
alert(distance[0][0]);
});
});
});
I don't know what error are you getting so i can't be of much help.
But the code you posted has three issues:
1- Since a is undefined, i couldn't get past the first two lines.
2- Removing the a calls in the code, then it threw a Syntax Error. I fixed this by removing the last }); line.
3- It made the request, but it threw another error (probably because the URL was malformed).

Categories