how to pass information from php to javascript - php

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.

Related

Create paginated Drupal form. (Drupal 6)

I am trying to create a form which provide a checkbox element on each row. Problem is that I have 2000 rows which takes some time to load and also it is not easy to navigate through whole list.
Is there a way to create some kind of pagination in Drupal form ?
There's no built-in pagination of field values within the context of a larger form that I'm aware of. Instead, you'd probably want to consider a Javascript solution, where you load all 2000 form values, but you use JS and CSS to hide all but the first page. Then you create Javascript forward/back and page links which dynamically hide the first "page" of checkboxes and load the page in question.
The reason I recommend this, instead of an AJAX request that loads only the first 20 records and then dynamically loads more via a pager, is that you'd have to separately track and store which values had been checked (since the AJAX would literally throw away and reload the next 20 checkbox values). By contrast, if it doesn't slow the page down to load all 2000 checkboxes as, say, 100 individual sections behind the scenes, and then use your custom JS pager to show/hide the pages, your user could check and uncheck while paging and all the values would be remembered. (It's an often overlooked feature of HTML forms that they retain their field values even when hidden via CSS, which can be super helpful when you're aware of it).
I don't think a code snippet would be too useful here because this is a fairly open-ended problem, but the basic process would be:
Use hook_form_alter() to change the specific checkbox group field(s). Specifically, you would use markup to add the paginator controls after running the database query to retrieve the results and determine the number of pages.
Also as part of using hook_form_alter(), you would loop a page at a time and generate all 100 (or whatever number) pages of checkbox options, setting all but the first page to display:none in the <div> tags surrounding the checkbox options.
Create JS or jQuery functions in your site's custom theme, or put the code into an includes/ folder and load it dynamically through hook_form_alter (not elegant - I recommend always having a custom theme or sub-theme available). This function would listen for the link press and the current page and hide/show the proper CSS blocks.
If you wanted to get fancy, you could also create a JS-enabled page number field where you could type in a page number and hit Enter, or a search feature that would return individual results (more complex since now you'd have to be able to show/hide all individual records), and a check all/uncheck all feature for individual pages. Have fun!

Should my html markup be generated on the client side?

I have some server side code that outputs a <ul> of items that the user can edit and post changes back to the server. I am now working on an "Add New" feature that adds a new item to the <ul> and will be posted back to the server when the 'save changes' button is clicked.
When the user clicks the "Add New" button, I execute client side code that appends <li> markup (same markup generated by my server side code).
What is bugging me is the redundancy. Meaning that if I should change the <li> markup, I would have to open both php and js files to do the change.
In the interest of eliminating redundancy, should I only output the <ul> data from the server and let the client code generate the markup? What are the performance hits from a concept like this?
You could do a hybrid using the JQuery .clone() method.
Your back-end code could produce the structure of the <li> elements when it is creating the initial code and then, if the user wanted to add a new <li>, you could grab on of the existing ones to use as a template, .clone() it, update the values of the clone with the new data from the user, then append it to the <ul>.
The only issue would be if there was a possibility that there might not be any <li> elements on page load, so the .clone() call would have nothing to reference. There are ways around that if it's an issue though (e.g., a JS string template of the <li> format that you want to use, that could be used like this: var newLI = $(liTemplateString);. Again, this template could be created by the same code on the back-end that would create the actual <li> elements on page load . . . it would just be creating a JS variable as well.
Amongst other things, this would allow you to update the <li> to the page immediately and then send the update to the back-end using Ajax, to update the "master" version, without making the user wait on that process.
In the end, my personal preference is to let the back-end do as much of the processing as possible and only you client-side code to handle the things that the back-end can't do, so I would shy away from dumping data and letting the front-end handle building the list, if the back-end can do it as it's creating the page.
Theoretically, you can just append the new <li> with no problems. However, for most uses, you will want the server to hold the master copy, thus re-serving the entire <ul> for each update.
If you're using .ajax(), this will be a nearly immeasurable difference in load time.
Let me suggest the Third Way: duplicate an existing element and change its properties and/or content as needed.
jQuery has .clone(), but it can be done with plain DOM or any other library as well.
This way you don't add unneeded latency and you keep your client-side code relatively independent of any markup changes you might have to do. Meaning that if you add or change any markup that's unrelated to what the JS needs to do (for example adding a class="" or an inner <span>) and your JS is sufficiently generic (for example getting the element to clone and the one whose text to edit from attributes) then you don't need to update it.

Multiple views for the same form in a web application

I have a situation where I have several ways to perform the same activity in my php web app.
There is the "Manage Widgets" section of the app which has a form for creating new widgets and a list of existing widgets.
Then somewhere else in the app there is a button that pops up a dialog to add a new widget.
Then on the home page of the app there is another place where a form is embedded to add a widget (think home page portal).
My question is: What is the best practice for this? In this case all of the forms will be essentially the same. So my first instinct is to use the same code for all three of these scenarios. On the other hand, space on the home page could be smaller and layouts may have to differ between the three.
So even though it would be repetition, is it better to duplicate this form 3 times (there is a proper model layer, so the duplicated code would not include the logic to add/edit the widget)? Or try to force a single view in all of these scenarios? Both seem wrong to me and I am hoping for some ideas to discover some sort of middle ground.
One approach would be to have the markup (not the styles) for the form as a standalone file, which can then be included from anywhere you like.
You can then use AJAX to submit the form to a specific PHP script that handles the form submission and returns a meaningful JSON response. You can then display and style this JSON response on the page in question.
This way you have a single form (that can be styled differently) and a single handler for any view that's required to use the form.
i mean, the best way is compose form from other forms (Dont repeat yourself). You can use different templates for same form to change appearance of final form.
For example/idea you can check forms what is used in Nette Framework (http://doc.nette.org/en/forms)
T.
If you are just changing the styles, not the markup, I think the best approach is to add a specific class to the form element and then use Javascript (not Ajax, justa Javascript) to alternate between these clases as you need.
If your application do not use Ajax at all and you just generate web pages with PHP, is a simple matter of decide which class you form shoud have.
In CSS, you do something like this:
form.main { ... }
/* main form rules */
form.other { ... }
/* other form rules */

How to prevent a modal from being drawn more than once?

This is a bit more abstract than the usual questions which I know goes against the spirit of things, but I'm hoping that I can still get a good response.
Here's the issue. We have a fairly complex web application that is written in PHP. The purpose is relatively unimportant, but simply put: We are using Comet / AJAX / JSON / JavaScript / PHP / MySQL (NO jQuery, however, native JavaScript only) to render controls that display data in real time. Throughout this application we are rendering popup modals using native JavaScript. It's fairly complex logic that tests for the existence of a modal with the same name on the page and prevents creating new versions of the same, and of course once created a layer is created to prevent interacting with links beneath.
The issue is that we have at least one modal that can be called multiple times before it is rendered on the page due to the time it takes the AJAX call to collect data from the database and assemble it for presentation. If a user were to 'double click' on said link they would be presented with two modals, one on top of the other. I've been able to actually render 8-10 of these. Interacting with the topmost modal appears to be broken because the user is actually effecting collapsible headers on the bottom-most modal. Once you start closing the dialog boxes and get to the bottom you can see where you've clicked.
So, my issue is this: What is the best way to prevent this behavior?
I've considered simply adding a function to the onClick event that would remove the onClick attribute from the link after the first click with a minor timeout (say 500ms). I've also considered trying to implement bit testing logic that would count clicks and only actually first the event after the first click and reset when the modal is closed.
What I'm wondering is if someone has any thoughts or suggestions or even has tackled a similar issue and has some insight on best practices to accomplish my goal in this instance.
Thank you very much.
You can unregister the click handler once it fired:
var element = ...,
myClickHandler = function(event) {
// ...
element.removeEventListener('click', myClickHandler, false);
// ...
}
element.addEventListener('click', myClickHandler, false);
In this case, I found the simplest solution to be the best but I would still love to hear other feedback if'n it's out there.
In this case I found that the order of operations was the issue. I was awaiting the AJAX response to generate the body html for this modal. I changed the order to instead create the modal immediately using <p>Loading...</p> within the body of the modal. Then, when the AJAX was completed and I had my new body text, I just injected it into the modal's content area with a neat bit of code and Bob's your Uncle, we had jackpot.

Help changing content on the page using both php and javascript

So I am trying to have a dynamic tabs kind of thing using both php and javascript. To make it much easier to understand, remember the two choices on facebook (Recent news and most recent) or something like that, when you click on one of them it just changes the content that you see in the middle without updating the page. i know how to delete the content in a div for example, but after deleting the content in the div (innerHTML = "") I want to populate it with the option chosen from the database.
So let's say I have an option (all) and an option (only this)
The default is all so when I run the page, I will just get all. However, if I click on only this, it will clear the div "my header" and will replace the content with the latest content from the database (database) and display it.
For that I need both php and javascript, is there a sample or an easy way to do this before i start digging around.
((Sorry if is not clear but the facebook example should be clear enough))
Whatyou are looking for a is AJAX/PHP approach.
Clicking on the tab
The current content gets removed. This is possible because it has a unique "id" attribute in the HTML code
The server is asked for the new content. This is the AJAX request that will be triggered after/while/... the content is removed.
The server sends back the code. This can be HTML, JSON, XML or similar.
You script recieves the answer, may "do" something with it (like some parsing or similar)
The content will be placed on the page (again, this is possible due to an unique "id"
This is basically the way it is done.
Check out the different JavaScript frameworks. They all come with nice AJAX support:
jQuery
MooTools
dojo
Prototype
And of course, SO is also a nice place to look at: https://stackoverflow.com/questions/tagged/ajax+php
What you're talking about is ajax.
I would suggest a javascript library to help leverage this, like jquery.
It can be as cool as
$.post('serverScript.php',
function(data) {
$('#idOfDivToUpdate').html(data); //shove script data into div
},'html' );
tutorial.

Categories