Should my html markup be generated on the client side? - php

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.

Related

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.

OnHover run php script

Okay I'm not really sure how to approach this. I have a user-generated post board where people post, it drops down onto a list of a bunch of posts. When you click on the ID number of the post it will bring you to a separate page with just that post and the comments on the post. I want it so when you hover over the href it drops down something that tells the user there are x amount of comments on this post. This way people know if there is comments without switching pages and also being able to be able to click the href still and go to the postid page.
I assume some ajax/jquery/javascript would be used to accomplish this but since I'm fairly new to ajax and jquery I'm not certain how this would be done. Thank you!
For a hover effect, it would be better if that information was already stored on the page and just hidden. Then when the user does hover, you can just un-hide it and have it positioned where you want, and then hide it again when their mouse leaves the area. Using AJAX requests for this purpose would waste away a lot of HTTP requests for such a tiny amount of information.
Really, you could do the hover effect using pure CSS if you wanted too (I would).
Since a hover happens fairly often, I wouldn't use it as the default event to fire an AJAX-request. This would increase the HTTP-traffic enormous. See if you can fetch this information when the page is build (and put it in then) or use something else like a "preview"-button for the event.
Anyways, this would be the basic workflow if you want/need to use AJAX:
Write a PHP-script (or any other language you use) which fetches the number of comments (and what else you want to display) from the database (or where your data is stored).
This script should then be called via AJAX (with $.ajax() from jQuery for example). As the expected return-type you would then use json.
The script which fetches your data would then create an object, use PHP's json_encode()-function to encode this object to JSON and echo it out.
This JSON-object will then be available in the success-method of the ajax()-method from jQuery. Then, you can access its members (e.g. the comment-count).

Send a post with PHP + AJAX

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.

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.

how to pass information from php to javascript

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.

Categories