Including Information in HTML for Javascript to Consume? - javascript

I'm am building a web app with app engine (java) and GWT, although I think my problem is moreso a general javascript question.
In my application, I want to include a side-menu which is generated from data in my database. This obviously needs to be done dynamically from a servlet.
Currently, I am sending a blank menu container, then making an ajax call to get the information i need to populate the menu. I would rather just send the menu information along in the original request, so I do not need to waste time making a second request. I used this initial approach because it seemed simpler: I just wrote a gwt rpc service that grabbed the data i needed.
My question is, can I instruct a javascript library like gwt to look for its information in the current web page? Do I have to hide this information in my original HTML response, maybe in a hidden div or something?

If the data that you'd like to embed is restricted to menu items, why not directly generate lightweight HTML out of simple <ol> and <li> elements? You can still keep HTML out of your Java code by using a template engine. The menu markup could just be styled with CSS or if you need something fancier than mere <ol> and <li> elements, you can massage the DOM with JavaScript once the page loads (read: progressive enhancement).
If you're looking for a more generic solution, beyond the menu case, then you could embed a JSON block in your page, to be consumed when the page loads for the dynamic generation of your menu.
Or, you could look into using a microformat that is suitable for menu data.

You can include a script block in the original response defining the data and then use an onload event (or similar) to create the menu based on that data; that's very similar to what you're doing now, but without the extra trip to the server. I'm assuming there that the data to construct the menu is transformed in some way by JavaScript on the client; otherwise, just include the menu markup directly.

GWT has something called JSNI (Javascript Native Interface) that can interface with other non-GWT Javascript. So, you could in your HTML page container have a containing the generated menu items as a Javascript object. Then, in your GWT code, you have a JSNI call to fetch this data and put it in the right place in your UI/DOM with GWT methods.

I asked a similar question a few weeks ago about how to store data safely inside HTML tags. It also contains a few links to other questions. Here

There are in general 2 options:
Store the data in some xml tags somewhere in the html code and later get the information from there by traversing through the DOM. (you can hide them with css)
Store the data as JSON data in a script tag. (There en- and decoders for nearly every language)
var data = { "foo" : "bar", "my_array":[] };

Related

How do I change my controller so it is decoupled enough from my view?

I'm programming a web app using Spring MVC where I need to create some elements that I cannot create directly through jsp. Specifically all of those that list values that I get from my database, since I cannot create a structure in jsp before knowing its size. Here's how I'm doing it right now:
#RequestMapping(method = RequestMethod.GET)
public ModelAndView getAllEjercicios (...)
...
Table table = new Table("table_ejercicios", "table_ejercicios", new ArrayList<TableHead>(Arrays.asList(tH1, tH2, tH3)), getEjercicioTableContent(ejercicioList));
...
model.put("table", table.getCode());
return new ModelAndView("ejercicio/ejercicio-list", MODEL_NAME, model);
This is my controller method, where Table is a custom class that I created that will return the html code of the table when calling getCode(), using the parameters it was given. The problem with this is that I'm starting to see my Controller is not decoupled enough, since it's passing the view the HTML code of the entire object instead of just the parameters I need in order to build it in my jsp file. Btw, this is not just an issue with this particular table, I have other dropdown lists and things as such in my code.
The problem is that if I use a javascript function which receives the same parameters as my table inside the jsp, I'll have to replicate a lot of code in other views that use similar tables, since I'll have to copy the entire javascript function in each jsp file.
My code works perfectly, it's not a problem of it not working, it's a problem of structure.
What should I do, should I keep my code as it is, or is there a solution I'm not thinking of?
Thanks
The html pages, contains lots of elements, such as tables, forms, dropdown,... . If you generate all UI elements in the backend, your server side code will full of client side coding! This is not a good practice as you already know.
I think the best practice is rendering html pages without any extra UI elements, just html code with data. You can even exclude data from page and fill html elements with data from ajax request. However, your controller will completely free from UI codes. With this approach, your concern is duplication of codes in the client side. This can be solved with generating javascript utilities. For example, you have same html table structure in multiple pages. For doing this, you can write a javascript function for generating table. This function can take some parameters and add dynamic table to every page you need. You can do similar works for other elements such as forms and dropdown.

Get data from another HTML page

