I just wrote some code, looked it over, and wanted to cry. Lines that end in .’\’);”>’; cannot be a good thing.
I’m writing an ajax function to return a new row to add to a table. The row uses javascript to be user editable.
$ident=mysql_insert_id().'_c_label';
$html='<tr>';
$html.='<td class="label" id="'.$ident.'" onclick="editTextStart(\''.$ident.'\');">';
$html.='<div>';
$html.='<span id="'.$ident.'_field">'.self::default_label.'</span>';
$html.='<input id="'.$ident.'_input" type=text onblur="editTextEnd(\''.$ident.'\');" onclick="editTextEnd(\''.$ident.'\');"/>';
$html.='</div>';
$html.='</td>';
$html='<td>';
$html.='</td>';
$html='<td>';
$html.='</td>';
$html='<td>';
$html.='</td>';
$html.='</tr>';
return $html;
So how should I be going about this to get html and javascript variables out of my php?
Use an external JavaScript file, which you include with a
scripttag just before your closing</body>tag (or in thehead, there are trade-offs — off-topic discussion of them below). You can hook up event handlers at that point by using DOM selectors and/or IDs andattachEvent(IE) oraddEventListener(standard).For instance, say your structure looks like this:
Then with straight JavaScript+DOM methods, you can hook up a click handler to the cells like this:
(Or you can define
hookEventin a way that only looks for which version to use once, but it would be over-complex for the example above.)Off-topic, but if that
hookEventlooks awkward, a using a library like jQuery, Prototype, YUI, Closure, or any of several others can really help smooth these browser differences out.For instance, with jQuery:
(Edit Sounds from your comment below like you’re using jQuery, so here’s a live example for the above.)
With Prototype:
Off-topic: I said above to put your
scripttag at the end of the body. That’s just one choice. If you do, the DOM will reliably be ready to be searched, etc., you don’t have to wait forwindow.onloadwhich happens much, much later or rely on “ready” events. But if your script file isn’t coming from the browser cache, there’s a delay while your page may be showing (and your user clicking) before you hook things up. On the up side, your page displays more quickly (because the script file didn’t hold things up by being in thehead); on the downside, you probably don’t want them frustrated by clicking before you’re ready (although the gap is quite small). So where you put it is a balance between those things. If you’re worried about people jumping on clicks, put the script inheadbut then have a small script tag at the end ofbodythat calls a function defined in the file that hooks things up. Or use areadyevent (most libraries provide them). Or there are sophisticated strategies to use a small inline script to capture and defer clicks.