Lets say i have json which contains informations. What would be the best way to put the informations on site. Creating elements via js like
(this is just part im interested in , inside ajax call)
var div=document.creteElement("div");
var text=document.createTextNode("bla");
var img=new Img;
img.src=json1.img;
img.onload=function(){
div.appendChild(text);
div.appendChild(img);
}
or putting them "in" like
body.innerHTML+="<div><p>blabla</p><img src='json1.img'/></div>"`
which one of there is better/faster/more efficient , or is there any better way how to put content into site via ajax? Also how does big sites that load tons of data from server handle this? Tons of data would take a lot of time to load
Ok, I understand now. To render content from ajax you have 3 choices:
Load the data with an ajax request ($.ajax in jquery or xmlhttprequest from scratch) and then create elements and insert into DOM. This solution is very bad because it is unmaintainable.
Load data using ajax and use javascript templates like Underscore template (_.template) or Handlebars (http://handlebarsjs.com/). This is a very useful solution.
Load data using ajax and use a very powerfull system views like React JS. I love it and it's very intuitive and easy to use to have a good performance without a lot of work from your part. "Template system" is very cool and easy (like using html). I will use react if I were you :) https://facebook.github.io/react/
Related
Let's say you want to dynamically inject 10 extra posts to a WordPress site's homepage blog roll. The 10 new posts are added after some user interaction. So for this example let's pretend the JSON response of the user interaction is identical to the results of this call:
GET /wp-json/wp/v2/posts?s=awesome
What is the ideal way to add the results into the homepage, but ensuring the new posts use the same HTML as the existing ones?
In my mind it seems like the options are currently:
1- Write a loop in Javascript and write the correct html for the posts inside the loop. But that would complicate things like translations and I already have loop templates in PHP, so feels like duplicating code.
2- Writing a custom endpoint. But from what I understand I'd need to write a new WP_Query() with the search parameters, and then return all the html in a single variable (so no get_template_part() and duplicating code again).
3- A hacky idea I had was to add a hidden empty skeleton of the html of a post somewhere on the site on page load. Then when the time comes, in Javascript run a loop and clone the skeleton each time to inject the relevant post data from the JSON. But this feels nasty to me.
Is there a better way? Or am I misunderstanding a basic concept of the WP REST API?
Your idea #3 sounds a lot like using a templating language like Handlebars, and isn't all that hacky necessarily.
You'd "hide" your HTML template in a script tag and then use Javascript to render it with the data that comes from your Ajax call. See the examples here for a basic idea: http://handlebarsjs.com/
I'm pretty new with the "dynamics" programming, but I really love it and now I need to improve my PHP web page.
Actually I have an PHP array, and I'm building "standard" html output inside a foreach cycle to build my page.
As you can see from the screenshot the actual result it's a page with a lot of <div class="ui-content">, there is a way, to simple create pagination where I'm able to show only six DIV entry per page, and create the menu to switch between page?
I think, the best solution is build something using advanced "dynamics" technics like AJAX call, but I'm totally new with this kind of programming.
Another possibilities is to use some pure java script at runtime to make the pagination, but I think this is not the best solution concerning the performance.
You Can try with simple Jquery Pagination, which is simple one to implement, but it loads the complete data and then paginate, in other approch like AJAX which request server each time you change the page.
Simple pagination jquery example easily available online. for example :
http://flaviusmatis.github.io/simplePagination.js/#page-2
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?
I am new to dojo and somewhat new to symfony as well and am having a wee problem here: I want to reload a part of my page using Ajax but it includes a Javascript which needs to be executed. This isn't reallly a problem in prototype or Jquery but I just can't figure it out in dojo. (I need to use dojo because it's a part of symfony and already in heavy use on the page I'm supposed to modify. I also know this is probably improped technique but it's just a little mod I need to do and this would be the easiest way ...)
Can you help??
Thanks,
thomas
You can do it by using dojo's require tool
For more information regarding this, take a look at the documentation
dojo.require("my.path.to.file", false, true);
Call this when you want to load the javascript file, mostly after the ajax request is complete. So that if this javascript is to alter/perform some operations on the ajax loaded content placed into DOM, you won't get NOT_FOUND dom exception.
I'm usually a creative gal, but right now I just can't find any good solution. There's HTML (say form rows or table rows) that's both generated javascript-based and server-sided, it's exactly the same in both cases. It's generated server-sided when you open the page (and it has to stay server-sided for Google) and it's generated by AJAX, to show live updates or to extend the form by new, empty rows.
Problem is: The HTML generation routines are existing twice now, and you know DRY (don't repeat yourself), aye? Each time something's changed I have to edit 2 places and this just doesn't fit my idea of good software.
What's your best strategy to combine the javascript-based and server-sided HTML generation?
PS: Server-sided language is always different (PHP, RoR, C++).
PPS: Please don't give me an answer for Node.JS, I could figure that out on my own ;-)
Here's the Ruby on Rails solution:
Every model has its own partial. For example, if you have models Post and Comment, you would have _post.html.erb and _comment.html.erb
When you call "render #post" or "render #comment", RoR will look at the type of the object and decide which partial to use.
This means that you can redner out an object in the same way in many different views.
I.e. in a normal response or in an AJAX response you'd always just call "render #post"
Edit:
If you would like to render things in JS without connecting to the server (e.g. you get your data from a different server or whatever), you can make a JS template with the method I mentioned, send it to the client and then have the client render new objects using that template.
See this like for a JS templating plugin: http://api.jquery.com/category/plugins/templates/
Make a server handler to generate the HTML. Call that code from the server when you open the page, and when you need to do a live update, do an AJAX request to that handler so you don't have to repeat the code in the client.
What's your best strategy to combine the javascript-based and server-sided HTML generation?
If you want to stay DRY, don't try to combine them. Stick with generating the HTML only on the server (clearly the preferable option for SEO), or only on the client.
Make a page which generates the HTML on the server and returns it, e.g.:
http://example.com/serverstuff/generaterows?x=0&y=foo
If you need it on the server, access that link, or call the subroutine that accessing the link calls. If you need it on the client, access that link with AJAX, which will end up calling the same server code.
Or am I missing something? (I'm not sure what you mean by "generated by AJAX").
I don't see another solution if you have two different languages. Either you have a PHP/RoR/whatever to JavaScript compiler (so you have source written in one language and automatically generated in the others), or you have one generate output that the other reads in.
Load the page without any rows/data.
And then run your Ajax routines to fetch the data first time on page load
and then subsequently fetch updates/new records as and when required/as decided by your code.