PDA

View Full Version : InnerHTML Question



guvenck
Mar 13th, 2007, 05:11 PM
Hello, I know the topic is much more related to strings, but anyway:

I have a function like this:



function Panel(loggedin,id)
{
box = document.createElement('div');
box.innerHTML = ''+
'<table>'+
'<tr>'+
'<td><a href="books.php?op=showinfo&id='+id+'">Book Info</a></td>'+
'</tr>'+
'<tr>'+
'<td><a href="lists.php?op=add&id='+id+'">Read Chapter</a></td>'+
'</tr>'+
'</table>';
}



Depending on the loggedin variable (can be 0 or 1), I wish to display the Read Chapter <tr> just to visitors who are logged in.

Similar in PHP:



function Panel($loggedin,$id)
{
$innerHTML = '';
$innerHTML .= "<table>";
$innerHTML .= "<tr>";
$innerHTML .= "<td><a href=\"books.php?op=showinfo&id=$id\">Book Info</a></td>";
$innerHTML .= "</tr>";
if($loggedin == 1) {
$innerHTML .= "<tr>";
$innerHTML .= "<td><a href=\"lists.php?op=add&id=$id\">Read Chapter</a></td>";
$innerHTML .= "</tr>";
}
$innerHTML .= "</table>";
return $innerHTML;
}


How can this be done in JS?

BarrMan
Mar 13th, 2007, 05:27 PM
function Panel(loggedin,id)
{
var text = "";
text = '<table>';
text += '<tr>';
text += '<td><a href="books.php?op=showinfo&id='+id+'">Book Info</a></td>'+
text += '</tr>';
if(loggedin)
{
text += '<tr>';
text += '<td><a href="lists.php?op=add&id='+id+'">Read Chapter</a></td>';
text += '</tr>';
text +='</table>';
}
return text;
}

glenngv
Mar 13th, 2007, 05:33 PM
function Panel(loggedin,id)
{
box = document.createElement('div');
box.innerHTML = ''+
'<table>'+
'<tr>'+
'<td><a href="books.php?op=showinfo&id='+id+'">Book Info</a></td>'+
'</tr>'+
((loggedin) ? '<tr>'+
'<td><a href="lists.php?op=add&id='+id+'">Read Chapter</a></td>'+
'</tr>' : '') +
'</table>';
}
But why not do it in PHP? It's better to do it server-side so that users won't see the business logic behind it.

guvenck
Mar 13th, 2007, 08:01 PM
I use an external js file called panels.js and the Panel function is inside it, with some additional functions like ClosePanel etc. This function displays an overlay div (panel) that includes over the link when clicked (using onClick function).

How would you do it in PHP?

glenngv
Mar 13th, 2007, 10:43 PM
You can dynamically output Javascript codes using PHP (or any server-side language for that matter) the same way you output HTML tags.

function Panel(id)
{
box = document.createElement('div');
box.innerHTML = ''+
'<table>'+
'<tr>'+
'<td><a href="books.php?op=showinfo&id='+id+'">Book Info</a></td>'+
'</tr>'+
<? if ($loggedin) {
echo "'<tr>'+";
echo "'<td><a href=\"lists.php?op=add&id='+id+'\">Read Chapter</a></td>'+";
echo "'</tr>'+";
} ?>
'</table>';
}
The syntax may be wrong as I don't know PHP but you get the idea.

If this function is in a js file, you can have a php file as an external js file.

<script type="text/javascript" src="panel.php"></script>
Then inside panel.php, you need to have a line that sets the response type to "text/javascript".