A good way to pass information javascript? - javascript

I have an asp.net website, but I need to pass stuff to javascript to do stuff there. At the moment, I am doing things like this:
<script type="text/javascript">
var userHasMicrositePhoto = '<%=hasMicrositePhoto%>';
</script>
But I've been told that putting lots of script tags in like this is bad, and also its annoying to have to keep writing Properties in my code behind.
What is a better way to do this?

This is pretty much the ideal way to go IMO. If you have a lot of stuff like this, try putting it all in one <script>block. You could also use an array to reduce the code overhead, or have asp.net output a JSON encoded array with all the needed properties in it.
Depending on your architecture, you could consider fetching those properties through a separate Ajax request which would make the page body a bit cleaner, but it would be an extra request that can't be cached, so I would use this only in very extreme cases.
The same applies to embedding a separate <script src=....> it looks nicer in the generated markup, but needs another request to the server.

The only alternatives would be
write a page that generates AJAX and have your JavaScript access
that with XHR
write a page that generates JavaScript and have your
HTML access that with a single script tag
I don't think either of those solutions are obviously superior to what you're doing now, except they could be used by other pages more easily, if that helps.

I would use JSON when you're passing information to be used by javascript.
This may require you to reconsider how you're developing your website or application. I usually use it when the server is passing information via ajax but ajax isn't the only solution.
http://code.google.com/p/aspjson/
http://www.json.org/
I may not quite understand your question though so forgive me if I am totally off.

Related

Duplicate an HTML file (and its content) with a different name in Javascript

