Parse First Title from RSS with jQuery - javascript

I don't want to parse all title from the list. I only want the first title to be parsed. Any suggestion?
function parseRSS(url, container) {
$.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
$.each(data.responseData.feed.entries, function(key, value){
var thehtml = '<h3>'+capitaliseFeed(value.title)+'</h3>';
$(container).append(thehtml);
});
}
});
}
function capitaliseFeed(string) {
return string.toUpperCase();
}

Instead of $.each you could loop the data and keep only the first entry
for (var i = 0; i < data.responseData.feed.entries.length; i++) {
var entry = data.responseData.feed.entries[i];
var thehtml = '<h3>'+capitaliseFeed(entry.title)+'</h3>';
$(container).append(thehtml);
break;
}

Related

request.getParameter("pgIndex") always returns null in the servlet

I am trying to paginate rows of a table inside my servlet using hibernate.But once I click on the desire index of the page it always gives me only the first set of row of the table.So I put System.out.print() at every major sections and finally found out that the request.getParameter("pgIndex") is always returns null.
My servlet code:
int pageIndex = 0;
int totalNumberOfRecords = 0;
int numberOfRecordsPerPage = 5;
String sPageIndex = request.getParameter("pgIndex");
//whether pgIndex=1 or pgIndex=2 in the url, always returns null as the output.
System.out.println("pg - " + sPageIndex);
pageIndex = sPageIndex == null ? 1 : Integer.parseInt(sPageIndex);
int s = (pageIndex * numberOfRecordsPerPage) - numberOfRecordsPerPage;
List<ProductHasSize> phs = ses.createCriteria(ProductHasSize.class)
.setFirstResult(s)
.setMaxResults(numberOfRecordsPerPage)
.list();
for (ProductHasSize pro : phs) {... some html content here...}
Criteria criteriaCount = ses.createCriteria(ProductHasSize.class);
criteriaCount.setProjection(Projections.rowCount());
totalNumberOfRecords = (int) (long) (Long) criteriaCount.uniqueResult();
int noOfPages = totalNumberOfRecords / numberOfRecordsPerPage;
if (totalNumberOfRecords > (noOfPages * numberOfRecordsPerPage)) {
noOfPages = noOfPages + 1;
}
for (int j = 1; j <= noOfPages; j++) {
String myurl = "products.jsp?pgIndex=" + j;
String active = j == pageIndex ? "active" : "";
s2 = s2 + "<li class='" + active + "'>" + j + "</li>";
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("[{\"d1\":\"" + s1 + "\",\"d2\":\"" + s2 + "\"}]");
products.jsp
<div class="row">
<div class="col-md-12">
<ul class="pagination" id="pagId"></ul>
</div>
</div>
JavaScript
$(document).ready(function () {
$.ajax({
url: 'AdimnProductFilterAction',
dataType: 'json',
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
});
UPDATE :
$(document).on("click", "#pagId a", function (event) {
//tried with adding another function . But still returns null.
event.preventDefault();
var para = $(this).attr('href').match(/\d+/);
$.ajax({
url: 'AdimnProductFilterAction',
dataType: 'json',
data: {pgIndex: para},
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
});
Thanks in advance.
In sending JSON data, you will not simply receive it as request parameter. Instead, just add "normal" parameter:
Sending as HTTP POST
$.ajax({
url: 'AdimnProductFilterAction',
type: 'POST',
data: {
'pgIndex': para
},
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
Or as HTTP GET
$.ajax({
url: 'AdimnProductFilterAction?pgIndex='+para,
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
To add parameter into your servlet call.

javascript function inside loop run only once

I have a javascript function which is looping on my data basically I call another function inside of loop but it only execute once on last index here is my code and this function I wants to execute on every time.
basically inside loop I call ajax that is run fine on each index of loop but issue is to call db.transaction function which is only execute on last index
db.transaction(populateDB, errorCB);
function renderList(tx, results) {
len = results.rows.length;
console.log("rows" + results.rows.length);
for (var i = 0; i < len; i++) {
(function (i) {
var nid = results.rows.item(i).nId;
$.ajax({
type: 'post',
url: 'http://localhost:50972/LibraryService.asmx/GetTitleSections',
dataType: 'json',
data: "{'MainSectionId':'" + nid + "'}",
contentType: 'application/json; charset=utf-8',
async: false ,
success: function (response) {
var data = response.d;
alert(data.nId);
TitleSectionData = data;
},
error: function (error) {
console.log(error);
}
});
db.transaction(TblTitleSection, errorCB);
})
(i);
// htmlstring += '<li>' + results.rows.item(i).strTitle + '</li>';
// $('#resultList').append("<li>" + results.rows.item(i).strTitle + "</li>");
$('#'+i).append( results.rows.item(i).strTitle );
// $('#tblMainSection').append("<tr><td>" + results.rows.item(i).strTitle + "</td></tr>");
}
// $('#resultList').html(htmlstring);
}
Perhaps you loop continues while running your ajax call. You could try putting the increment (i++) in your success function to force the loop to halt till the function is finished. Syntax seems to be okay.
replace:
for (var i = 0; i < len; i++) {
With:
for (var i = 0; i < len;){
And
success: function (response) {
var data = response.d;
alert(data.nId);
TitleSectionData = data;
}
With:
success: function (response) {
var data = response.d;
alert(data.nId);
TitleSectionData = data;
i++;
}
See if that works :)

JS Alert or append is not working on DOM

Please look at this code on https://jsfiddle.net/safron6/9g98j68g/embedded/result/
I am trying to get the calculated result from the list of APIS and JSON code that is generated to show the precipIntensity. At the end of the code there is an alert and the code works in firebug but nothing is showing up. What may be the reason why the alert does not pop up?
var listAPIs = "";
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time +"?callback=?";
$.getJSON(darkForecastAPI, {
tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
tagmode: "any",
format: "json"
}, function(result) {
// Process the result object
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain")
{
$.each(result, function() {
eachPrecipSum += (result.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ; ///Write mean precip
alert(eachPrecipSum );
$("body").append("p").text(eachPrecipSum)
});
}
});
totalPrecipSinceDate did not declared.
I can't access your hosted data source.
Replacing your current $.getJSON call with an $.ajax call should work:
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time +"?callback=?";
$.ajax({
type: 'GET',
url: darkForecastAPI,
async: false,
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
success: function(result) {
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain") {
$.each(result, function() {
eachPrecipSum += (result.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ; ///Write mean precip
alert(eachPrecipSum );
$("body").append("p").text(eachPrecipSum)
});
}
},
error: function(){
alert('failure');
}
});
});

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>
`

appending JSON data to different elements

I need to use a switch statement to build the markups based on the retrieved feed. Although I'm able to retrieve the data, I wonder if it's correct to use two $(data.value.items).each(function (index, item) { to append the feed's titles to a select box as well as an unorder list. Any better way of doing the same thing?
$.ajax({
url: "http://www.zzz.com/text.json",
dataType: 'json',
success: function (data) {
item_html = parseData(feedformat, data)
var nextarea = $this.next('.area');
nextarea.append(item_html).slideDown();
},
error: function () {
area.html('fail'); }
});
function parseData(type, data) {
var item_html ='';
switch(type) {
case 'thisfeed':
item_html +='<select>';
$(data.value.items).each(function (index, item) {
item_html += '<option>'+item.title+'</option>';
});
item_html += '</select>';
item_html += '<ul>';
$(data.value.items).each(function (index, item) {
item_html += '<li>'+item.title+'</li>
});
item_html += '</ul>';
break;
}
return item_html;
}
You could just do both in the same loop, something like this
$.ajax({
url : 'http://www.zzz.com/text.json',
dataType : 'json',
success : function (data) {
var item_html = parseData(feedformat, data)
var nextarea = $this.next('.area');
nextarea.append(item_html).slideDown();
},
error: function () {
area.html('fail');
}
});
function parseData(type, data) {
switch(type) {
case 'thisfeed':
var select = $('<select />'),
ul = $('<ul />');
$(data.value.items).each(function (index, item) {
var option = $('<option />', {text : item.title}),
li = $('<li />', {text : '.......'});
select.append(option);
ul.append(li);
});
}
}
return select.add(ul);
}

Categories

Resources