Passing parameter map (list of values) to JQuery - javascript

to initialize a javascript loaded grid, I need to pass a list of values from controller/gsp. Since the javascript is activated once the page is rendered/loaded, there may not be a direct way to do it. 2 possibilities
1. do an ajax call, and retrieve the list of values from the server
2. store the list in html as a hidden element, and read it from javascript.
option 2 seems better as it avoids few calls back to server. So, which control should I use for a list of values? Any jQuery code snippet to read it back into array/list.
thanks in advance.

It depends on the size of that data. It it's small enough, you could embed it in the page. For example, to populate a calendar with events, I used something like:
<div id="calendar" data-events="[/* event list */]"></div>(the data-events attribute contained a JavaScript array of event objects in JSON format)
However, if you're talking about a huge amount of data, loading it (possibly in chunks) asynchronously after the page load (or when the document is ready) could increase your app's performace and make it more interactive (i.e. I don't want to wait and load that data if the next thing I'm gonna do is navigate away)
Does that answer your question?

You can directly write JavaScript from the server side. I don't know about grails, but here's a very simple example in php:
<script type="text/javascript">
var someVar = "<?php echo $someServerVar;?>";
</script>
Sure, this example is very simple, but you get the idea. And most languages will have some sort of function that escapes JavaScript strings (basically turn " into \" and new lines into \n).
If you put a script like that at the top of your <head>, then those variables will be accessible from all other scripts on the page.

Related

fluid template: passing a javascript varible as the argument value?

For a f:link show action in my fluid list template i want to pass a javascript variable to the arguments, basically the uid (to pass that specific object to the showAction), but it doesn't work the way i intend to do it. Is there a workaround for this particular problem?
The naked template looks like this:
<f:for each="{termins}" as="termin">
<tr>
<td><f:link.action action="show" arguments="{termin : termin}"> {termin.mitarbeiter}</f:link.action></td>
<td><f:link.action action="show" arguments="{termin : termin}"> {termin.kunde}</f:link.action></td>
</tr>
</f:for>
</table>
You can't - and you also can't (read: never should) generate links to controller actions from JS since it needs to generate a security checksum. Modifying the URL you create will generate a security error. The checksum exists to prevent DDOS so it has good reason.
There are two options:
You can generate all links in advance
You can make a link-generating service that you call with XHR to generate the necessary links from JS.
Only the first one is appropriate to your use case. Especially so since you want to pass UID values which always refer to an object in the database - which means you can easily generate a list of links to all possible detail views, then read/pass that list of links from your JS to select the right one.
The JS is something working after the fluid template. The right order is, your fluid template is parsed into the HTML, and then the browser render the HTML/JS/CSS to you. So, you can not expect to use JS value in your fluid template.
There are 2 possibilities:
1) Instead of a link use a form and transmit it via POST. Set a form field dynamically with JavaScript. That way your variable isn't included in the (cHash-) checksum.
2) Create an AJAX action that accepts your variable as argument. Let it generate a valid link. Use POST to call it with your variable data. Show the link on your page with JavaScript.

Pushing HTML to a web page (JS VS PHP)

