What's the best way to add dynamic content to a web page after a successfull xml http request. To break down a more concrete example:
User fills in data in input field (e.g. a forum post)
Data is asynchrously updated using the ajax technology
The forum post is instantly displayed for the end user
Sites like Facebook or last.fm (when you post a shout, ie) send the processed markup in a direct object back to the javascript, instead of just the processed data. An example of this written in jQuery would be
$('#activeField').html(callback.data);
Another way to do this is to create the dom elements on the fly with javascript. I find this too clumsy as there's no easy (?) and simple way of doing this today. At the same time, sending the processed markup directly from the server violates our application's design principles (MVC), as having markup in a front controller is not preferred.
What's the "best practices" way of doing this? Thanks!
At the same time, sending the
processed markup directly from the
server vioalates our application's
design principles (MVC), as having
markup in a front controller is not
preferred.
I may be missiing the point, but could you not send markup from the server by rendering it within a view as you would normally, rather than having to have markup in your controller? Assuming your View mechanism has the ability to return rendered HTML rather than outputting it immediately, you could retrieve this and then add it to an array before calling json_encode() and outputting it. You could potentially then use the same view code to render this piece of HTML regardless of whether it is being fetched as part of a full page or via an AJAX call.
I think this question pushes too far on subjective perhaps, but personally I believe the best plan is for the request to return JSON which describes both the content and the mechanism (by which I mean javascript method) for serialising that to HTML if multiple possibilities exist. This saves on bandwidth and (as you've pointed out) preserves your separation of concerns. The last thing I want really is for my front-end guys to have to deal with arbitrary mark-up from the server-side guys. Abstraction is good.
I don't really get why you feel JS generated mark-up is clumsy or difficult. A handful of JS methods which parse and generate standard JSON structures seems lightweight and trivial to me, though I must admit I've always rolled my own here. Almost certainly there's a framework for this out there (anyone?). If not, well I've got this great business idea...
Related
I want to make a faq panel when user ask any question it show on the top of division without reloading the page for that i think i have to make a connection with database after every few second. Now the question is that how to make connection without reloading the page and how to show new question ?
You have two options:
Ajax, which allows you to retrieve data from the server with JavaScript, which you can then use to manipulate the DOM. The basis of Ajax is the XMLHttpRequest object, which allows you to retrieve data completely behind-the-scenes in JavaScript. Note that Ajax is limited by the Same Origin Policy, but for what you're describing, that's fine — you'll be loading data from the same origin.
Frames (e.g., iframe elements), which you can load content into by setting their src property.
Of the two, Ajax is much more flexible.
References / further reading:
DOM2 Core
DOM2 HTML
DOM3 Core
HTML5 Web Applications APIs
XMLHttpRequest object
Side note: Although obviously you can use XMLHttpRequest and the DOM methods directly, note that there are cross-browser differences (and outright bugs), which can be smoothed over for you by a good library like jQuery, Prototype, YUI, Closure, or any of several others. They also provide a lot of useful utility functionality, allowing you to focus on the actual problem you're trying to solve rather than the details of the plumbing.
For example, here's how you would send an Ajax request to a server using jQuery and have an element on the page updated with the HTML fragment the server sends back:
$("#target").load("get_the_data.php", {article: x});
That says: Request an HTML fragment from get_the_data.php sending it the parameter article with the value from the x variable, and put that HTML fragment inside the element that has the HTML id "target". That would be a good 10 lines of code if you didn't use a library. Now, that's not a lot, but repeat that over and over (and in the process deal with an IE bug around looking up elements by their id), and you see how it can add up.
I do recommend you read the references above so you know how the libraries are doing what they're doing (it's not magic), but there's no reason not to leverage the hard work people have done to make this stuff easier.
I think what you need is AJAX. It is a way of contacting the server with only partial page refresh. I don't know how it works with php as i use asp.net but here is a link that may help.
It's Ajax turn. What you need is a technology called AJAX. You can find something usable in jQuery library that provides different methods to work with Ajax more easily.
http://api.jquery.com/jQuery.ajax/
You will create a relation with your server-side programming language and your database through a client-side scripting language (Javascript in this case).
This is an example of these realations:
http://jqueryui.com/demos/autocomplete/
You have to look into push/publish/subscription technologies. Few that i know are pubnum and commet
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.
How do you go about designing/structuring a completely ajaxed MVCish style site? I guess what confuses me the most is that there would only be one view that adapts and changes to the user actions...
I'm looking to build a really simple app, both front end and back end in this style.
Yeah, you'd be building a "front controller" of sorts that would route the views (there would be more than one) to the page for rendering in divs. My company does this with two of its apps and it's lightning fast and a great way to go for a simple app...users love it. Key to the success is a well-formulated layout with well-defined divs to receive the content. As you'll be repeatedly writing and re-writing to them, you have to ensure ahead of time that they are able to handle data of various sizes and amounts as you'll have very few ways to effect layout per page on the overall container....besides after-the-fact hacks (just say no!)
Do as you would with controllers and models and the views (the front-end view code) In some cases our code will use an intermediary page (we call it a mid-model) to generate Jquery data in a JSON string format. It's not quite a model in that case, as it takes action like a model but sometimes returns more than just JSON depending on the needs of the Jquery element.
An interesting offshoot of this system is the use of a program called XAJAX. It's a PHP library that facilitates AJAX called directly to PHP functions, so it eliminates the need to do intermediary JSON generating pages like Jquery uses. For those who understand PHP but struggle with Javascript, this can be an easier solution to grasp. While the documentation hasn't proven very strong, it's a very powerful tool.
I would do all your views as usual (except they would only be HTML fragments that would be inserted into the page) and then have an extra "special" controller and view that loads your views via Ajax. When a link is clicked or something like that the JavaScript makes an Ajax request to the special controller with the view you want to load. The special controller then renders the view and sends it back to be inserted into the page.
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.
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.