I am making an on-line shop for selling magazines, and I need to show the image of the magazine. For that, I would like to show the same image that is shown in the website of the company that distributes the magazines.
For that, it would be easy with an absolute path, like this:
<img src="http://www.remotewebsite.com/image.jpg" />
But, it is not possible in my case, because the name of the image changes everytime there is a new magazine.
In Javascript, it is possible to get the path of an image with this code:
var strImage = document.getElementById('Image').src;
But, is it possible to use something similar to get the path of an image if it is in another HTML page?
Assuming that you know how to find the correct image in the magazine website's DOM (otherwise, forget it):
the magazine website must explicitly allow clients showing your website to fetch their content by enabling CORS
you fetch their HTML -> gets you a stream of text
parse it with DOMParser -> gets you a Document
using your knowledge or their layout (or good heuristics, if you're feeling lucky), use regular DOM navigation to find the image and get its src attribute
I'm not going to detail any of those steps (there are already lots of SO answers around), especially since you haven't described a specific issue you may have with the technical part.
You can, but it is inefficient. You would have to do a request to load all the HTML of that other page and then in that HTML find the image you are looking for.
It can be achieved (using XMLHttpRequest or fetch), but I would maybe try to find a more efficient way.
What you are asking for is technically possible, and other answers have already gone into the details about how you could accomplish this.
What I'd like to go over in this answer is how you probably should architect this given the requirements that you described. Keep in mind that what I am describing is one way to do this, there are certainly other correct methods as well.
Create a database on the server where your app will live. A simple MySQL DB will work, but you could use anything. Create a table called magazine, with a column url. Your code would pull the url from this DB. Whenever the magazine URL changes, just update the DB and the code itself won't need to be changed.
Your front-end code needs some sort of way to access the DB. One possible solution is a REST API. This code would query the DB for the latest values (in your case magazine URLs), and make them accessible to your web page. This could be done in a myriad of different languages/frameworks, here's a good tutorial on doing something like this in Node.js and express (which is what I'd personally use).
Finally, your front-end code needs to call your REST API to get the updated URLs. This needs to be done with some kind of JavaScript based language. jQuery would make this really easy, something like this:
$(document).ready(function() {
$.Get("http://uri_to_your_rest_api", function(data) {
$("#myImage").attr("scr", data.url);
}
});
Assuming you had HTML like this:
<img id="myImage" src="">
And there you go - You have a webpage that pulls the image sources dynamically from your database.
Now if you're just dipping your toes into web development, this may seem a bit overwhelming. But I promise you, in the long run it'll be easier then trying to parse code from an HTML page :)

Easiest way to get data from single file and inject into 4 HTML pages

I have a static web page for a restaurant. The menu changes twice a year. Site is bi-lingual.
I want to know what would you recommend to achieve such effect -
I want to change one (not four like now) file (could be text, JSON, whatever) and see results on those pages - two pages in one language should be updated, and two in the other. I don't want to mess with CMS of any kind (I'm a front-end developer and don't want to get into SQLs/PHP and such). I thought maybe jQuery or AngularJS could do that? But how?
The file itself could be something like that:
en_Tea | de_Tea
en_sandwich | de_sandwich
en_pizza | de_pizza
or JSON of some kind...
You could do something like add a stub .js file that gets imported to your full page files. In the stub file, you could simply have a function that builds a constant array with whatever values you like. The calling portions of your code could then use the values however they would like.
Check jQuery Ajax functions & methods
Some you could use:
$.ajax() - the most configurable one.
.load() - adds functionality which allows you to define where in the document the returned data is to be inserted.
$.get() - abstracts some of the configurations away, setting reasonable default values for what it hides from you.
Most are shorthands for $.ajax()
You can make these requests when certain elements are clicked and bring/replace specific content without having to refresh the whole page.

How Should I Send HTML/CSS Content To A Server?