I was just curious about the title because I have been using PHP to load up my search results with HTML, and now I have started to use javascript for this purpose.
Previously I was doing the following on my website to load search results on a page
<?php
//example code
echo ' <div class = "container">
<div class = "box"> <p> Searh result e.g foo bar </p> </div>
</div>'
?>
Now the above would work when I called an ajax function to post the search text to the PHP page, and the page would return all the matched results along with HTML, and the jQuery would push the result on my page
What I am doing right now is I am posting the search text via ajax to a PHP page but this time instead of returning all the search results packed in HTML tags, it return a JSON type array with only data in it
Now when I receive this data array from PHP I send it to a custom (self-made) javascript function that iterates through the array and generates the HTML as following (e.g.)
for (myData in data)
{
results+='<li>'+
'<div class="row">'+
'<div class="col-xs-12 col-sm-9 no-margin">'+
''+data[myData].name+''+
'<div class="price">'+
'<div class="">'+data[myData].price+'</div>'+
'</div>'+
'</div>'+
'</li>';
}
In the end, the variable results has all the HTML along with data which is then pushed to the page via jQuery append.
So in the first method all the work is being done on the server side and it is returning a huge amount of data because of the HTML tags which will be multiplied by the number of results returned
While in the second method the server will only return a JSON type array of data
and the rest of work will be done on the client side. So The question is, Is the second method better than the first one in any way or not?
Thanks in advance
Both approaches are equally valid, but there are a couple things to consider for each approach:
PHP
It works even if the user has JavaScript disabled
JavaScript
Processing is offloaded to the client, putting less load on your servers.
The actual amount of load is going to be negligible since the only "processing" is building HTML
Less traffic, but if your server is compressing the response (it likely is), then this isn't really a noticeable difference.
Faster, more responsive page if you're using ajax, since it doesn't have to reload the entire page.
Doesn't work if the user has JavaScript disabled.
In the end, I'd go with JavaScript unless you know you have a lot of users who disable it.
Ideally you would have a no-JS fallback where PHP creates the HTML.
When you're talking about small simple website, do what you like...
When it comes to more complex applications you must to separate your data from presentation. So the right way, I think, will be to use templates at first.
Then, you can choose the side:
Client side will be better, when using some framework or your application HTML changes instantly. You get the data you need and render it on client. Using template engine.
Server side may be good if you need to build large amount of HTML with some difficult logic and need it once or twice...
Also you can use the same template engine for both sides, so you can combine.
I think, it's always about the combination of ways, so prepare your app for both.
(Maybe designing from the start for REST)
P.S. It may help: Sharing Templates Between PHP and JavaScript
Not an actual answer... but they're both pretty bad :-/ Why not look at something like Knockout.js. You could just update your view model with the "json type array with only data in it" and you're view updates as if like magic ;-)
Just sayin!

Is it good to return html code to jquery?

I'm working on a project where it has a number of pages. Each page displays 10 rows where the layout that is using for each page is different. Until now I had the html code of each row in a javascript code and based on the page's url I was using the appropriate html code (if statement). The if statement is inside into a loop which is looping based on the number of rows. The results of the rows are coming from an ajax method. Now I want somehow to separate it so it can be more easily for me to maintain it, basically to remove the html code from the javascript and keep each row's html code into a different file.
Note: the Ajax is in a given time, is sending automatically requests to the php file for any new rows.
One solution which I came out is that I can use the php to create a variable with the html code .
Second solution is to create an array of each record with the html code and then pass it to jquery to print it.
Both solutions I don't know if are good solutions and can help me to maintain the project in the future.
You might consider a template library such as handlebars to help with templating. Frameworks such as AngularJS and Ember also excel at solving these kinds of problems.
Your Web Services API should be returning JSON though, not HTML fragments. Let the client build the DOM, and let the server focus on data.
You should return structured data (see JSON for example) to your AJAX request. This way, you can support multiple interfaces (e.g., a website, an application): each interface will get only the data, and will handle the rendering as it needs.
In your example, you ask for data via an AJAX request, your server responds with a JSON-structured response. JQuery reads it and converts it to javascript array thanks to jQuery.getJSON. With your array, you loop through each element and insert html elements into the webpage.
You have two options:
If your HTML templates is not changing frequently, the best way is to define html templates in your HTML structure using some java script template library (eg. Handlebars) and fill it with data from your AJAX (JSON) requests.
If your HTML templates change frequently or depends on some conditions (data) in row, you should create PHP partial views which generate proper html structure already filled with data.
For many rows it is better idea to create whole table server side to reduce requests.

How do I load an mbox content without inserting into the dom

