Jquery Html Data Function - javascript

I've been developing a web game, with jquery doing some of the work. It was on a server, but I've moved it back to my laptop. Everything seems to work fine, except the most important function, which imports the contents of an html file.
$(".ReportList a").live('click', function(){
var getreportname = $(this).text();
$("#scroller").append("<span>The reportname is " + getreportname + "</span>");
var usersreport = "ReportList_" + User + "";
jQuery.get('Reports/' + getreportname + '.html', function (data) {
$("#" + usersreport).html(data);
$("#" + usersreport + " span").addClass("Py" + User);
updateCount();
});
});
Not sure why it stopped working. Would appreciate any insight.

I didn't need the .get() method to do what I wanted, .html() was good enough if I re-formulated the script.

Related

Display SignalR message with embedded HTML

I've begun playing around with SignalR, of course starting with the initial chat hub that I suppose everybody does at one point or another. I want to modify it so that if the user types in HTML in their message, when it gets displayed it shows rendered HTML as oppose to just the string with HTML tags in it.
Here is my javascript:
<script type="text/javascript">
$(function () {
var chat = $.connection.chatHub;
chat.client.broadcastMessage = function (name, message) {
var encodedName = $('<div />').text(name).html();
var encodedMesg = $('<div />').text(message).html();
if (message === "joined session") {
$('#discussion').append('<li><strong>' + encodedName + ' ' + encodedMesg + '</strong></li>');
} else {
$('#discussion').append('<li><strong>' + encodedName + '</strong>: &nbsp' + encodedMesg + '</li>');
}
};
$('#message').focus();
$.connection.hub.start().done(function () {
chat.server.send("#FullName", "joined session");
$('#sendmessage').click(function () {
chat.server.send("#FullName", $('#message').val());
$('#message').val("").focus();
});
});
});
The encodedMesg has "this is <b>bold</b>", but instead of rendering it as HTML, it just shows it as a string. How can I allow this to render as HTML?
I've tried encoding the < as < and > as > but that didn;t work. I also tried %3C and %3E but they didn;t work either.
Calling .text changes the text of an object and intentionally prevents html or scripts from being parsed.
You can get it to parse it by changing the value with .html
var encodedMesg = $('<div />').html(message);
use this:
var encodedMsg = $('').text(message).html();

Clicking on an element to reveal additional .get information

I'm trying to work through the 2nd question on this set of problems. I have to be able to click on a legislator's name and have additional information about him/her show up. Here's what I have so far.
$(function() {
$("form#get-zip").submit(function() {
var zip = $("input#zip").val();
$.get("http://congress.api.sunlightfoundation.com/legislators/locate?apikey=191e116b2a244fb48c5028e8f370488b&zip=" + zip, function(responseText) {
responseText.results.forEach(function(legislator) {
$("ul#legislators").append("<li>" + " " + legislator.first_name + " " + legislator.last_name + " (" + legislator.chamber + ")" + "</li>");
$("li").click(function() {
$(this).append("<p>Party: " + legislator.party + ", District: " + legislator.district + "</p>");
});
});
});
return false;
});
});
The problem is that when I click on a legislator's name it reveals information about all the legislators in the list rather than the particular legislator I clicked on. This is my first experience with A.P.I.s and I'm very much still a novice programmer. I'm finding all these moving parts to be very mentally exhausting. So I really appreciate any help I can get with this. Thanks.
I would suggest building out all your html on submit, even the details that appear below each legislator. Then hide all that extra detail. And set up the function of your li's to show the relative details.
$(function() {
$("form#get-zip").submit(
function() {
var zip = $("input#zip").val();
$.getJSON("http://congress.api.sunlightfoundation.com/legislators/locate?apikey=191e116b2a244fb48c5028e8f370488b&zip=" + zip,
function(responseText) {
$.each(responseText.results,
function(i,legislator) {
var newEl = $("<li>" + " " + legislator.first_name + " " + legislator.last_name + " (" + legislator.chamber + ")" + "<p>Party: " + legislator.party + ", District: " + legislator.district + "</p></li>");
newEl.appendTo("ul#legislators");
$("ul#legislators li").last().find("p").hide(); // hide the last added one
}); // end each
}); // end get function
}); // end submit function
$("ul#legislators").on("click", "li",
function() {
var details = $(this).find("p");
if (details.is(":visible")) {
details.hide();
} else {
details.show();
}
}); // end click function
}); // end document ready function
When the click event fires, the legislator variable no longer contains the data you looking for.

memory leak in IE9

I seem to have a memory leak in IE9. It works just fine in Chrome. The memory leak is on the client machine. I left this page open for days in chrome and no leak.
Using jquery 1.9.0, signalr rc2
This page uses signalr and refreshes it's contents every 5 seconds with what comes from the server.
I have four tabs/divs that do this.
proxy.on('newRequests', function (data, updatetime) {
newrequestupdatetime.text('Last updated: ' + updatetime);
numberofnewrequests.text('Number of cases found: ' + data.length);
numberofnewrequeststab.text('(' + data.length + ')');
var h = '';
$.each(data, function (i, val) { h += '<li>' + val.Ref + ' ' + val.Type + '</li>'; });
newrequests.html(h);
});
newrequests is an ul on the page which I initialized like this
var newrequests = $('#newrequests');
in
$(function () {});
Not really sure what is the cause.
I can make it a lot worse by doing this.
newrequests.empty();
$.each(data, function (i, val) { newrequests.append('<li>' + val.Ref + ' ' + val.Type + '</li>'); });
I'm guessing that it has something to do with the last line of code, that puts the new html inside the ul tag.
Try changing the line into this (old code):
document.getElementById('newrequests').innerHTML = h;
See also: jQuery - Internet Explorer memory leaks