The Situation
I have to create a web-application that allows me to, starting from a blank page, insert new html, images and so on, and allows to edit it with features like: resize, positioning and so on.
To figure out what I'm talking about, see: https://www.scrollkit.com in its editor section.
My Question
How should I save the new html I create, with the CSS bound to it, to my server?
Should I use a JSON structure in which I put all my elements with something like:
{
attributes: "",
tag: "div",
html: "some-html",
..
}
Or should I save the entire (maybe "compiled"?) html page to the file-system?
Thanks in advance to all.
I see this as an architecture question more then a code question, especially since the asker didn't specify what server side technology they are using or are comfortable with.
Here is how I would design this:
I'd have a div where all the content would go inside. I'd optionally have a style element (with an id) that all my custom css would be written into. I'd simply save the contents of the div and css style to the server, using ajax, when various things happened (user hit save button, perhaps auto-save every so many minutes, etc), and reload it when needed (on page load, reset button, maybe undo, etc.).
Hopefully, I'd be able to build all my insert/resize/position code to work just off of html. If I needed to, I'd put data- elements on my html to store information I needed to make all my manipulation work. I'd strongly hesitate to have a duplicate JavaScript structure in memory for all my elements, because it seems that nightmares could happen if they get out of sync. However, if you have to do so, I'd also save that to the server and reload it. I'd find a way to rebuild either the structure or the data- attributes if they don't exist.
That's a good enough start, I think. Feel free to ask questions.
I'd recommend using XML+XHTML. Browsers can render XHTML just as well as HTML, but unlike with HTML, XML processing rules allows namespaces so the browser will just ignore unrecognized elements and attributes as long as you put them in a separate namespace. Your editor can use namespaced elements and attributes to store editor metadata that wouldn't be in the compiled HTML.
Creating an HTML editor is a very complicated task. I would use one of existing controls that is actively maintained. But if you insist, you can use JSON and post the HTML and CSS data to an endpoint, then save it to a file or database. I don't believe keeping a node by node structure is necessary.
So, you could try the following:
(I assume, you're using an <iframe/> for this HTML editor)
var data,
// since we're editing within an iframe,
// we'll get the iframe document to access HTML data
iframe = document.getElementById('editor-iframe'),
editorDoc = iframe.contentDocument || iframe.contentWindow.document;
// gathering post data from the edited document
data = {
// get the full html from the editor document
html: $(editorDoc).find('html').get(0).outerHTML,
// since the user is editing a file on the fly, you can
// have a <style> element within the head and modify it when
// user edits the file. So we can get the style contents
// and store it separately here.
css: $(editorDoc).find('head style').html(),
// add some extra metadata here
metadata: {
user: 'onur'
}
};
// finally, posting the data to the endpoint when the
// user clicks a "save" button. And you should also auto-save
// periodically to prevent data loss.
$.post('/saveFile', data);
Here is a demo fiddle.
When I implementing something like this I saved the raw html as XML then I parsed the page accordingly.
To be more clear I used various xml blocks for different items eg:
<xml>
<html>
</html>
<css>
</css>
</xml>
Just build the structure you need. Hope this helps
This is how I'd do it to keep things simple:
{
filelist: [
{
filename: "style.css",
contents: ""
},
{
filename: "index.js",
contents: ""
},
{
filename: "index.html",
contents: ""
}
]
}
If it's pure HTML, I would just keep it as one string when passing to the server and use an iframe on the client side to preview it. This would make loading simple and you can just manipulate the HTML using the DOM when sent to the client. Is there a particular reason you would need the HTML tags in any other format? I suppose if you wanted to implement some kind of content management system with re-usable blocks, you would want to change things up a bit.
Steo, when you are developing an application which has a feature to insert HTML, make sure you have a good control to avoid persistent/non-persistent XSS attacks.
If the HTML/CSS depended features are manageable, I would recommend you to go with JSON storage with proper server side validation, which may help you to keep your model clean and no technology dependent. So that you can parse the JSON and develop your application for mobile, tablet etc., later.
Having an array of JSON objects(CONFIG) copy will also help the application with undo or redo operations, which will be an important feature when working with editor.
Good luck! :-)
With html5 i think it's simple http://www.w3schools.com/html/html5_webstorage.asp

Generate an HTML table from a Word Document

I'm putting together a simple website for our department. I'd like to include one of the references that we use often on the main page, a word document that contains a priority list for outstanding work. This document is generated by another department and located on a shared drive. The info is not in a table, but uses a fairly consisten format for displaying info.
Ex: (the info is actually formatted like this)
--------------
Item Title
--------------
Tracker#: 12345-0012 Due; 01/01/12
Description...
My ultimate goal is to have a table on the main page that contains the various items in the priority list. I would like a mechanism that automatically checks the word docs about once an hour, parses the document, generates a table from the info in the doc, and updates the main page accordingly.
I've never done anything like this and have no idea where to start or if what I'm asking is even possible. I'm not in IT and do not have the ability to use ASP or PHP at the moment. So I'd like to avoid server-side scripting if possible, but I may be able to work something out if absolutely necessary.
Thanks
I know how to do this in java.. you can use the docx4j library.. Without that it would be difficult. Can't the team that create the doc store the file as a flat file as well maybe?
One possible solution is to save document as html (using automation - create Word.Application object, call Open, SaveAs) and serve it directly or inside frame.

Categories

Resources