In page.tpl.php of Drupal, the following code has variable $page which contains the html codes that are required to render part of the webpage.
<?php if ($page['content']): ?>
I'm trying to retrieve the updated content from DB at an interval and update a DIV without refreshing the whole page. My question is, where can I find the DB query codes from which $page came about?
page['content'] variable
When Drupal displays the "content" variable, think of it as big array of data that will be rendered in a specific section of the page.
Before that happens, it either retrieves data from the block settings of the native interface (block visibility settings) or from custom modules that override this original settings like f.e. context (https://www.drupal.org/project/context).
>> Template files
The template files are kinda like the last stop where data is built and ready to be rendered and delivered to the client.
In general, the best practice is keep the render templates intact and keep the logic and variables manipulation at the pre_hook levels .
>> So if you do wanna have "programmatic" control over what you can display you can f.e.:
Render specific nodes with "node_load" function and then using node_view($node)
f.e.
$node = node_load(23); //23 is random a node id
if (isset($node)) {
$node_data = node_view($node,'default''); // here's my node display data
print drupal_render($node_data); // here's my html
}
Render templates that aggregate different data with the "theme_render_template"
https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_render_template/7
Render views by using views_get_view('view name') like stated before.
Hooks like these might help you in adding/modifying the content you wish
template_preprocess : (hook templates
hook_node_view : (alter node array data before render)
page_alter : (alters page variables like content, header and so on)
hook_views_pre_render : (views is built, can alter render process)
hook_panels_alter : (for page manager and ctools approach)
>> Database queries
Doing a straight query to the database can also be done through the database api and then rendered, but be aware you might miss out the drupal hook power and end up having high maintenance code that escapes the convenient and safer Drupal way.
Hope it helps!
That content comes from inner node templates (if you are displaying node on that page) or i.e. view template....or...depending on what page you are displaying. But if we assume that you are displaying node page in some content type "player" you created content will "come" from template file "node--player.tpl.php"
https://www.drupal.org/node/1089656
Inside that file you can do database query (by using Drupal's database api) or even easier use Drupal's views module to query database:
https://www.drupal.org/project/views
What you are trying to do :
"I'm trying to retrieve the updated content from DB at an interval and update a > DIV without refreshing the whole page"
, is usually done with Javascript sending Http requests from the browser and not from PHP code executing server side in a Drupal template file, and is named AJAX. Doing AJAX with Drupal could be done in multiple ways, one of the recommended ones is with the use of the "Drupal AJAX Framework", resulting in PHP code with "Drupal AJAX API" calls server side that will generate for you the appropriate JavaScript client code renderer in the Drupal's output. The Drupal "Views" module may also help in this task, being "aware" of the Drupal AJAX framework. A good understanding of general AJAX mechanisms and of the Drupal AJAX framework are required to do this properly.
Related
Has anyone faced this feature request and were able to resolve it? We have a webapps that is capable of creating a form as a template. That template will basically be called and user will need to fill out the form before it got push into the db. So the form is created directly inside the application and the fields, labels and variables are all defined when the form is created by user using the apps. Since the form is always going to be changing, I can't hardcode the activity in android and have to create it manually and recompile every time a new form is created. Is there a way for us to read the label, variables setting that's stored in db either in XML format or called as JSON and build the form dynamically everytime the form is called via android? Am I making any sense? Please advise?
Yes. Everything you do in XML (view creation, positioning etc) can be done dynamically via code as well.
A simple way would to be to put a single ScrollView with a single LinearLayout inside it. Then in your activities onCreate(), you can read your JSON or XML file just like any other file (you can store this is assets folder or maybe query it from your backend). Then depending on your variables you can initialize and add TextViews and EditText's to the LinearLayout. The ScrollView will expand infinitely to accommodate all your form elements.
Just make sure you don't do any long-running operation such as querying from your backend or reading from your file in the main UI thread. Another caveat is that if ScrollView does not recycle views and putting too many views in it (say more than 20) can make your application run out of memory and slow down/crash.
You can create a form in relative layout having all the fields/view you require in XML, then on Runtime in code According to your label name in db or whatever you are using, you can hide/show the fields/view which are needed dynamically. This way you can preserve the position and setting of each field as when 1 view is hidden other views are going to take its position.
Goal
I would like to be able to dynamically create javascript and serve it based on preset configuration from the application. The url of the javascript resource can remain the same. The idea is to make available the option to change javascript parameters depening on backend configuration.
An example of this:
The administrator has a set of classes that when clicked upon open a modal pane for the end user. lets say that those classes follow the format of *_modal where the * portion of the class will indicate a portion of the url where the content of the modal pane will be pulled from via ajax.
For example:
click me
would then trigger an ajax event on click where the contents from #contents would be pulled from http://www.myurl.com/modal/orange and displayed in the div #modal_output at the client side.
lets say for some odd reason the administrator for the site decided that he wanted to change the id of the display modal pane for some reason to #modal_output_view . Normally this would require some modification of the javascript and possibly the static output of the page.
I would like to forgo that and offer a configuration option whereas the administrator can choose what the div id would be for the modal output.
At run-time the resource would be requested, php would grab the configuration value for that div's id and return a string in the form of a javascript resource.
Secondly I will be using magento, is there a good way to improve the performance via cache?
Is there any way to use a cdn?
Questions
1) I know how to do the configurational portion, asside from doing this within an appended block or inside of a template file:
<script type="text/javascript">
(function(){
configuration_value = <?= Mage::getStoreConfig('my/config/value');?>;
})();
</script>
is there another easier way to interface between magento's configuration values and client side javascript?
2) Will this work correctly? are there any issues I might face? The key being the .php extension
3) Are there existing core javascript classes/methods that may be useful? Any documentation?
Hello guys I newbie question :) - I am currently using PHP/Zend and now I need to display a form and other content in one of my pages. I do not want the page to reload and I cant use a pop-up window so the best option is to sort of dynamic display a "square" in the middle of the current page with this form being load on the go... this way i could have my pages (forms, text, whatever) being pulled in this square.
In order to keep compatibility with older/new and different browsers, what would be the best choice? DOJO - that is already in Zend, JQuery, or just HTML5/CSS3? Besides, if anyone could point me to some references of where can I find this info it would be great!
AJAX is the most common means (Asynchronous Javascript And Xml) to do this- which uses Javascript to poll other scripts (can be .php pages) which then return predefined output based on the request- this output can be content to inject into a page, or data which can then be interpreted by your page for another action (i.e. the output from another page etc..).
In this instance, your .php page could include JS (javascript) in the head, whether linked or inline, which would contain details for launching an AJAX request- namely, how often or on what trigger (button press etc), by what means (POST or GET), what is sent (any other variables you wish), what the target script is (the script which will handle the request and output your required content/data), and what to do when the response is recieved (i.e. which element on the page should be updated with the response).
A little about AJAX:
http://webdesign.about.com/od/ajax/a/aa101705.htm
http://webtrends.about.com/od/web20/a/what-is-ajax.htm
Likely the simplest way to begin is to use a pre-existing Javascript library like the ubiquitous jQuery (jquery.com), there are thousands of tutorials out there for it, and though you will need to do some Javascript programming, the library has meant that you can rely on fairly simple syntax to do so (as simple as $('#myelement').load('mypage.php')):
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
http://www.sitepoint.com/ajax-jquery/
http://yensdesign.com/2008/12/how-to-load-content-via-ajax-in-jquery/
In simple terms:
You have your php page with the element (area) that needs updating (page A)
Build another php script which outputs the content you want 'refreshing', e.g. the latest news stories, each time it is run (page B)
Link to the jQuery library in your header section (page A)
Write a simple jquery function in the header section of page A, which says every X seconds/minutes (or on demand), run an AJAX request to fetch the content of page B and insert into an element (DIV) within page A
---updated---
If you wish to use DOJO as opposed to jQuery, there is also a wealth of resources available:
http://dojotoolkit.org/documentation/tutorials/1.6/ajax/
http://www.infernodevelopment.com/dojo-ajax-tutorial
http://startdojo.com/2010/01/02/simple-ajax-form-tutorial/
http://today.java.net/pub/a/today/2006/04/27/building-ajax-with-dojo-and-json.html
http://www.ibm.com/developerworks/web/tutorials/wa-dojotoolkit/index.html
http://www.roseindia.net/dojo/
Context
I'm working on a project that I'd like to make more dynamic with PHP + AJAX.
I'm using jQuery for the AJAX part because I totally suck in Javascript, and anyway it seems to be worth something.
I reached a point where my application needs to use a form to send a post, and I want to use an ajax call to perform this action. In the page I'd like to send the post, there is also a list of the most recent 15 posts submitted.
First question: Should I just forget about it and use just PHP?
The action
The user writes something in the <textarea></textarea> and clicks on a <a id="myPostSubmit">Submit</a> that is the handler that I'll manage on the jQuery script with something like $("#myPostSubmit").live('click', function() { /* here i make the ajax call */ });. If the post is successfully submitted we are going to do something (I'll talk about it in the next section), either we will alert the user using my showAlert(text) function, that shows a black box for 4 seconds with the text in it.
Second question: Should I manage the click event in any other ways? Should I create a function, such as sendpost(post) and attach it into the HTML onclick="" event?
If the post is successfully sent
I'd open a discussion about 2 options:
We refresh the page [not actually
loading the entire page but making
another ajax call that retrieves the
posts lists and makes disappear the
old one, load the PHP file to
retrieve the new posts (including
the one we just sent), and then make
the post list appear]. Pro: 1) We are sure that what the user is reading after the post list is loaded is the real post sent. So it actually double checks the action. 2) We load also some possible posts sent in the mean while. Cons: 1) We have to create a PHP file that gets the post list template, slicing the template of that page in 2 files. 2) It doesn't really seems that smooth to me.
We just use Javascript to get the post template, add it to the list. Pro: 1) We make it really smooth, without reloading the entire page. 2) We don't need of any PHP file to reload the page. We just use Javascript (jQuery). Cons: 1) How do we get the post html template to add it to the list? 2) How do we get the user (logged) informations without PHP?
Third question: Is it better the 1st or the 2nd solution? Would you provide a even better 3rd solution?
The PHP page
The PHP page that will receive this AJAX call is : ?p=action&a=sendpost. The page require $_POST['myMessage'] to be set and not empty and nothing else. The page itself will get all the user infos from the cookies and will manage to perform the needed query.
The application
It is divided in 3 parts: App, Template, Library. Basically each page of the application has its own .app.php and .tpl.php file.
The .app.php file manages the building
of the basis of the page, using classes
and other stuff from the library. In
our case it retrieves datas from the
database and put them into
variable.
The Template is called at the end of the .app.php file. The .app.php file send to the template the retrieved data and the .tpl.php file outputs them.
The library is used to contain the classes and functions we need in the application file.
Fourth question: Is this a good way of manage my web application?
Edit: What about returning the alert message to the user?
I read about an option, inside $.ajax() that will manage the response on success or in error. The documentation about it is very simple and I didn't get it.
Fifth question: How should I return (from the PHP file) the error
or the success?
First question: Should i just forget about it and use just PHP?
Well, you application will relay on JavaScript if you use ajax, this days i think it just fine ;)
Second question: Should i manage the click event in any other ways? Should i create a function, such as sendpost(post) and attach it into the HTML onclick="" event?
Create a function and bind onclick. Code will be more readable ;)
Third question: Is it better the 1st or the 2nd solution? Would you provide a even better 3rd solution?
My solution: ajax submit the form and on callback insert new comment in to the list or display error message if user can't comment.
Check jQuery serilize() for submitting forms data with ajax.
Fourth question: Is this a good way of manage my web application?
It's just fine ;) When you application get's bigger you will have to redesign it, but don't do it know, do it when current solution becomes to hard to work with.
Read some good book on building MVC framework. And on programming patterns in general.
You seem to be on the right track with everything. There are lot of opinions called "best practices" about how to exactly attach event handlers, how to reload the data on the page and how to organize your application, etc, but I personally would rather build more software instead of worrying about details like that. The details will come to you eventually.
I personally find that updating whole chunks of server-side-rendered HTML on the page is more robust solution, but I have seen people getting excellent results with templates.
I'm working on a web UI control called Folder - it basically mimics Windows Explorer folder - you see a grid of items inside a rectangle and can drag an item around, drop an item inside a different instance of the control, add new items and so on. each item is made of an item template - basically some php code that dictates the look of the item, for example an item template might look like this:
my_item_template.php:
<h3>my item</h3>
<p>i'm an item</p>
when dragging the item i want to replace it with a different template, for example:
my_item_drag_template.php:
<h3>my item</h3>
<p>i'm being dragged</p>
one page may host many different kinds of items, each with its template, its load template, its drop template and so on. my problem is moving all these templates from the server side to the client side.
what i'm doing now - in the server side stage i figure out all the templates that i'll need and include them on the page, hidden (display:none). whenever i need a template (for example when the user starts dragging an item and i need its drag template) i locate it, clone it and use. i'd like to avoid having all this code hidden in my page, maybe store it in a jquery's $(folder).data or something. however, i still need to move it from the php. one option would be to insert the templates to $(folder).data and remove them from the page on page load, but i'd rather avoid it (it adds unnecessary dom manipulation). are there any better ways?
It's certainly an interesting problem, but I don't think you are too far off from a good solution by storing the templates in the dom in a hidden div. Unless you have alot of templates, that generally is a great way to have easy access.
Another option is to ajax request a template when you need it. You can use jQuery's $.load function to get a chunk of html and inject it into an element.
$('<div class="newItem" />')
.load('getTemplate.php?template_id=newItem')
.appendTo('body');
You would obviously have to fill the new element with real data, but you can still do it in a single call.
There is obviously a performance hit by doing this, but the structural gain is pretty significant if you don't mind making the requests. It allows you to define your templates in your backend just like you would a normal page, instead of mucking them all together in a hidden div at the bottom.