Outputting data with JQuery & PHP - php

I have a general question regarding quality of writing code ...
I'm working on website, that outputs data from MySQL with PHP and it is being called with $.get() / $.ajax() with jQuery....
Now my question is .. the data I´m exporting for example: an array of comments (from class Comments) for a specific post, and this array is being returned from PHP as a string with its HTML manipulation (return '<div id="this->$data"> this->$data</div>';) and with the JQuery manipulation, I´m adding all the comments as list elements or anything else to a specific html element.
Is it useful to do this? Or it is better to send the array in a variable to jQuery, and then work with its elements and make the dynamic html code directly in JavaScript/jQuery..
If that was confusing, is it better to generate the html code in PHP when returning /echoing, or to generate the html code in jQuery after receiving the core data from the php?
I know there are other methods like XML JSPN, I'm just asking here about the efficient with generating HTML to manipulate core data (example: Array or Core Json data)

Let me elaborate on AlberVo's answer
The PHP file which is generating the data, if it is going to be called from possibly other sources, say from an iPhone app, or a command line application or a desktop application, or even if say 2 months down the line you think your website's front-end is going to be say Flash based, then its better to keep your PHP code front-end agnostic and just return xml/json/yaml.
If you know its going to remain a HTML/Javascript based front-end and front-end load speed is an issue, then you can do all the hard work of converting your data into HTML in the PHP file.
In the end personally, I'd say stick to just generating front-end agnostic xml/json/yaml. You never know what direction of the code the future may bring. And architecting your design this way keeps you flexible a.k.a your front-end and middle-tier are loosely coupled.
A few more advantages to such an approach (which really just arise from the loose coupling)
Work organization. If in the future someone else is also working on this project one of you can work on the middle-ware and the other on the front-end as long as you respect the json/xml/yaml in between. Your work is not going to affect the other's.
Testing. Using a xml/json/yaml also allows you to unit tests your PHP code and front-end easier. Your test data is just xml/json/yaml.

The way I decide on this is if I foresee using the data for things other than that specific use, then it is better to return the raw data such as json or xml.

You will want to consider which part of your application should control your page structure and layout. Do you want your page structure to be defined by the PHP script that just returns data? Or do you want to define the page structure in the page itself, and let the PHP script just return the data as needed.
This is an issue addressed by the MVC (Model-View-Controller) pattern. If you follow the MVC pattern, you will separate logic from presentation, rather than mixing the two. This allows your application to remain as flexible as possible, and also promotes code reuse.

Related

Which is better practice? Getting HTML from Jquery Response

This is just a question as to find out what and how people do this, but
Say a user adds something to a list, when it's done, it runs the ajax below and updates the .user-stream-list
$.ajax({
url: "user-stream-list.php",
success: function(data){
$(".user-stream-list").html(data);
}
});
but the user-stream-list.phpresponse for example is
<li class='feed'><a href='http://www.theverge.com/rss/index.xml' data-fid='13' data-uid='15'><img class='favicon' src='https://www.google.com/s2/favicons?domain=www.theverge.com'><span class='title'>The Verge - All Posts</span><span class='options'><span class='addcat' data-fid='13'>+</span><span class='delete'>×</span></span></a></li>
Would this be acceptable in web development? Or should I really be passing it through as json and sort it into html afterwards?
Do what works for your particular problem. Good design finds compromise between the trade-offs. If you are on a tight deadline and you need something that works and it is easier to return HTML from PHP do it.
That said, you are generating the HTML programmatically on the server. You have same job if you pass JSON, the difference being the client generates the HTML. That is far more flexible for you, as you can generate different HTML in different contexts. Or not even HTML at all.
Designing to return a flexible data structure loosely couples your application components by affording reuse: the data structure remains agnostic to the caller's environment and the target presentation. This flexibility will serve your application well as it grows, and - in my opinion - the effort to design such an API early on is worth it.
I agree with bishop's answer, i think it depends on the architectural design of your system. If for example you want to use a js templating system, create a mobile device system, serve your data to other systems or something else that communicate with your back end then it is best to serve json from your server.
However even if you choose to prepare HTML server side using php, which is very common and acceptable as others noted in this thread, it is best to separate the entities creating the data and the ones creating the html code/template in order to be flexible and have the best of both worlds in the future.
If I understand you right you are worried if you should pass complete HTML code from the server or simple just the data. Well both approaches are good. It all depends on your needs and implementation.
For example you may want to add some inline styles to certain items in your list. You can generate that on the server side which would be much easier and send the whole HTML code. You may also want to add some microdata. Passing each of this parts separate as JSON would be unnecessary.
On the other hand you may already have premade HTML code and you only want to insert data into it. In this case passing the whole tag would be a waste of bandwidth.
There are also other factors you need to consider like: would it be faster to compile the data on server side or on the client side, do I need to save bandwidth or can I allow myself to send as long messages as I want?
In general try avoiding 2 things: sending large chunks of data and doing the same job twice.
Answers to this question could be broad, and are very opinion based, however I'll give my 2 cents.
Since you tagged the question as PHP, I assume your application is primarily PHP based for the server side code. Since all of your views will be generated by PHP, I'd keep all templating on PHP's side. Why? Maintainability and clarity. Having to chase down different sources of view generation is time consuming and misleading. IMHO it's better to keep all of the logic in on one side/language, and something like client-side JavaScript should be used for things a server side language cannot do (AJAX, transitions etc.).
This approach will allow for a smarter (IMO) view generating, its also very clear and makes it easy to alter your templates/views (remember, you should be writing code with other people in mind).

