How to completely separated DOM manipulation from PHP? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have to create a website for a friend of mine using PHP. It is basically an online store.
I want to use new features of HTML5, CSS3, jQuery and other JS libraries.And I want to keep all the document generation and manipulation separate from PHP.
I have done a lot of searching on Google. People come up with MVC architecture. And that's all good.But the problem is in all the examples or tutorials that I found; people retrieve the data from the SQL based databases, and then echo or print it to generate html, or use some ORM classes to display it. I don't know much about ORM or PHP frameworks.
I have always made pet projects, small websites, nothing like this medium-sized Store.
The way I understand the MVC architecture is this:
**Model:** Basic purpose is to save and retrieve data from the databases.
**Controller:** Do some operations on the data to either store them using Model, or do some operations on the retrieved data (again using the Model), to be passed to the View.
**View:** This is used to display the user the content.
What I want to do is do almost ZERO html generation using PHP.Instead I was thinking of a approach in which :Model is used for database handling only. Controller is used to convert that data into JSON objects, and make those JSON objects available to the appropriate Views.Then using JavaScript I will do the DOM Manipulations according to the JSON objects.
Is this approach any good ? If yes how to do it (especially the part of converting the data retrieved from database to JSON objects).
If you can provide me with a better approach where I won't have to do generate html using PHP, and use PHP for front-end as less as possible.
I am doing all the front-end stuff which the user is gonna see. My friend will be doing all the database handling. I don't wanna get involved in the PHP part, and if it is mandatory (i.e. there is no way-out) then as little as possible.
Please provide me with some solution. In desperate need here.
EDIT: I am especially talking about echo and print commands. I would like to have a fresh slate to work on instead of getting the html creation mixed with PHP and JavaScript.
If NOT using these commands is not suggested based on the fact that the user may be on mobile device, or have JavaScript turned off. Then is it possible to have a simple looking website with all the data displayed if JavaScript is turned off; and if it's not turned off then remove all those elements from the DOM and make a fresh DOM with JavaScript. However the main hindrance to this is converting the data retrieved from database to JSON object so that it can be used by the JavaScript.
I don't think this is possible, but is there some way in which PHP variables can be directly used by JavaScript ?

PHP does never manipulate the DOM, the DOM is purely client side, while php is purely server-side. PHP can generate HTML, which will be sent to the client, and processed to a DOM by the clients browser.
If you want to (nearly) completely split it in two parts, you could split it into an API server (php & database) which will provide a RESTful JSON-API and a content server, which will provide your static HTML, CSS and Javascript files.
The Javascript on the content server will connect to the API server with AJAX get and post requests to retrieve and send data to the database.

Yes, it's entirely possible to do what you're describing. You'd use static HTML files for the basic page setup, the usual CSS and images and such, and your PHP would only be used to generate JSON to return to the client and get used by JavaScript. So for instance:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Example</title>
</head>
<body>
<table id="theTable">
<tbody>
<tr><em>Loading...</em></tr>
</tbody>
</table>
<script src="yourscript.js"></script>
</body>
</html>
yourscript.js:
getDataViaAjax("data.php", function(data) {
var table = document.getElementById("theTable");
// ...fill in the table using the information from `data`...
});
data.php:
<?php
// Get data from somewhere
// ...
// Output it
echo json_encode($theData);
?>
Obviously the table there is just an example. You'd probably have much more static content, and a few places where you wanted to add dynamic content.
This is a perfectly feasible approach, and the separation of concerns helps as the team expands.
However, note that if you do this, any page that has content from the DB will result in two HTTP requests to the server (one to load the HTML, the other — which won't start until after the first one is at least partially finished — to load the data) rather than one. In general, the goal is to minimize HTTP requests. So there are trade-offs.
I don't think this is possible, but is there some way in which PHP variables can be directly used by JavaScript ?
Correct, that's not possible. There are frameworks like Meteor (that one isn't PHP-based) that handle the middle layer for you, though, and make it seem a lot like that's happening.
You can also look at tools like AngularJS and KnockoutJS that can bind your JavaScript data objects to DOM elements, saving you a huge amount of manual update code, or even just things like Handlebars that render templated stuff for you.

