HTML that's both server-side and javascript generated - how to combine? - javascript

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.

Related

Best way to inject HTML with the results of a WP REST API call?

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/

AJAX url and controller

For form submission I use an AJAX call that posts data to a page like form.ajax.php. At this page I check if '_POST' is set and then process the form by validation, and then save the data using my database class. Depending on the result, the ajax-page return a status message back to the form-page which fires an alert message with the status.
My question is how and where should I put my AJAX files. Should I use one file for all kinds of AJAX requests or multiple and how does AJAX fit into web MVC? I have tried to search for it but there seems to be many different opinions.
I usually find it manageable to make ajax calls from the views files which load ajax(js) functions as needed. This way all the functionality related to the front end display is contained in one place and easier to debug later on. I also create common utility ajax functions so minimize code repetition.It goes something like this:
view.php( callController(ajax function) ) --ajax call--> controller.php( return value)---> view.php(updateView(ajax function))
You could, for clarity, use one file per AJAX action, and put them all in the same directory, like /AJAX/logout.ajax.php, /AJAX/login.ajax.php etc. If you only have a couple of actions you can just use one file to serve them all.
This is just a matter of convention between you and the people you work with (including your future self, say 6 months later, when you will have no idea what you did in that project).
As long as everyone is in the same page, you can't really go wrong.
Also, I hope you sanitize your _POST inputs properly so little Robert won't be able to harm your database.

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.

angularJS & web2py: calling python from ng/javascript/html

I'm using AngularJS (mainly the client side) and web2py (mainly the server side)together in an app.
I have an issue now.
At a point of the program, I use AngularJS to get some data from the client and these data are store in an AngularJS variable. I planed to use $http.post to submit these data to database directly, but it didn't work due to cross-orign problem.
Right now I'm trying to pass these data(they are in JSON format) back to web2py and let web2py insert these data to database.(similar to submitting a SQLFORM).
Is there anyway I could pass these data as an argument to an web2py function and invoke that function within javascript code?
Possible approach in my mind:
1) Since I could write python in html using {{}}, and I could write html in javascript, could I write python code within javascript using something like: document.write({{python code}}) ?
I tried this but whatever html I write it goes to a brand new html page. I also tried document.getElementById('testDiv').write("<p></p>"); But it doesn't work.
2)use ajax, I'm not familiar with ajax, any example will be really appreciated!
Any thoughts?
Thank you all!
ok so you got me lost for a second there, lets see if i got it right
1- angular as your frontend
2- python as your backend
3- you are rendering an html document in python and delivering it to the browser
4- since python template language uses {{}} as delimiter am assuming you changed the angulars delimiters too
either using ajax or reload you'll need to provide a python post handler script. that takes your data and makes the DB update. if this is going to be a pattern and you are going to be making AJAX CRUD operations, you should use angular resources ngResource if not a simple
$http.post(url,data).success(function(response){})
https://docs.angularjs.org/api/ng/service/$http#post
where url would be your form submission handler url.
if you where to use a form you'll need to set the target to an iframe hidden in your page and the response should a script tag that gets the scope pertinent to your controller and let him know the result of the operation. this is an old approach, but handy when it comes to send information to sites that don't allow CORS which by the way might be the solution to your problem, when storing data directly to your db, you might just need to enable CORS headers in your storage engine API and that should allow you to submit information even when coming from a different domain
After hours of struggles and countless google, here's my workaround solution:
Main problem: the data are stored in AngularJS but AngulatJS could not submit data to database through API due to cross-orign issue. But Web2py could submit data to database using sqlform.
My approach:
1.)When the user click the submit button, invoke 'ng-click="submitBtn()"'.
submitBtn() is a function of the ng-controller, which has access to the data.
2.)In submitBtn(), the function first write data into web2py's sqlform through
document.getElementById('inputId').value=$scope.data;
then the function click the sqlform submit button through
document.getElementById('submitBtn').click();
It took me a lot time to figure out those element ids of fields in web2py's auto-generated sqlform. The way to find them is using developers' inspect element tool in a browser and see the source code directly.
Hope this will help someone will face the same issue!

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