Ajax (client) vs PHP (server), Loading DB Data

I am embarking on part of a project now that has me planning on how to load a dynamic table data from a DB. I have uncovered two basic methods.
I believe that I can use url query strings to communicate with the php backend of my phpbb3 forum. And it can load the appropriate data and ship it off to the user in full static page chunks. So I would have something like /stats.php?page=3&orderby=name&dir=desc.
Or I can just send the same empty page to everyone and the browser can dynamically load anything that the user wants using ajax.
Or some combination of the two.
What is best practice? What are the downsides and upsides of both?
It really depends what you're trying to do. For simplicity's sake, I would say that the first option (just load it with the appropriate query string variables in the URL) is better.
Rendering a page using AJAX is pretty much always more complicated. However, it also gives you much more control over the UI if you know what you're doing. From my experience, if you want your page to be more like a "web app" with dynamic things happening everywhere, it is much easier to simply load JSON data from the server via AJAX and to dynamically create views via some sort of templating system. Otherwise you're stuck with loading the DOM with PHP, and then somehow communicating that data to your JavaScript, either by using data-XXX attributes on DOM elements, having PHP output a JSON string at the top of a page and assign it to a JavaScript variable, etc. It could get very complicated and convoluted.
In your case it looks like you're just trying to allow users to view certain data from your forum. Barring any additional requirements, I would recommend going with the first option because it will be much easier. This is simple enough that you don't seem to need to load anything dynamically.
A good rule of thumb is the more complicated and dynamic your UI, the more you should think about moving to a "web app" framework, and just let the server act as a REST server.

