Pushing HTML to a web page (JS VS PHP) - javascript

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!

Related

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.

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?

initial data loading in angularjs

When building a web app where every page depends on many data sources, what's the best way to fetch the initial bits of data? When I look at twitter, I see the tweets that are visible on page load are in the HTML source, and more tweets are loaded in using AJAX as you scroll down. But there's no convenient way to get data that's already in the DOM to be inserted into the model.
Making a request for the initial data, immediately after page load seams stupid, because you've just made a lot of roundtrips to the server to fetch css, html and javascript. Would it be a bad idea to insert the data into a javascript tag on the page, so a javascript function can add the initial data?
I'm specifically asking for angularjs, but if there's an general technique, please let me know as well.
You'll be referencing your controller anyway on page load, so you won't have to have an inline script tag.
You can either set a default model and use the attribute ng-bind on initial load, or call a function to pass back data.
It's pretty typical to fetch data on load in angularjs.
Would it be best to couple Angularjs with an HTTP Client in the backend like Zend_Http_Client or Guzzle to let the server fetch the data. Then, pass the data as json to javascript upon render.
I know Angularjs is designed for Single Page applications. That's why it makes sense that it lazy loads the data.
However, if we're going to move to the approach where we still render the page dynamically and still delegate the task of organizing the content to Angularjs. What framework will be suitable to contain the AngularJS views. Right now, project templates like angular-seed are all static..
That is, the idea is the server serves a page with the embedded json object. Then angular, takes over in the client side, Fetching additional content where needed.
So instead of just a single page of contact (e.g: index.html), we would have several pages like profiles.html, products.html. The help of the backend would be particularly helpful say you have a section which doesn't change often like your username on the top right side of the page. For me, I just think it's better to have these data preloaded in your page and not have to ask the server after the page has been loaded.
As bigblind have noticed, this seems to be the way sites like facebook, gmail, twitter does it. They contain the data embedded on page load. Then, load additional content via services afterwards.
The idea is something like below:
Webservice <---------- Backend------------> Frontend
<------------------------------------------
Backend delegates the task of querying the webservice to provide initial data in the rendered page to the client. Then client, can directly connect to webservice to fetch additional content.
Using the above setup.. What is the ideal development stack?
One way to do it is to create a directive that handles the initialization before binding happens.
For example:
app.directive('initdata', function() {
return {
restrict: 'A',
link: function($scope, element, attrs) {
if ( attrs.ngBind !== undefined)
{
$scope[attrs.ngBind] = attrs.initdata ? attrs.initdata : element.text();
}
}
};
});
This directive takes either the attribute value as initial value for the bound $scope property, or the textvalue of the element.
Example usage:
<div initdata="Foo Bar" ng-bind="test1"></div>
<div initdata ng-bind="test2">Lorem Ipsem</div>
Working example on http://jsfiddle.net/6PNG8/
There's numerous way to elaborate on this; for example parsing the initdata as json and merging it with the scope, and making it work for more complicated binds, like $root.someprop. But the basis is remarkably simple.
According to the answers on this question, a JSON object in a script tag on the page seems to be the way to go. If ayone comes up with a better idea, I'll accept your answer.

PHP to JS: printing js variable (like PHP echo) compatible with AJAX responseText?

I'm using W3 Schools' AJAX PHP Example (http://www.w3schools.com/ajax/ajax_aspphp.asp) as the foundation for my guestlist web app that uses data stored in LocalStorage, rather than MySQL database, in order for users to be able to search while offline. Now I'm trying to finalize the search guest part.
This is how it works (and differs from the example above):
(index.php). Placing / mirroring all records from MySQL db into
javascript arrays
(index.php). Storing the above mentioned js arrays in LocalStorage
(index.php). By using the AJAX GET code used in the example,
sending the searched item to getData.html (a html file instead of
php file as W3 does)
(getData.html). Successfully getting the searched item through the
URL parameter
(getData.html). Looping through and matching values like in the
above example (code rewriten in javascript).
BUT here ends my success. The AJAX code is identical to the one in the above supplied example (except of course the reference to getData.html), and everything else seems to be working so I won't bother you with my entire code. In the example mentioned, at the very buttom of the PHP-file it says
//output the response
echo $response;
This is where javascript seems to be failing. I've desperately been trying to echo / print the response but for some reason, it doesn't get returned to index.php properly. The only way to force it to display at least something is to either use php echo, or simply just write plain html text somewhere in the getData document within the HTML tags. I've also tried getElementById('txtHint').innerHTML = "hello"; to see if it works but with no success.
The most obvious way to do this would be to simply replace echo $response with the equivalent in js:
document.write(response);
but whatever document.write prints, nothing's dipslayed. The div in which the "hint" is supposed to pop up is yet empty. I've googled solutions, different ways of printing js variables with no further success. Perhaps, document.write is not "compatible" with XML or AJAX responseText? There must be a simple solution to this. Hope you guys can help me out. Thanks!
php is of course a server-side language that emits a page and runs on your back end.
js is of course a client-side language that runs on the user's front end.
document.write() is the proper function for emitting client-side text; it runs at page load time. Example:
<b>My domain is: <script>document.write(document.domain);</script></b>
properly gives
My domain is: www.mydomain.com

Passing parameter map (list of values) to JQuery

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.

Categories