I think what you are looking for is a client-side template engine, where the document is built client-side using ajax queries. The ones I have heard good things about are Handlebars and Mustache, though I'm sure there are others to choose from.
But even with such a solution, I imagine that some amount of server-side HTML needs to be output to "prime the pump", in which case, you would want to consider a server-side template engine like Smarty or whatever the latest-and-greatest equivalent is. With a server-side template engine, you would write the templates as standalone files (like .tpl for Smarty) and PHP would consume the template as an object and then pass in any unique variables for the template via the template-engine's methods and then you would call the display method for the template.
In either scenario (or a combination of both) you are separating your final HTML output from PHP so that PHP is interacting with the templates rather than doing plain echo "<div>This looks so Web 1.0</div>"; which I think is what you are trying to avoid.

Related

Using a form to save/update settings in a db and build a HTML with those settings from a template

My limited experience in web development as a self-taught led me to hit a wall while trying to figure out how to deal with this problem.
I need a form (map_settings.php) where the user should enter some inputs. Those inputs must be saved in a database table (MAPS) and then used to create the final HTML file (e.g. map1.html) for that specific user/inputs.
I know how to deal with using forms and saving submitted data to a database.
What is completely obscure to me is how can I use those inputs to automatically generate the final HTML.
My idea is to have a template HTML (template.html) and each time a user saves new settings via the form, I copy the template and replace some variables inside it with the actual data the user has input in the form.
If this might matter, the variables I need to replace in the template are also JavaScript variables within a <script> tag.
Can anybody help me suggesting one viable way to do this? I am mostly using JavaScript and PHP, without frameworks. I've also red about JavaScript templating engines, but I sincerely did not get if those are useful to me in my case.
Anyway, here is an illustration of what I would need to do, to hopefully clarify better my point.
Creating a static HTML file per user is not the way to go. Instead just have a PHP script like mapdisplay.php or similar.
Make the script so that if you type mapdisplay.php?map=1 in the browser then it will read the map ID, get the relevant settings from the database for the map in question and then generate some HTML to display them - of course you can have most of the HTML ready made like a template, and just use PHP to fill in the details from the database. This idea of getting data on the fly when requested, and plugging it into some HTML is how most web applications work.
If you create a static HTML for each user it quickly becomes unmanageable with a large number of users, plus it's hard to introduce changes or improvements to the template because instead of just updating one script file, you have to back and re-do every existing page. There are other disadvantages to your approach too, but I won't continue here - you get the idea I hope.
If I were you I'll make that in this way:
Don't use template.html
Don't get data from database to new file, but from form
Make database test before make file
To make template use
$template_text = "text...text...html...text...".$php_varible."text...text...html...text";
For other things about php see w3schools

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?

How is it possible to call data from an xml document into an html page?

I'm new to web development but from what I've learned so far, I'm sure what I want to do is super easy. I just haven't quite figured it out, yet.
I have an app that pulls external html pages. These pages all pertain to grain prices. I have about ten pages or so and currently to change the prices I open each page, find the prices and manually change them. What I want to do is just have all the pages pull their prices from the same document (I'm assuming this will have to be an xml or txt document) so that I just have to update that one external document.
The external document will be hosted on the same server as the html pages.
This seems like something I should be able to do simply with javascript and Ajax and I have seen many examples using just that. The thing is that in all of the examples I've seen, the ajax calls an entire text document instead of just one piece of it.
For example, I have an html page called Northern Alberta Prices and it lists about six different grain prices. I want that page to call the external document (let's call it prices.xml) and get all the northern Alberta prices off of it and put them in their proper places on the html page and then I want the Central Alberta Prices page to also call prices.xml and take the relevant prices off it etc.
What would be the best way to do this?
(I'm not able to use PHP on my server at the moment but any answers involving PHP would still be welcome.)
Thank you for your time.
You'd have to call the entire document and then interact with the specific node in the XML
without the actual schema there's not much more help I can give you, although there is an ok tutorial here:
http://www.sitepoint.com/server-side-xml-javascript/
which will help you understand the core concepts behind data manipulation
Yes, to use XML with PHP you can do this:
http://php.net/manual/en/simplexml.examples-basic.php
That pretty much says, you can do this:
<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
echo $movies->movie[0]->plot;
?>
... Which will get the Plot attribute from the first movie node. Please let me know if you have any additional questions.
Edit: One more option I came across was using jQuery (javascript):
http://think2loud.com/224-reading-xml-with-jquery/

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

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.

Categories