I'm trying to interface with Adobe Test & Target because I want to load JSON rather than markup through my mbox. I want to load some mbox content into javascript and manually add it to the DOM. I have searched all over for full documentation of the mbox.js but I can't find anything other than the very basics. It describes how to use mboxDefine() and mboxUpdate to target a specific dom element. Is there a function that just returns the content?
```
T&T does not offer a function to assign the response to a javascript variable. Basically the way it works is mbox.js builds a url to their server and then then outputs a script include tag. This is done to get around the same origin policy limitations (cross-site scripting).
In order to handle whatever is in the html offer, they put it in their own javascript variable on their server and then output it as that as the response. However, they also have the response output the code that updates the target element. So there's nothing you can do to actually stop them from updating the target element with the html offer contents. They simply don't expose that.
However, you don't have to put html in an html offer. You can put json (javascript) in an html offer. Just do like
html offer 'myJsonMbox' (in interface)
<script type='text/javascript'>
var myJsonString = "[json string]";
</script>
Then on your page (inside your body tag, but before your code that wants to use it) you'd have the regular mbox code:
<div class='mboxDefault'></div>
<script type='test/javascript'>
mboxCreate('myJsonMbox');
</script>
And then somewhere after that, where you're wanting to do something with it, that myJsonString is there for you to reference. Or, you can do it with the mboxDefine and mboxUpdate sometime after page load, if you prefer.
Is there some particular reason why you don't think this will work for you?
You can:
a- Insert JS code you are going to use to manually manipulate the DOM
b- Insert CSS code you can use to alter the original HTMl or the newly added HTML.
c- Insert a call to a 3rd party script that will load content from a 3rd party server if needed, or the same server.

Generating HTML in JavaScript vs loading HTML file

Currently I am creating a website which is completely JS driven. I don't use any HTML pages at all (except index page). Every query returns JSON and then I generate HTML inside JavaScript and insert into the DOM. Are there any disadvantages of doing this instead of creating HTML file with layout structure, then loading this file into the DOM and changing elements with new data from JSON?
EDIT:
All of my pages are loaded with AJAX calls. But I have a structure like this:
<nav></nav>
<div id="content"></div>
<footer></footer>
Basically, I never change nav or footer elements, they are only loaded once, when loading index.html file. Then on every page click I send an AJAX call to the server, it returns data in JSON and I generate HTML code with jQuery and insert like this $('#content').html(content);
Creating separate HTML files, and then for example using $('#someID').html(newContent) to change every element with JSON data, will use even more code and I will need 1 more request to server to load this file, so I thought I could just generate it in browser.
EDIT2:
SEO is not very important, because my website requires logging in so I will create all meta tags in index.html file.
In general, it's a nice way of doing things. I assume that you're updating the page with AJAX each time (although you didn't say that).
There are some things to look out for. If you always have the same URL, then your users can't come back to the same page. And they can't send links to their friends. To deal with this, you can use history.pushState() to update the URL without reloading the page.
Also, if you're sending more than one request per page and you don't have an HTML structure waiting for them, you may get them back in a different order each time. It's not a problem, just something to be aware of.
Returning HTML from the AJAX is a bad idea. It means that when you want to change the layout of the page, you need to edit all of your files. If you're returning JSON, it's much easier to make changes in one place.
One thing that definitly matters :
How long will it take you to develop a new system that will send data as JSON + code the JS required to inject it as HTML into the page ?
How long will it take to just return HTML ? And how long if you can re-use some of your already existing server-side code ?
and check how much is the server side interrection of your pages...
also some advantages of creating pure HTML :
1) It's simple markup, and often just as compact or actually more compact than JSON.
2) It's less error prone cause all you're getting is markup, and no code.
3) It will be faster to program in most cases cause you won't have to write code separately for the client end.
4) The HTML is the content, the JavaScript is the behavior. You're mixing both for absolutely no compelling reason.
in javascript or nay other scripting language .. if you encountered a problem in between the rest of the code will not work
and also it is easier to debug in pure html pages
my opinion ... use scriptiong code wherever necessary .. rest of the code you can do in html ...
it will save the triptime of going to server then fetch the data and then displaying it again.
Keep point No. 4 in your mind while coding.
I think that you can consider 3 methods:
Sending only JSON to the client and rendering according to a template (i.e.
handlerbar.js)
Creating the pages from the server-side, usually faster rendering also you can cache the page.
Or a mixture of this would be to generate partial views from the server and sending them to the client, for example it's like having a handlebar template on the client and applying the data from the JSON, but only having the same template on the server-side and rendering it on the server and sending it to the client in the final format, on the client you can just replace the partial views.
Also some things to think about determined by the use case of the applicaton, is that if you are targeting SEO you should consider ColBeseder advice, of if you are targeting mobile users, probably you would better go with the JSON only response, as this is a more lightweight response.
EDIT:
According to what you said you are creating a single page application, if this is correct, then probably you can go with either the JSON or a partial views like AngularJS has. But if your server-side logic is written to handle only JSON response, then probably you could better use a template engine on the client like handlerbar.js, underscore, or jquery templates, and you can define reusable portions of your HTML and apply to it the data from the JSON.
If you cared about SEO you'd want the HTML there at page load, which is closer to your second strategy than your first.
Update May 2014: Google claims to be getting better at executing Javascript: http://googlewebmastercentral.blogspot.com/2014/05/understanding-web-pages-better.html Still unclear what works and what does not.
Further updates probably belong here: Do Google or other search engines execute JavaScript?

Categories