Populating HTML unordered lists using jQuery with json - json

I am learning jQuery so please bear with me. I am attempting to populate an HTML unordered list using the following code. The error I am encountering is:
HTMLfile: No such interface. The code breaks on the following jQuery library statement:
fragment.appendchild(script)
Here's the code (a fragment of a successful jQuery Ajax call).
Json contains ID and Name.
success: function(data) {
var $defs = $('<ul id="mylist"></ul>').insertBefore('#lst');
$.each(data.d, function (index, list) {
$(this).appendTo($defs).wrap("<li>" + list.Name + "</li>");
})
},
Thank you

I can't be sure, because there is not enough of your script here, but it may be that your this statement isn't pointing to an HTML element. Console log your this statement to see what it is. I don't know what data.d is, but jQuery likes to replace this statements when you might not expect it to.
Maybe show more of your code?
Learning to understand what this is in JavaScript can be hard enough for people new to the language, so I generally advise people to learn JavaScript, before learning jQuery. Otherwise I think it will take longer to learn JavaScript, and be harder, more error-filled learning experience.

Related

how to interact with HTML forms in delphi using TChromium

i need to update the design of a browser in delphi7 I was using the twebbrowser but he had many problems with javascript and navigation.. so i decide to migrate to Chromium. the problem is that I cannot find code on these components. does anyone know which command would be equivalent to this one in tchromium:
OleObject.Document.all.Item ('ElementbyId', 0) .value: = 'edit1.text';
i need to transfer a text from memo to textarea in html form and at the end send a click on the button on the html form. if anyone knows the commands and can share I appreciate it.
A more flexible alternative than DOM access could be to perform this in Javascript, with the ExecuteJavaScript method of TChromium.
From your summary description, the JS could be something like
document.getElementById('yourtextarea').value = <JSON stringified content of your memo>;
document.getElementById('yourform').submit();
Alternatively, you could implement a JS function in your HTML, and call it with ExecuteJavascript, this way there would not be anything specific (besides the function name) on the Delphi side, and the HTML would be free to evolve.
function setTextAreaAndSubmit(value) {
document.getElementById('yourtextarea').value = value;
document.getElementById('yourform').submit();
}

Creating a UI/writing HTML from a JSON file

I have a really long, unwieldy, unformatted JSON file generated by Lighthouse (a tool that conducts page load time analysis- so this file has the results of the tests). In order to make it formatted to be readable by people, I need to apparently create a UI around this file. My problem is that I'm not sure how to begin working on it.
I've read about something like creating HTML from JSON objects, I think I'd like to try that to just display all the information from the tests in the browser right now... But where would I write that? I have one Node.js file right now, which is running the tests and using JSON.stringify() to stick the JSON'd results into a file. Can I generate the HTML right after I create the JSON? (And the main question- how would I create HTML from a JSON file?)
I'm just starting out with Node and JSON, any tips are highly appreciated.
Yes, you can create HTML from a JSON file.
Here's a simple example done with jQuery, first creating an array of all of the elements, and then using .join("") to parse them. Once parse, they can simply be appended anywhere in the DOM:
var json_file = {
"one": "Hi there",
"two": "Another item",
"three": "Third item"
}
var items = [];
$.each(json_file, function(key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
});
$("<ul/>", {
"class": "json-list",
html: items.join("")
}).appendTo("body");
// Sample extension showcasing manipulation of inserted HTML
$(".json-list #two").css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Obviously, the more complicated your JSON (and desired HTML structure), the more complicated the method of parsing the JSON is going to be.
A templating engine would make your job significantly easier,
and there and hunderds of these. Some of the more popular ones are:
EJS
jQuery.dForm
JQuote2
JSON Template
JTemplates
Mustache
PURE
Tempo
Hope this helps! :)

HTML repetitive blocks

I wish to do the following things:
Insert external html blocks into new html pages
Use the same html header from one html file for a number of pages, without recreating the header again for all the pages
Please help!
You can use HTML Imports which is part of Web Components:
<head>
<link rel="import" href="/path/to/your/file.html">
</head>
If your page does not have to be pure HTML, you should consider using PHP or a similar server-side language.
There are plenty of options, depends on you:
1) use iframes (a lot problems with responsibility) http://www.w3schools.com/tags/tag_iframe.asp
2) ajax call in javascript, load external resource and then print it in placeholder tag (example is with jquery) http://www.w3schools.com/jquery/jquery_ajax_load.asp
3) use some server language/preprocessor (php, ruby, nodejs), depend if you can (need to by installed on server)
4) also there are static page generator, you add marks in your html, and they will compile html with marks to full static html http://hyde.github.io/ for example.
What you are talking about appears to be a process called templating. There are many ways to do this, including writing Javascript to insert pre-written HTML templates into the DOM (the webpage). You might also consider using a pre-written templating library such as http://handlebarsjs.com/ or another library which contains templating functions like http://underscorejs.org/. A simple MVC guide like:
http://blog.ircmaxell.com/2014/11/a-beginners-guide-to-mvc-for-web.html
May be helpful too, to get you started.
In a more practical sense, here's one possible solution:
To begin I would recommend putting the 'blocks' you want to insert in a separate folder. In the website I run, for example, I place them in the \templates folder (or subfolders) but you can more or less call it what you want as long as it makes sense to you. For our purposes let's say we've created block.html and put it in our \templates subfolder...
Now, within each template you will have whatever you want to load in; something like this:
<h2>Title of section</h2>
<p>My text.</p>
Or whatever you'd like. Then, you'll probably want to add an element to your main page which calls some Javascript, which loads your HTML template in when a particular condition occurs. For example, if you wanted to load in our block.html file you might write something like this:
<div id="calling-block" onclick="menuClicked('locationToInsert', 'block')"></div>
Which would call a Javascript function called 'menuClicked()' when we click the div with the id 'calling-block'.
Within the function we would write something like this:
<script>
function menuClicked(insertEl, UrlString, onTemplateLoaded) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById(insertEl).innerHTML = xhttp.responseText;
if (onTemplateLoaded) onTemplateLoaded();
};
};
console.log(UrlString);
xhttp.open("GET", UrlString, true);
xhttp.send();
};
</script>
This is a very simple way of doing things and I'm sure people will tell you there are problems with it, so I would definitely recommend doing your own reading as well, but I hope this covers the very basics.
You need tu use a server side functionality like php, aspx ...