How to implement MVC style on my PHP/SQL/HTML/CSS code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have been developing a program for the visualization of some data. My program takes specific input from a MySQL database and draws some graphs (libchart library), creates some tables etc.
My problem is that right now its a code hell in there. I have around 7 php files (index, graph-page, gallery, etc) with HTML/CSS and PHP/SQL code all together (some of them just have the php extension but have only HTML inside). I have no problem to read and understand the project for the time being, but I guess if someone else tried to, he might get a headache. Plus, continuing programming like this is not practical because the project might not be easily scalable in the future.
Do you have any suggestion on how to successfully seperate HTML/CSS from PHP/SQL? I don't want to use a framework since I'm not doing anything that requires user-input, session handling, etc. I just run some queries and visualize the results. I'm mostly talking about architecture here, and if applicable perhaps a script to help me (I've read about Smarty but I'm not sure if that's what I need).
Do you have any suggestion on how to successfully seperate HTML/CSS from PHP/SQL?
Congrats for looking how you can improve code. That's the precondition, you need to want to improve it and the topic is lengthy. So your will is crucial.
I start lightly and then try to give some tips. As you're missing experience, look for one point to start with, most certainly the last one of the list below. But first things first:
To separate something from each other, you need to have some code that separates:
[HTML/CSS/PHP/SQL]
[HTML/CSS] <--> [SEPARATOR] <--> [PHP/SQL]
The Separator here actually is PHP code as well, but I think you get the idea.
As you can see only the Separator talks with HTML/CSS and PHP/SQL.
So both HTML/CSS and PHP/SQL need to have an interface with Separator (the line between) to make this work.
Normally in a program you pass around data that get's processed. The data is pretty dynamic and can have a compound complexity, especially if you pass data to an output routine that should format it properly.
There are multiple ways of how such a Separator (or multiple of them) can be written. You can layer your software or provide components that do things in their area or domain. E.g. you have a database layer or database component that takes care about the interaction with the database.
Or you have a templating engine that takes care to put your strings and arrays into some readable HTML.
In short this is the pasta theory of software design:
Spaghetti code - all in one, code is heavily interwoven, preferable with Bolognese or Aglio, Olio e Peperoncino.
Lasagne code - Layered, one layer has two other layers it interacts with (unless bottom or top), always with Béchamel sauce.
Tortelini code - Small components that just do their job, they have Meat or Spicy Vegetables inside.
Like we eat different pasta in our lives, when programming we need to deal with all these different type of code as well, and we develop our own preferred taste over time. As a kid we're feed but over time we start to cook something our own and vary the recipes.
So I think it's a good point you just don't want to now eat MVC Framework X with much awesome for the next weeks only because somebody told you it's the way to eat now. And before eating, there is tasting, right? Not to mention fast-food, you know like these noodles with sauce in package - only add water. Urgh.
I don't know which data your output needs and what the input is. Following are some rough refactoring tips for applications that output HTML/CSS and interact with a MySQL database. This can not be a complete list and the descriptions can only roughly outline some thoughts:
Move CSS out of HTML. Use selectors effectively in the linked CSS definition and replace any style attributes if you still have some. This makes your CSS code re-useable and more modular. It will help you to find flaws inside your HTML and to separate the Structure (HTML) from the Presentation (CSS). Effective HTML start with effective usage of CSS, those two are very powerful together and often this already will lighten your programs output routines.
Move business logic out of HTML. Both HTML and your code can be a beast, so better keep them apart. They have the tendency to fight with each other, and as both are very powerful, the fight will continue while you develop your application, that distracts you from the work you need to do.
Consider if you need to already have complex output inside your application or if you can just pass on arrays with subelements (a key is a var, a var can contain a string or number or another var-array). Normally that is all needed to pass even complex data into a view or template. You HTML then only needs to echo some array members and or foreach over subarrays. This is a very simple technique to create a template. You can use PHP for it, so you're actually really flexible (just draw the border which code belongs into your view layer and which is part of the application, e.g. providing values for the view).
Move SQL out of your code. Move the database interaction code away. Create yourself one or multiple objects that have methods which return the data in a way you need (consume) it in your actual processing code, like $component->getThatData() which then returns data in a normalized form. Make those components then use a dedicated database component to talk over with the database. In your application code (business logic) only use the database component and preferably the objects you create to get the data, so you don't have any line of SQL any longer inside your main code.
Divide and Conquer your application code: Divide your code into Transaction Scripts. They are often easy to create from existing spaghetti code and will be probably become the said Separator you're looking for in middle terms. They will then have the role to process data and passing it on (into the output/view).
Use clear language: If you have complex formatted string data that is not normalized, write yourself Parser classes that do the work for you and which can be easily re-used (if that's the case in your application). As you should look forward to minimize the use of plain SQL in your code, you should also look forward to move complex regular expressions away as well. Encapsulate what varies is a key point. Same applies to long routines to just handle some data (e.g. sort, order and arange it in another format), move them into components of each own and think about how you can make them accessible and re-useable.
Make your code functioning: Find out about the logic how you invoke functionality in your program. You can try to separate functionality away from how it's invoked. E.g. some routine that invokes any of the Transaction Scripts. This might not be necessary if you request PHP files directly via the browser, as those are then your transaction scripts and the webserver takes care to resolve the command send via URL into your application to the transaction script. But you should then wrap any logic needed to process the incoming command and it's parameters into re-useable components (e.g. a Request class that contains standard code to get the URL and or variables from a HTTP request).
Create a common entry-point by including the same file at the very top of all files that are called via the browser. You can then put common code (like setting up the application session state object and initializing the database component) into it, see as well Application Controller
Remove duplication by looking for literally duplicated code. Wrap it into a function or class. Create a library folder for your own application into which you put your includes. If you follow a common pattern with Classnames and Namespacing, you can easily use an autoloader to keep inclusion easy. Make your library apart from third-party code. Place all third-party code into a library folder of it's own with one subdirectory for each third-party component.
Use lightweight, existing components. Lightweight is important because you have your own code already, you don't want to turn and press it all at once onto a framework.
Existing is important because you don't want to re-invent the wheel. You will have enough work for your own refactoring your code. After you feel better about your application and you still have power and will, you can always write everything new. But if you're alone or in a small team, Existing is pretty powerful.
Simple libraries are for example:
Templating engine: Mustache
Database layer: NotORM
Create Application State, e.g. as an object you can make use of in case some components need to know about the application state or each other without direct interaction. By default in PHP if you don't have one, global and global static variables are used to create state. However these variables can make your live hard as code grows. When you create an application state object, it's clear which components make use of it, access to it can be controlled (e.g. calling a method instead of reading a variable, which can help with debugging) and components as well can find out if it's the right time in the application flow to come into action. It's also a good tool for refactoring your code over time.
Preserve a Working Application, keep your code in a state to run. Ideally this would be backed up by automatic tests. Consider that you need to rewrite much. For example if you start to integrate a database component, do it. Move all your existing code to it in one step. So who tells you it still runs? Use git for better undo and to test stuff. That's more important than choosing the right library. Preserving a working application is also always the key point because that's why you change it, right?
Why not use a templating engine? TWIG is very easy to use and great for this sort of thing. It is often used with the Symfony framework, but can easily be used on its own.
as you don't need user input and store session.
You can just create a controller -> model & controller -> view structure
the controller: will help you get data from DB (via. model) and embed data into view.
You can create 3 folders controller, model, and view. In each folder, you can create files based on your needs(e.g.MVC for User).
The model can access static objects written in mysqli.inc.php or pdo.inc.php based on your need you can write a template for connection, query, disconnection, in all your model classes.
In model file, you can call static function DB::query('SELECT/INSERT/UPDATE/DELETE', );
For view, you will need a render function to embed data into HTML Code for example
function render() {
//start output buffering (so we can return the content)
ob_start();
//bring all variables into "local" variables using "variable variable names"
foreach($this->vars as $k => $v) {
$$k = $v;
}
//include view
include($this->file);
$str = ob_get_contents();//get teh entire view.
ob_end_clean();//stop output buffering
return $str;
}
In the controller, you can include your model file call particular class and function for data. Call view file with render function for example,
$view = new view('../view/data.php');
$view->name = 'Your Name';
$view->bio = "I'm a geek.";
echo $view->render();
you can either return or echo your view based on your requirement

Migrating from POST forms to CSS

I've been tasked to migrate a web application to a more 'modern feeling' AJAX web 2.0 deal. The application as is currently uses PHP to pull data from the database, present the user with forms, and then update the database based on those form submissions. Frames are used to have a persistent main navigation menu, and a content area where the actual
So each php script basically looks for $_POST information; if there is none, it shows the user database data, otherwise it updates data ( provided it is proper data ) and then show the user the result. There are simple get navigations that show subsets.
To migrate this to a AJAX site with a css layout with the content changes happening inside a div, I'm precluded from using POST, because that refreshes the whole page, right? ( I mean I could, but that would be wasteful -- I don't need to regenerate the whole page when only a small part changes.) So basically, the whole task is using Javascript to read the form information, send an XML HTTP Request, and display results? That sounds like a lot of re-writing the existing php funcitonality in javascript, which I would hope to avoid.
Have I understood the task correctly? Are there libraries or frameworks that can help me?
You have two problems here, which are related in some ways, but shouldn't be simply lumped together.
CSS for layout
Only loading part of pages when forms are submitted
I'd work on the separately (while keeping the other in mind as you do so)
First, I suggest you focus on moving to web standards based pages — without introducing Ajax.
It is true that there are some inefficiencies to be had when reloading the whole page, but this approach is simple and relatively easy to debug.
While you do this, consider separating out your display and business logic. The MVC pattern works well for this.
CakePHP is a popular MVC framework that might help.
Once you have a working system, then you can worry about using Ajax. Follow the principles of progressive enhancement.
If you have separated our your display logic from the business logic you should find it relatively simple to reuse your existing code with a different View that provides the data you care about in a JavaScript friendly format (such as JSON).
You can process this to update the parts of the page you care about.
Frameworks that can help you include YUI and jQuery.
I wrote a simple example last year. Lines 51 onwards of the main script pump data into either an HTML template for processing directly by the browser or a JSON module for processing with JS. There isn't a great deal of duplicate effort there since the code for looking at the parameters sent by the user and extracting data from the DB based on it is shared.

