I'm a noob trying to build a map for my Com. Prog. class with the Google Maps API.
I have data that I want to output as markers and infowindows.
I used Codeigniter to output an XML from my database. (data modified for privacy)
<markers>
<item0>
<city>Boston</city>
<latitude>0.01111</longitude>
<longitude>1.2345</longitude>
</item0>
<item1>
<city>Los Angeles</city>
<latitude>9.99999</latitude>
<longitude>2.00011</longitude>
</item1>
</markers>
Now I'm trying to use Javascript to get all the child nodes of each "item" tag.
My callback function:
var xml = data.responseXML;
var items = xml.documentElement.getElementsByTagName("markers");
// for loop iterates through each the child nodes of the "item" tags.
Array.prototype.forEach.call(items, function(markerElem) {
var city = nodeValue(markersElem.children.item[0]);
var point = new google.maps.LatLng(
parseFloat(nodeValue(markersElem.children.item[1])),
parseFloat(nodeValue(markersElem.children.item[2])));
});
The main problem (I believe) is that the "item" tags each contain a unique number, so I can't call them with the getElementsByTagName method.
I've tried modifying the items variable to get the children nodes of the "markers" tag:
var items = xml.documentElement.getElementsByTagName("markers").children;
But the console outputs an error where the items variable is now undefined.
I've also tried to modify the XML file, but I can only seem to output XML through Codeigniter's built-in helper. Maybe there is a way to create a DOM document in PHP 7 that I don't know about?
It will be much easier if you convert XML in your controller with the simplexml_load_string() to a PHP array or object and then use the json_encode() to convert it to JSON format, so it will be much easier to work with this JSON array or object in JS code.
In your controller do this and send it to your view:
json_encode(simplexml_load_string(your XML here), JSON_UNESCAPED_UNICODE);
I would suggest that you would use XPath for that it will allow you to pull all the element under a cetrain path which you can then iterate over as normal.
Related
I have two JSON objects which are Youtube API responses.
I want to append some part of the second JSON (source) to a particular position in the first JSON (destination) and finally have one merged JSON to send to view.
I've tried like so:
var merged = Object.keys(source).forEach(function(key) {
destination.items[key].contentDetails = source[key].items[key].contentDetails;
})
They both contain same number of item sets so I use the same index key for destination within the loop of source and append each to the destination JSON.
destination.items[key].contentDetails is a valid reference that returns correct value in the console but when inside this loop it's undefined.
What am I doing wrong here?
I'm not quite sure about this practice for such task so I'd greatly appreciate for some direction.
Using AngularJS I am making a GET request to receive a JSON document. From this JSON document, after some traversal, I find an array of additional JSON documents. With more JSON traversal on each object in that array, the resulting inner JSON documents are raw HTML.
I am trying to display each of those raw HTMLs in a page, however, I can only get them as a raw text equivalent which is displayed as mere text, not actually rendered in HTML.
Using $sce in my controller, I can render one specific path on one specific element of my array into HTML correctly but not all of them.
Here is my code:
// controller:
$scope.latestEmails = function() {
$http.get('/emails/last/'+$scope.numberOfEmails).success(function(response) {
$scope.insertHtmlHere = $sce.trustAsHtml(response.body[0].body[0].content);
$scope.latestEmails = response.body;
});
}
// HTML
<div ng-bind-html="insertHtmlHere"></div> <!-- works for that one given element -->
<ul>
<li ng-repeat="email in latestEmails">{{email.body[0].content}} <!-- raw text displayed --></li>
</ul>
The ng-bind-html correctly replaces the first object in my array's HTML. The ng-repeat part simply places blocks of HTML text (not rendered as HTML) in a list (screenshot: http://i.imgur.com/swmZ4Xe.png).
Is there a way to render this HTML text received in my ng-repeat as full HTML? Is there a different AngularJS methodology I could use to accomplish this?
Any help or advice would be greatly appreciated!
After a lot of loop and concatenation trickery I found my answer. Basically I loop through through the array of HTML documents, concatenate each one together and display that concatenated HTML.
Here is my solution code:
// Controller:
$http.get('/emails/last/'+$scope.numberOfEmails).success(function(response) {
console.log('made a latestEmails get request');
console.log(response);
// get HTML of each email and concatenate together
var concat;
for(var i=0; i<response.body.length; i++) {
var email = response.body[i].body[0].content;
concat+=email;
}
// display the concatenated emails as pure HTML
$scope.insertHtmlHere = $sce.trustAsHtml(concat);
});
// HTML
<div ng-bind-html="insertHtmlHere"></div>
Hope that helps someone else who comes across this problem.
I've created a live feed (like Facebook's) wherein if you scroll to the bottom of the div, it gets more feeds via ajax. Also, it keeps checking for new feeds at iteration of 5 secs and if new feeds are found, they're loaded at the top of the div. Now, every time new feed is found, I want to show it's count in notification. And btw, the feed data is returned in a json array in form {'success':true,'data':'the-html-form-of-new-feeds'}.
I want to count the number of feeds in data part for which I'm using $(json.data).find('.one_feed').length (json is the returned json array), but everytime I get 0 as count. What's wrong here, please?
You can wrap you data html code with another HTML element (for example, with div) and search in it.
Example.
$(function()
{
var data = '<div class="one_feed">feed content</div><div class="one_feed"></div>';
var wrap = $('<div>');
wrap.html(data);
alert(wrap.find('.one_feed').length);
});
You are incorrectly accessing the data property of the json response. It can be accessed using json['data']
Try this:
$(json['data']).find('.one_feed').length;
it seems that jquery is searching divs inside the string, and not the dom element
Try yo apply your form in HTML using :
$('#some_div_id').append(json.data);
$('#some_div_id').find('.one_feed').length;
Ans the \n string doesnt work un HTML, use
var response = {'success':true,'data':'<div class="one_feed">feed content</div><div class="one_feed"></div>'};
console.log($(response.data).length)
The above code solves your problem!!
Ok so I have a template in Play! that receives a List as a parameter:
#(actions : List[RecipientAction])
RecipientAction is just a regular case class with a couple of fields. Within the template, I have a <script> tag where I want to use D3 to make a line chart. Inside the script I want to populate a JavaScript array with objects that contain the properties stored in RecipientAction in order to use them for my line chart later. I currently have this code:
testArray2=[];
for(var i=0; i < #actions.length;i++){
testArray2[i]= {};
testArray2[i].eventAt= #actions(i).eventAt.toString();
testArray2[i].action= #actions(i).action.id;
}
When i run it, i get the error "not found: value i". This is because i is a client side variable while actions is a server side variable, so scala cannot find i. What would be the best way to work around this and successfully populate the array?
You need to create a JSON serializer for your RecipientAction, then you'll just be able to print the list as JSON in the template. Say it looks something like this..
import play.api.libs.json._
case class RecipientAction(id: Int, description: String)
object RecipientAction {
// Define a `Writes` for `RecipientAction`
implicit val writes: Writes[RecipientAction] = Json.writes[RecipientAction]
}
I used one of the JSON macros included with Play that will automatically create a Writes for a case class, since all we care about is printing the list.
Then in your template:
#(actions : List[RecipientAction])
#import play.api.libs.json.Json
<script type="text/javascript">
var testArray = #Html(Json.stringify(Json.toJson(actions)));
</script>
The definition of an implicit Writes is required so that Json.toJson knows how to convert the class to JSON. For more about Json serialization/deserialization see the documentation.
i have just begun using jquery datatables in my project and I do like it so far. I have many tables, sometimes 2-3 on a page. Rather than have to keep track of what initialization string I am using for a specific table and trying to remember what webpage its on, I have built an xml file to store all the initialization strings. I built some jquery functions to retrieve the strings on document ready but it never dawned on me how to actually inject the json into the method as a parameter.
If i was doing it manually you would call
selector.dataTables(json initializer string here);
Once I have that string how do I actually inject it into the method call? Or do I have to create that whole code line and inject it into my script?
If the json data comes in as something like this:
{"order": [[ 3, "desc" ]]}
You could use jquery to get the JSON via a HTTP GET request.
$.getJSON('somejson.json',function(data){
someSelector.dataTables(data)
});
Because you are using getJSON it will expect the JSON to be in that format and do the parsing for you.
Or if the JSON is available already(since you are using jquery you can use it to parse the JSON data just in case there may be a browser support issue since IE7 and below does not support JSON.parse.):
var options = $.parseJSON(someData);
someSelector.dataTables(options)
you can assign the json string to a variable...
var tableSettings = theJsonString;
selector.dataTables(tableSettings);
you may need to convert the string to an object first...
//javascript
var tableSettings = JSON.parse(theJsonString);
//jquery
var tableSettings = $.parseJSON(theJsonString);