I have a PHP class/object which acts as the primary data source for my webpage. I'm using jQuery/Javascript to provide a dynamic interactive experience for the user. Both parts work independently really well.
I'm now trying to find an elegant and clean way for the javascript library I've written to access and update data stored in the PHP object.
Communication Javascript -> PHP: I've previously always created a PHP wrapper that takes input over the GET/POST and routes the data to the appropriate PHP function. This works well enough but surely there is a cleaner way to interface from javascript to PHP?
Communicating PHP -> Javascript: Previous websites I've written have seen communication from javascript to PHP only. The PHP would output HTML which Javascript would place in a container (Standard javascript usage I guess). However, in this website, the Javascript library I've written requires structured data in return which it processes to perform multiple UI updates. It seems that looking into JSON would be the right thing here but there seem to be a variety of options.
I would love the advice on the best way to get your PHP and Javascript communicating in both directions is a clean and elegant way.
Thanks!
Related
I want to refactor my php site which supports a front end which makes ajax calls.
Currently my ajax calls a php page which stores all my backend code and based on the parameters passed from the ajaxcall it determines which php methods to run.
I realize building a rest API as the php backend woudl be better but was wondering if there is another alternative? ie a good way to structure a php page that allows for clean re-usable ajax calls from the front end?
Thanks
There are multiple ways of doing such kind of web development. It could be REST based micro framework approach in PHP where you invoke different views. Another could be to invoke the PHP code solely based on the input or interactions on the view (HTML/Javascript) using AJAX. Depends what you want to achieve.
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.
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.
Maybe this is gonna sound naive and all, but is there something even remotely close to a php crawler for ajax based websites?
The problem is that vanilla PHP doesn't understand how to parse JavaScript, generate the JavaScript environment, and interact with everything. In order to theoretically do it, you would have to extend PHP via the C API and interface it with a JavaScript library. The scale of this is quite large depending on how many resources you have.
Not automatic crawlers, because they would need to understand the javascript code and need to know what's going on.
What they could do is use the same calls as the ajax enabled script would do, so you can get at the raw data.
But this would mean you need to have a very good understanding of the webpage and which url's it's calling, and is quite labour intensive.
So the answer is: No, as far as I know, they don't exist.
you can use the phantomjs library to excute js.
https://github.com/ariya/phantomjs/blob/master/examples/waitfor.js
I've noticed that a PHP frameworks; Zend, Cake, and Symfony; seem to either generate JavaScript or allow it to be embedded as a string into the PHP itself. Is this a good idea? From people who've used these frameworks/libraries, what has been your experience working with the Ajax and JavaScript helpers? Has it been easy to maintain? Does it cut down on development time?
No it is a bad idea,
Generated javascript usually means that the site won't even function without it (like many asp.net sites). If you want to do more complex things or want to enhance accesibility there is no other way around than clearly seperating HTML from CSS and Javascript.
Seperating Javascript also makes your code more maintainable as you do not need to have your client side frontend developers mess with your PHP code and the other way around.
The best way to use Javascript is to first let php generate your html, then at the bottom of that page include your javascript files and use functionality like onDomReady. This also doesn't force you to use a particular library just because your framework is using that as base for its generated Javascript.
This is quite a subjective question, but personally, I wouldn't want a back-end framework to do this for me. It's better to keep a clean seperation between business logic, presentation, and client-side UI behaviours for a number of reasons:
More maintainable applications.
Easier to test individual components.
Easier collaboration. Different skill-sets can work on different areas.
Should help ensure your application does not rely on JavaScript in the end users environment.
Personally, I like to write my Javascript by hand, unobtrusively so that i just have to add an extra event to document.domReady with for example the correct parameters. That little trigger function then gets the ball rolling.
Best practice of the day:
Keep frontend-code and backend code
untangled as much as you can
I would say it depends, like anything. There is certainly some value in having "smart" server side widgets. For example, a widget that "knows" how to update itself through AJAX, or a form which can handle client side, and server side validation. The latter is an example of which it would be costly and time consuming and error prone to rewrite boring validation code in the client. It doesn't require rocket-science javascript, so as long as your framework can handle it unobtrusively, I would actually advise this route.
Additionally, framework code that will handle GUI stuff also (a la ext or something similar), is also not a bad a idea.
However, anything more complicated than that, please use Javascript itself.
I personally love writing my own Javascript so I don't really want it written for me, but I don't see it as being particularly 'dangerous' or 'harmful' to have frameworks that do it for you, as long as it is properly done. My biggest problem with them is that most of them will work as long as you want the standard behavior of a feature, but as soon as you want something a little different to meet your project's needs better it takes so much work to customize it you would have been better served to do it yourself. At least that was my experience with CakePHP's javascript automation.
My experience with the Javascript and Ajax helpers in CakePHP has been very positive.
They have allowed server-side developers to prototype and build features that otherwise would require someone with real client-side experience to do, all without having worry about the quality of the javascript code they "write" and leaving the real front-end engineers free to focus on the advanced client-side features.
It's not a good idea for the PHP to generate Javascript. The only javascript I would recommend exporting is simple JSON assignments like the following:
<script type="text/javascript"><!--
var MyNamespace.info = <?php echo json_encode($info_array) ?>
// --></script>
This is the easiest way to sanitize PHP information and let it be accessible to javascript on the client. However, anything else should be written in actual JAVASCRIPT FILES that are referenced with tags at the head of the document. The only other appearance of Javascript from server-side files, that I would say is alright, is stuff placed into "onclick" and other such attributes.
The rationale for this is that the Javascript should be written and maintained by front-end people who know Javascript, and the site should be able to work (at least partially) without javascript. There is no reason to generate spaghetti Javascript inline.
Check out my PHP framework, PHP On Pie (http://phponpie.com) for an example of how to implement this properly. It keeps the JS and PHP separate, except when exporting JSON as shown above. However it also provides conventions for easy interoperation between the client and server via AJAX.
I believe you should keep languages apart. Even though they can complement each other. That way you can pick the implementation of said language and create a mix that fits you perfect.
I think there is definitely a place for generated javascript. (1)
The number one reason for generated javascript is ease of maintenance. Any dependencies are explicitly encoded and configured from the framework (PHP, ruby, scala, python) itself. For instance if you move your assets or change the upload directory, just update the configuration and watch things Just Work.
Need client side input validation to take some load off your server? (2) Let the framework generate correct validation code derived directly from your data model for you. With generated, javascripted population your framework can serve pre-rendered, static HTML forms from the cache. This could be a huge win if your forms contain lots of selects and options.
1) Assuming that the client has decided that it's OK for the site to depend (more or less) on javascript, with all the caveats that entails. Graceful degradation may or may not be possible or desirable.
2) You need server side side validation too, but you knew that, right?