I am getting a 'date' element from a RSS feed. I am having trouble with sorting and displaying the information. Can someone have a look? Thanks!
$('#feedContainer').empty();
$.ajax({
type: 'GET',
url: categoryURL,
dataType: 'xml',
success: function (xml) {
var data = [];
$(xml).find("item").each(function () {
var dateText = $(this).find("Date").text().substr(0,5);
var title = $(this).find("title").text();
var region = date.substr(6);
if (region.length < 3) { region = "ALL"; }
var description = $(this).find("description").text();
var descriptdisplay = description.substr(0, description.indexOf(",")+6); //Parsed DATE from description
if (descriptdisplay.length > 35) { descriptdisplay = "See event for details"; }
//var locationdisplay = description.substr(description.indexOf(",")+6,4); //Parsed the location from description
var category = $(this).find("category").text();
var linkUrl = $(this).find("link").text();
var item={ title: $(this).find("title").text(), dateText: $(this).find("Date").text().substr(0,5), date : new Date( dateText) }
data.push(item);
// var displaytitle = "<a href='" + linkUrl + "' target='_blank'>" + title + "</a>" ;
// $('#feedContainer').append('<h3>'+displaytitle+'</h3><p>'+"Event Date: "+descriptdisplay+'</p><p>'+"Location: "+region+'</p');
data.sort(function(a,b){ return a.date > b.date;});
$.each(data, function(index, item) { $('#feedContainer').append('<h3>'+item.title+'</h3><p>'+"Event Date: "+item.dateText+'</p><p>'+"Location: "+item.date+'</p'); });
});
}
});
You're sorting date objects, try sorting the epoch timestamp instead:
data.sort(function(a,b){
return a.date.getTime() > b.date.getTime();
});
Related
$(function() {
$('#sendit').click(function() {
var user_id = $('#user_id2').val();
var all = $('#Senditem').find("input[name='forall[]']").map(function() {
return $(this).val();
}).get();
var session = $('#sessionit').val();
var dateit = Date.now();
var thisdata = '<span style="color: red">No User Selected';
var div2 = document.getElementById('resultshere');
div2.innerHTML = '';
if (user_id < 1) {
var div = document.getElementById('resultshere');
div.innerHTML = thisdata;
} else {
var posting =
$.get(
$(this).data('url'), {
senddate: dateit,
session: $('#sessionit').val(),
user_id: $('#user_id2').val(),
inputmade: $('#Senditem').find("input[name='forall[]']").map(function() {
return $(this).val();
}).get()
});
$('#destinationtable tr:first').after('<tr><td>' +
user_id + all + session + '</td><td> <input name="inputmade" value="' + dateit + 'pim' + user_id + 'pim' + all + 'pim' + session + '">waiting to insert ..</td></tr>'
);
At button click event, the content in input field are collected in an array and pushed to be saved. Then the array content gets append to another table, which will later be accessed and saved again every 5 seconds by another JavaScript below. The issue is, the JavaScript below never get the correct array format.
(function autoinsert() {
var input = $("#destinationtable td:last").find("input").val();
var req = $.ajax({
type: "get",
url: "{{route('AjaxInsertTuckshopIssueAuto')}}",
data: {
postthis: input
},
error: function() {},
success: function(data) {
$('#resultshere').html(data)
if (input == data) {
function deleterow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
table.deleteRow(rowCount - 1);
}
deleterow("destinationtableTable");
}
},
global: false
});
setTimeout(autoinsert, 5000);
})();
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);
});
}
I am trying to make a World chart that also shows how many transactions are coming from certain country's. But i need to translate the name of the country's to ISO because that is the only way this chart will work. Also the transactions is String (It is actually type of transactions) so i am trying to kind of convert the strings to numbers as well. I don't know if i am doing that right as well.
Here is my code:
<script>
var xmlURL = "some url";
var xml;
var xmlData;
var countryCodeColumn = "Counterparty country";
var categoryColumn = "Type of transaction";
var map;
var jsonText = "{";
var mapData;
var regionStyling = {initial: {fill: '#93959b'}};
$j.ajax({
url:xmlURL,
dataType:"xml",
beforeSend: function(){
$j('#loader').show();
},
success: function(data){
xml = data;
drawMap();
$j('#loader').hide();
}
});
function drawMap(){
console.log("xml as text", (new XMLSerializer()).serializeToString(xml));
var columns = {};
var columnNames = [];
var xmlColumns = $j('head', xml);
xmlColumns.find('headColumn').each(function(){
var columnName = $j(this).find('columnValue').text();
var columnID = $j(this).attr('columnid');
columns[columnName] = columnID;
console.log("column",columnName,columnID);
});
var xmlData = $j('data', xml);
var countryCode;
var category;
var categoryColor;
var url;
xmlData.find('item').each(function(){
itemId = $j(this).find('itemID').text();
url = "./injectColumnViewItemPage.action?metaData.channelID=9&metaData.siteID=723&metaData.sheetId=4640&metaData.itemId=" + itemId + "&metaData.sheetViewID=0&metaData.viewMode=0&view=readonly&sheetItemLinkView=true";
console.log("url", url);
console.log("itemid", itemId);
$j(this).find('column').each(function(){
var colID = $j(this).attr("columnid");
console.log(colID);
var value = $j(this).find('displayData').text();
console.log("field:", colID,value);
if(colID == columns[countryCodeColumn]){
countryCode = value;
}else if(colID == columns[categoryColumn]){
if(value != 0){
category++;
}
category = value;
categoryColor = $j(this).find('rawData').find('choice').attr('style');
}
});
jsonText += '"' + countryCode + '":{' + '"Transactions":"' + category + '","Color":"' + categoryColor + '","ItemID":' + itemId + '},';
});
jsonText = jsonText.substring(0,jsonText.length-1) + "}";
console.log("jsontext", jsonText);
mapData = JSON.parse(jsonText);
console.log("json", JSON.stringify(mapData));
map = new jvm.Map({container: $j('#isheet-map'),
map: 'world_mill_en',
series:{
regions: [{
normalizeFunction: 'polynomial'
}]
},
zoomOnScroll: true,
regionStyle: regionStyling,
backgroundColor: "#ffffff",
onRegionTipShow: function(e,el,code)
{
if(mapData[code])
{
el.html('<div style = "line-height:50%;"><span class="map-tip-title">' + el.html() + '</span><p></p><span class="map-tip-label">Transactions:</span>' + mapData[code]["Transactions"] + '<p></p></div>');
}else{
return false;
}
},
onRegionClick: function(e, code){
if(mapData[code]){
var href ="./injectColumnViewItemPage.action?metaData.channelID=9&metaData.siteID=" + 723 + "&metaData.sheetId=" + 4640 + "&metaData.itemId=" + mapData[code]["itemId"] + "&metaData.sheetViewID=0&metaData.viewMode=0&view=readonly&sheetItemLinkView=true";
$j("#iframe-Map").attr('src', href);
$j("#map-dialog").dialog({modal: true, title: map.getRegionName(code), width:600, height:500});
}
else{
return false;
}
}
});
map.series.regions[0].setValues(getColors());
function getColors(){
var colors = {};
$j.each(mapData,function(code,val){
colors[code] = mapData[code]["Color"];
});
console.log("colors", colors);
return colors;
}
}
</script>
There is nothing wrong with my ajax code since if i link it to another url it works fine
Can anyone tell me why this error?
Server Log:
StandardWrapperValve[ws_site.ApplicationConfig]: Servlet.service() for servlet ws_site.ApplicationConfig threw exception
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 5
at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
at com.google.gson.Gson.fromJson(Gson.java:791)
Javascript function, responsible for capturing the data of the filled form and sending to the server:
function save()
{
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name}';
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: obj
}).done(function (data)
{
alert(data);
});
}
Restful Java method:
#POST
#Path("data")
#Produces(MediaType.TEXT_PLAIN)
#Consumes({MediaType.APPLICATION_JSON})
public String registerUser(Gson json)
{
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
u.setAddress(a);
userDAO.save(u);
return "Saved successfully!";
}
Save userDAO method:
public void save(User u) {
EntityManager em = JPAUtil.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (u.getId_User() == null) {
em.persist(u);
} else {
em.merge(u);
}
tx.commit();
} catch (Exception ex) {
ex.printStackTrace();
if (tx != null && tx.isActive()) {
tx.rollback();
}
} finally {
em.close();
}
}
Using Gson to convert json into an object
You're not sending an object to the server, you're just sending a string:
var obj = '...';
Instead, send an object:
var objdata = {
"email_user": str_email,
"name_user": str_name
};
var objlocation = {
"country": str_country,
"state": str_state,
"city": str_city,
"neighborhood": str_neighborhood,
"street": str_street,
"number": str_number,
"zipcode": str_zipcode
};
var obj = {
"user": [objdata],
"endereco": [objlocation]
};
A string that looks like an object is still a string.
objdata was not populating correctly as valid json. Try with this:
function save() {
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name + '"}';
console.log(objdata);
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
console.log(objlocation);
var obj = '{"user":[' + objdata + '],"endereco":[' + objlocation + ']}';
console.log(obj);
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: JSON.parse(obj)
}).done(function (data) {
alert(data);
});
}
In your server side you are trying bind JSON data.
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
It mean user and endereco should be a JSON objects like below.
{
"user":{
"email_user":"str_mail","name_user":"nameeee"
},
"endereco":{
"country":"str_country","state":"str_state","city":"str_city","neighborhood":"str_neighborhood","street":"str_street","number":"str_number","zipcode":"str_zipcode"
}
}
But in your case user and endereco are actually a JSONArray's(See the square brackets.).
{
"user":[
{
"email_user":"str_mail",
"name_user":"nameeee"
}
],
"endereco":[
{
"country":"str_country",
"state":"str_state",
"city":"str_city",
"neighborhood":"str_neighborhood",
"street":"str_street",
"number":"str_number",
"zipcode":"str_zipcode"
}
]
}
So change below line
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
to
var obj = '{"user":'+objdata+',"endereco":'+objlocation+'}';
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>
`