I have an HTML file with some Javascript and css applied on.
I would like to duplicate that file, make like file1.html, file2.html, file3.html,...
All of that using Javascript, Jquery or something like that !
The idea is to create a different page (from that kind of template) that will be printed afterwards with different data in it (from a XML file).
I hope it is possible !
Feel free to ask more precision if you want !
Thank you all by advance
Note: I do not want to copy the content only but the entire file.
Edit: I Know I should use server-side language, I just don't have the option ):
There are a couple ways you could go about implementing something similar to what you are describing. Which implementation you should use would depend on exactly what your goals are.
First of all, I would recommend some sort of template system such as VueJS, AngularJS or React. However, given that you say you don't have the option of using a server side language, I suspect you won't have the option to implement one of these systems.
My next suggestion, would be to build your own 'templating system'. A simple implementation that may suit your needs could be something mirroring the following:
In your primary file (root file) which you want to route or copy the other files through to, you could use JS to include the correct HTML files. For example, you could have JS conditionally load a file depending on certain circumstances by putting something like the following after a conditional statement:
Note that while doing this could optimize your server's data usage (as it would only serve required files and not everything all the time), it would also probably increase loading times. Your site would need to wait for the additional HTTP request to come through and for whatever requested content to load & render on the client. While this sounds very slow it has the potential of not being that bad if you don't have too many discrete requests, and none of your code is unusually large or computationally expensive.
If using vanilla JS, the following snippet will illustrate the above:
In a script that comes loaded with your routing file:
function read(text) {
var xhr=new XMLHttpRequest;
xhr.open('GET',text);
xhr.onload=show;
xhr.send();
}
function show() {
var text = this.response;
document.body.innerHTML = text;//you can replace document.body with whatever element you want to wrap your imported HTML
}
read(path/to/file/on/server);
Note a couple of things about the above code. If you are testing on your computer (ie opening your html file on a browser, with a path like file://__) without a local server, you will get some sort of cross origin request error when trying to make an XML request. To bypass this error, either test your code on an actual server (not ideal constantly pushing code, I know) or, preferably, set up a local testing server. If this is something you would want to explore, its not that difficult to do, let me know and I'd be happy to walk you through the process.
Alternately, you could implement the above loading system with jQuery and the .load() function. http://api.jquery.com/load/
If none of the above solutions work for you, let me know more specifically what it is that you need, and I'll be happy to give a more useful/ relevant answer!

How to load large JSON file into javascript

Firstly, thanks for taking time to view my post. I am working on a project with a few people, and we basically have a webpage, and once you log in, it displays all the data from a mysql database which has 6 tables, 3 of which have data in them. We figured out that in order for us to go about this, we need to transfer data by exporting the data into JSON file(s), then from there load the JSON files into java script so it can communicate with the web server. We were wondering what would be the best way to go about this. One way we found out is to reference the JSON ddata as variables and just list everything out, but several of our files have loads and loads of data. Would there be an easier approach?
This would be the first time we are doing something like this, so we are learning and appreciate your feedback!!
If you're using some kind of AJAX library, you can easily request the .json file from the browser.
For example with jQuery:
$.post("ourJSONFile.json", function( data ) {
..logic to display data..
});
NOTE - The comment about no PHP was not posted while I was writing this. Until I know why there can be no PHP, I'm just going to leave this answer here.
I think you're going at this in the wrong way. There is no need for JSON here, just query your database for the information.
The overview of what you need to do is (in PHP or the language you use to talk with your server) you need to
connect to the database
query database for information (query in your case, more or less means get the information)
do something with the returned information (such as echoing it in PHP so it will go to the user)
Now, it doesn't look like there is much effort place for getting this done, only planning. So, I'll just show you a few links to read up. (Which is also why people has devoted your question, Stackoverflow doesn't like asking question with no effort to research answers)
I'd use php.net for looking up methods, such as the mysqli_query method. This is very useful for learning small but important things about the method, like what it returns when an error occurs.
http://php.net/manual/en/mysqli.query.php
Taking a quick look through this guide, I think it should suffice. Besides syntax and such, some other important points are use MySQLI (when using PHP 5 or higher) and use prepared statements.
http://www.pontikis.net/blog/how-to-use-php-improved-mysqli-extension-and-why-you-should
The use of prepared statements is to protect your queries from injections. w3schools gives a good explanation about this # http://www.w3schools.com/sql/sql_injection.asp
MySQLI is MySQL Improved, it is more secured and supported. MySQL has been deprecated since PHP 5, and php.net pages on a MySql method will actually say this at the very top.
Finally, Andrew mentioned AJAX. AJAX is (for example) a way of doing things that would normally require reloading the page, without reloading the page. There is more to that, and I would recommand looking into it once you get use to the languages you are using.
Note, AJAX does not require libraries to use, it can be done with pure javascript. Libraries simply (as seen around) simplify AJAX a lot.

Spring MVC - Is JSTL Tag JSON Conversion OK?

A psuedo controller method
#RequestMapping("/foo")
public String getFoo(Model model) {
model.add("foo", repo.findFoo());
model.add("bar", repo.findBar());
model.add("barOptions", repo.findBarOptions(bar));
return "fooView";
}
Let's say the client uses Expression language to render foo and bar; but we use JavaScript to render barOptions.
<html>
<script>
var options = <mytag:toJSON object="${barOptions}"/>;
$("#options").renderOptions( options );
</script>
<body>
<mytag:renderFoo foo="${foo}"/>
<mytag:renderBar foo="${bar}"/>
<ul id="options"></ul>
</body>
</html>
Common conventions tells me this is bad. But the essence of MVC, where the controller sends data and the view determines how to use it, tells me this is good. Is there a better way to do the same thing? Is there any reason why this isn't commonly done? I could request the JSON using a separate call, but then I have to make more requests for the page to load, and there may be logic to determine barOptions in the controller method getFoo() based on other input at the time of the page load.
At first glance I can not say that I see anything blatantly wrong with approach. The only aspect that initially took me off guard was your need to convert data in the model object to json.
For me, JSON usually implies that there is some sort of server side object that needs to be converted so that a client side javascript can access or manipulate its structure in a javascript way. I guess without knowing more of the purpose of the options list, I can't see a reason why json serialization is required here.
By using a Tag to convert a model object to JSON, we avoid an
additional request made by the client
But if we assume that JSON is a requirement (perhaps for some third party jquery plugin), then I absolutely do not see anything wrong with approach.
What is special or different about the barOptions unordered list, why does it have be rendered with json? Why not just use a for loop to build the list items? Or you can have a custom tag that builds out the ul entirely.
Aside from that, I missing the point as how one may perceive this as being bad code.
Normally JSON is requested by JavaScript with an Ajax call, but if in your case it's available at page rendering time, I see nothing wrong with your solution. It's clean, compact code and easy to read. Looks perfectly OK to me, the alternative would be to loop on the options array with a forEach, but this approach looks better.

How do you organize your Javascript code?

When I first started with Javascript, I usually just put whatever I needed into functions and called them when I needed them. That was then.
Now, as I am building more and more complex web applications with Javascript; taking advantage of its more responsive user interaction, I am realizing that I need to make my code more readable - not only by me, but anyone who replaces me. Besides that, I would like the reduce the moments of 'what the heck, why did I do this' when I read my own code months later (yes, I am being honest here, I do have what the heck was I thinking moments myself, although I try to avoid such cases)
A couple weeks ago, I got into Joose, and so far, it has been good, but I am wondering what the rest do to make their chunk their codes into meaningful segments and readable by the next programmer.
Besides making it readable, what are your steps in making your HTML separated from your code logic? Say you need to create dynamic table rows with data. Do you include that in your Javascript code, appending the td element to the string or do you do anything else. I am looking for real world solutions and ideas, not some theoretical ideas posed by some expert.
So, in case you didnt't understand the above, do you use OOP practices. If you don't what do you use?
For really JS-heavy applications, you should try to mimic Java.
Have as little JS in your HTML as possible (preferably - just the call to the bootstrap function)
Break the code into logical units, keep them all in separate files
Use a script to concatenate/minify the files into a single bundle which you will serve as part of your app
Use JS namespaces to avoid cluttering up the global namespace:
var myapp = {};
myapp.FirstClass = function() { ... };
myapp.FirstClass.prototype.method = function() { ... };
myapp.SecondClass = function() { ... };
Using all these techniques together will yield a very manageable project, even if you are not using any frameworks.
I use unobtrusive javascript, so, outside of the script tags I don't keep any javascript in the html.
The two are completely separated.
A javascript function will start when the DOM tree is completed, which will go through the html and add the javascript events, and whatever else needs to be changed.
In order to organize, I tend to have some javascript files that are named similar to the html pages that they use, and then for common functions I tend to group them by what they do, and pick a name that explains that.
So, for example, if I have UI functions then I may call them: myapp_ui_functions.js
I try to put the name of the application in the filename, unless there is some javascript that is common to several projects, such as strings.js.
I have (usually) one file that contains a bunch of functions and that's it. That is included in every page that uses Javascript. In the pages themselves, I'll make the calls to the functions like:
$(function() {
$("#delete").click(delete_user);
$("#new").click(new_user);
});
where delete_user() and new_user() are defined in the external file.
I too use unobtrusive Javascript, which for me means jQuery (there are other libraries that are unobtrusive).
You don't want a separate file for each page. That just means more unnecessary external HTTP requests. With one file—assuming you've cached it effectively—it'll be downloaded once and that's it (until it changes).
If I have a large amount of Javascript or the site is effectively split into multiple areas then I may split the Javascript but that's not often the case.
Also, in terms of my source code, I may have multiple JS files but I'll often end up combining them into one download for the client (to reduce HTTP requests).
More at Multiple javascript/css files: best practices? and Supercharging Javascript in PHP.
I've been rewriting a lot of my reusable code as jQuery plugins. I moved to jQuery from Prototype when I started doing ASP.NET MVC. Overtime I've migrated a lot my reusable code, or at least the ideas, from Prototype-based OO to jQuery-style plugins. Most of these are stored in their own JS files (mainly intranet apps so page load speed is pretty high anyway despite the extra requests). I suppose I could add a build step that coalesces these if I needed to.
I've also settled on a MasterPage approach that uses a ContentPlaceHolder for scripts that is right before the closing body tag. The standard jQuery/jQuery UI loads, and any other common JS goes right before the script placeholder in the MasterPage. I have tiny bit of JS at the top of the MasterPage that defines an array that holds any functions that partial views need to run on page load. These functions are run from the base document.ready() function in the MasterPage.
All of my JS is completely separate from my mark up. Some JS may exist in partial views -- these are encapsulated when the partial may be included more than once to make it specific to that instance of the view -- but generally not. Typically only included in the placeholders so that it's loaded at the bottom of the page.
Also, if you want to go OO heavy, check out mochikit: http://www.mochikit.com/
I find that developing your javascript using OO methodology is the way to go if you want it to be clean, readable and even somewhat secure. I posted the following question
Cleanest format for writing javascript objects
And got some fantastic responses on how to write my javascript code well. If you follow these basic principles you can use almost any library, such as yui, jquery and prototype, with ease.

Creating new html in JS or ajax loading a html layout?

I have a page where I need to create a large amount of HTML that's not already present in the page.
Using jQuery I've been building the page with JS piece by piece, adding divs here and there, etc, until I get my layout.
Right now I'm thinking rather than do all that in JS, I can create the layout in a separate HTML file and then load it with ajax. My initial aversion to that idea is because of ajax, it requires an additional server request, and might end up slow(er?).
Anyone have any advice on whether or not this is a good idea, and if it is, if there are tutorials, set ways and patterns to doing this sort of thing.
Thanks.
There may be a speed impact from making another round-trip to the server. However, I think that the readability/maintainability you gain from having all of your HTML in a separate template, rather than mixed in with your JS is the big win here. You won't have to deal with quote issues, entity encoding, all of that. And the code that you do have will be easier to debug.
I'm not aware of any specific tutorials on this, but with most of the AJAX libraries out there, it's easy to make an XHR request and pipe the response into a DIV. For example, see Prototype's Ajax.Updater(container, url[, options]) function. ( http://www.prototypejs.org/api/ajax/updater )
The issue you'll get is not slower, but your URLs will be a little messed up.
If you navigate from page to page your URL won't update easily. You CAN do it but it can be a lot of work.
I've used post's callback function to display the data from the post with good effect and it's fast.
Good luck with it!
edit: I was talking about jQuery's post function.
2nd edit: If you're going to vote me down guys, at least say why...

Categories

Resources