AJAX and the MVC pattern

Please redirect me if a similar question exists.. I haven't been able to find anything, though I'm sure that my problem is fairly common...
I have a page that has 5-6 divs that can be individually loaded through Ajax requests. Through a prototype ajax.request(), the server (php) echoes back the HTML code for the division before the client refreshes the divs's innerHTMLs.
Here's my question : What's the best practice for preserving the MVC pattern on the server side concerning the HTML code it throws out?
For now, my models return database data to the controller, enabling it to initiate a really long var containing the HTML code that it then echoes. My problem is that I end up with a lot of HTML code in my controller classes...
You could use JSON for transporting data to the client-side and constructing it there.
That way you'll have an abstracted data source not bound by your markup. JSON can be directly evaluated into a javascript object.
Do you really like to use MVC? The C can mostly be removed by Conventions / RESTful URLs.
Like Andy said, you should use JSON to transfer the data to the client side. XML is also a wide used alternative (because it acts much better if other apps have to use your services). XML can be tranformed easily to JSON! And JSON code is valid JavaScript Object code. So you can use it to stich client side templates together with it.
You should try EJS for browser/client side templating! If you do so, you have no HTML boilerplate in your controllers! Just business logic. That follows a lot of SOA best practices. The architecture pattern is called SOFEA or SOUI (which is the same).
I've written my homepage with it. The evaluation of a lot template engines has clerified that EJS is the best candidate.
Because:
1. It's fast!
2. It's free (MIT License)!
3. It works well with JQuery
4. It does realy modify the DOM, so other methods can access the used templates (JS Repeater doesn't).
Other frameworks:
JSmarty: Not such as easy to use but it can use Smarty templates. It isn't enteprise prooven and still under heavy development.
Trimpath Javascript Templates: Doesn't work well with JQuery/Prototype... Also still under development.
jQSmarty: Nice, but it seems that the development has stopped. The last change was in 2008.
seethrough_js: Invasive template layouting. Nice for Erlang people.
JsonML: Also an invasive template format which is based on JSON. What do you think about it? I think designers should stay at their HTML/CSS elements, so no knowledge is wasted.
JS Repeater: Reminds me at my own bad tries. I've checked it out and used it.. but it doesn't handle a lot of things very well. (Such es empty fields etc.)
Pure: Time to start a relegios war on how to develop pages? I think that Pure isn't the answer. It's bloating if you define what's really to do and it fails to scale like JSF. It has no invasive syntax, thats very good. But the price of the hard to use rules for rendering issues are a no go for me. It just feels don't right. I've met other people which think completly different! Test it out and let me know what you think.
This is what I do for MVC + AJAX...
Really simple implementation, if you were to ask me.
http://jarrettatwork.blogspot.com/2009/02/aspnet-mvc-ajax-brief-introduction.html
If think that the most important letter in MVC is V for working with AJAX. AJAX with HTML, and JS is part of presentation layer so by theory it is place for View - part.
View is responsible for what you send to end user, and MVC patter is there not only to separate Model, View and Controller but to enable us multiple views for the same data model provided.
So it is best to encapsulate code in a class and use that same controller code to render different views. In first case that could be drawing of a static page, but in other scenario it is view specially designed for AJAX calls and data may be in JSON or other standard format it doesn't matter, as long as you respect responsibilities that every layer has.
If the HTML is mostly in string literals, as I understand it is, you probably should move the HTML outside the <? ?> tags altogether and insert the dynamic contents from the database with small inline PHP snippets that reference variables set by the controller.
This is effectively a template mechanism. Remember, PHP is at its heart a template engine.
Example:
<?php
include 'controller.php'; // set variables used below
?>
<div>
<h1>Hi there, <?=$UserName?></h1>
<p>Since you've been here, <?=$numberOfDays?> days have gone by</p>
</div>
etc. This also gives you back the syntax highlighting in your HTML and gets you rid of having to concat all the long string literals inside your PHP code which often messes up the readability of the code.

Categories