Animating JSON data?

Dumb question time. I was trying to integrate my JSON data with a flipbook plugin, using a Mustache templating system. Needless to say, this wasn't working at all.
I'm a jQuery noobie, so is there any easy way to bind and animate the JSON data to/with a plugin (with or without the Mustache tags)??
From your question it is a bit hard to deduce what you want, but I feel you got already all the pieces together. First the example you have been linking to in a comment: https://github.com/blasten/turn.js/wiki/Making-pages-dynamically-with-Ajax
This fetches not yet loaded pages via Ajax, and the sample code assumes the Ajax call gets HTML back from the server, as can be seen in the code snippet from there (after adding a missing '}':
$.ajax({url: "app?method=get-page-content&page="+page})
.done(function(data) {
element.html(data);
});
Here the done function processes the data it got back from the server by straight injecting it into the element, which is expected to contain the current page.
I assume next that you do have a server side method, but that method returns JSON instead. Let me assume for the moment that it returns the following structure:
{ "title" : "the title of page N",
"text" : "here is some text for the page N." }
The next thing is to render this JSON into into html in the done funktion, before inserting the result into the page. Looking at the short tutorial on the README.md this might look like:
$.ajax({url: "app?method=get-page-content&page="+page})
.done(function(data) {
var pageHtml = Mustache.render("<h2>{{title}}</h2><p>{{text}}</p>", data);
element.html(pageHtml);
});
If the server returns the proper data you should now see a
<h2>the title of page N</h2><p>here is some text for the page N.</p>
appear on the page.

Chrome Extension: DOM traversal

I want to write a Chrome extension that looks at the HTML of the page its on, and if it finds eg <div id="hello"> then it will output, as a HTML list in the popup, 'This page has a friendly div' and if it finds eg I am married to a banana then it will output 'This guy is weird.'
So in other words, searching for specific stuff in the DOM and outputting messages in the popup depending on what it finds.
I had a look at Google Chrome Extension - Accessing The DOM for accessing the dom but I'm afraid I don't really understand it. Then of course there will be traversing the dom and presumably using regex and then conditional statements.
Well that stackoverflow question asked how to let your extension talk to the DOM. There are numerous ways, one way is through chrome.tabs.executeScript, and another way is through Message Passing as I explained in that question.
Back to your question, you could use XPath to search within the DOM. It is pretty powerful. For example you said you want to search for <div id="hello">, you can do it like this:
var nodes = document.evaluate("//div[#id='hello']", document, null,
XPathResult.ANY_TYPE, null)
var resultNode = nodes.iterateNext()
if (resultNode) {
// Found the first node. Output its contents.
alert(resultNode.innerHTML);
}
Now for your second example, same thing ..
I am married to a banana
var nodes = document.evaluate("//a[#href='http://bananas.com']/text()[contains(.,'married')]",
document, null,
XPathResult.ANY_TYPE, null)
var resultNode = nodes.iterateNext()
if (resultNode) {
// Found the first node. Output its contents.
alert('This guy is weird');
}
Well you could use XPath which does work perfectly in Chrome, and you can make your query simple such as finding nodes that you want or even complex with detail. You can query any node, and then do post processing if you wish as well.
Hope that helped. Remember all this should be within a content script in the Chrome Extension. And if you want your extension to communicate to that, you can use Message Passing as I explained in the other post. So basically, within your popup.html, you send a request to the content script to find you text. Your content script will send back a response from its callback. To send the request, you should use chrome.tabs.sendRequest and within the content script.You listen for that request and handle it. As I explained in the other stackoverflow question.
Do NOT use regular expressions to parse HTML. The <center> cannot hold.
With that out of the way... although you can use XPath, I think querySelector is similar in power while being somewhat simpler as well.
You simply pass a CSS selector as a string, and it returns the elements that match the selector. Kinda like using jQuery without needing to load the jQuery library.
Here's how you would use it:
var query = document.querySelector("div#hello");
if (query) {
alert("This page has a friendly div");
}
var query = document.querySelectorAll("a[href='http://bananas.com']");
for (var i = 0; i < query.length; i += 1) {
if (query[i].textContent === "I am married to a banana") {
alert("This guy is weird.");
return;
}
}
document.querySelector finds only a single element, and returns null if that element is not found.
document.querySelectorAll returns a fake-array of elements, or an empty fake-array if none are found.
...however, it sounds like you're wanting to update the browser action popup when something is detected in a webpage, correct? If so, that is possible but immensely more difficult.
Mohamed Mansour's post will get you to the point where you can communicate between content scripts and the background page/popup, but there are other bits that need to be done as well.
Unless the problem is more complex than I think, why not just use jQuery or other convenient js api for this? This is what they were made for - to traverse the dom easily. You can inject jquery and your script that will be using it into required pages in manifest:
"content_scripts": [ {
"js": [ "jquery.js", "script.js" ],
"matches": [ "http://*/*", "https://*/*" ]
}]