Cannot get json results from twitter using PhoneGap and jQuery

I'm trying to get the last 50 tweets using a certain hash tag, on a mobile device using PhoneGap (0.9.6) and jQuery (1.6.1). Here's my code:
function getTweets(hash, numOfResults) {
var uri = "http://search.twitter.com/search.json?q=" + escape(hash) + "&callback=?&rpp=" + numOfResults;
console.log("uri: " + uri);
$.getJSON(uri, function(data) {
var items = [];
if(data.results.length > 0) {
console.log("got " + data.results.length + " results");
$.each(data.results, function(key, val) {
var item = "<li>";
item += "<img width='48px' height='48px' src='" + val.profile_image_url + "' />";
item += "<div class='tweet'><span class='author'>" + val.from_user + "</span>";
item += "<span class='tweettext'>" + val.text + "</span>";
item += "</div>";
item += "</li>";
items.push(item);
});
}
else {
console.log("no results found for " + hash);
items.push("<li>No Tweets about " + hash + " yet</li>");
}
$("#tweetresults").html($('<ul />', {html: items.join('')}));
});
}
This code works great in a browser, and for a while worked in the iPhone simulator. Now it's not working on either the iPhone or Android simulator. I do not see any of the console logs and it still works in a browser.
What am I doing wrong? If it's not possible to call getJson() on a mobile device using PhoneGap, what is my alternative (hopefully without resorting to native code - that would beat the purpose).
Bonus: how can I debug this on a mobile simulator? In a browser I use the dev tools or Firebug, but in the simulators, as mentioned, I don't even get the log messages.
As always, thanks for your time,
Guy
Update:
As #Greg intuited, the function wasn't called at all. Here's what I found and how I bypassed it:
I have this <a> element in the HTML Get tweets
Then I have this code in the $(document).ready() function:
$("#getTweets").click(function() {
var hash = "#bla";
getTweets(hash, 50);
});
That didn't call the function. But once I changed the code to:
function gt() {
var hash = "#bla";
getTweets(hash, 50);
}
and my HTML to:
Get Tweets
it now works and calls Twitter as intended. I have no idea what's screwed up with that particular click() binding, but I ran into similar issues with PhoneGap before. Any ideas are appreciated.
Considering that (a) there isn't much that could go wrong with the first line of your function and (b) the second line is a log command, then it would seem that the function isn't being called at all. You'll have to investigate the other code in your app.
Or are you saying that you don't have a way to read logged messages on your mobile devices?

Variable url in json-script

Messing around for days know. Learning javascript and jquery a few weeks, it goes well, but sometimes...
For an mobile app i'm trying to get the coordinates. Showing them on page isn't a problem, but I want them elsewhere.
In the main.js
var getLocation = function() {
var suc = function(p) {
document.getElementById("locatie").innerHTML = "http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20";
};
var locFail = function() {
};
navigator.geolocation.getCurrentPosition(suc, locFail);
};
And in the htmlfile
<body onload="getLocation();" >
<p id="locatie">Finding geolocation...</p></ul>
<div id="geolocation">
Bezig met laden. Momentje geduld</div>
<script type="text/javascript">
jQuery(function(){
var script=document.createElement('script');
script.type='text/javascript';
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=53.216493625&lon=6.557756660461426&max=20";
$("body").append(script);
});
function processTheseTerraces(jsonData){
var shtml = '';
var results = jsonData.results;
if(results){
$.each(results, function(index,value){
shtml += "<li class='store'><a class='noeffect' href='#'><span class='image' style='background-image: url(pics/terras1.jpg)'></span><span class='comment'>" + value.address + "</span><span class='name'>" + value.building_name + "</span><span class='stars5'></span><span class='starcomment'>132 Beoordelingen</span><span class='arrow'></span></a></li>";
});
$("#geolocation").html( shtml );
}
}
</script>
Now I want the coordinates passing through json and load the data. I thought to change
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=53.216493625&lon=6.557756660461426&max=20";
in
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20";
But that doesn't work. Anyone suggestions how I can solve this.
This: http://www.192.168.1.111 is just a wrong URL. I guess you need just this: http://192.168.1.111
Geolocation can take a long time (multiple seconds). It is an asynchronous request which means that the other javascript code may execute before the geolocation has grabbed the address. The solution is to put any code or function calls that use the location inside the callback function on the navigator.geolocation.getCurrentPosition
The JQuery is building the URL before the lat and lng have been defined.
onload="getLocation();" tells that when the document is loaded call getLocation function and inside this function you set the innerHTML of <P id="locatie"> TAG as: http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20
So problems are:
If you make a script tag and assign source then browser fetch the source data but writing an url on inner html of a <p> tag won't do this and it doesn't make sense.
Code fragment below is loaded before the document is loaded but i guess you do not want this:
jQuery(function(){
var script=document.createElement('script');
script.type='text/javascript';
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=53.216493625&lon=6.557756660461426&max=20";
$("body").append(script);
});
If you want: script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20"; then you have to define p.coords first and before calling this otherwise p.coords is undefined.
Solution i am not sure what you exactly asking so could not answer. Do you want to assign inner HTML of the #locatie element or do you want to load customized script as tag?
Either ways, you have to make an ajax call to server which maybe like this:
$.ajax({
url: "http://www.192.168.1.111/tools/gpslocation.php",
data: "lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20",
success: function(Result){
// use Result variable in came from the success function.
document.getElementById("Your_ID_Goes_Here").innerHTML = "do_Something";
}
});

Categories

Resources