данные из базы в javascript редактор

anna1978

Новичок
данные из базы в javascript редактор

Всем привет!
Захотелось тут мне вставить в свой админ самый простейший javascript редактор, только размер, шрифт, цвет... Т.к. в javascript я полный нуль, то нашла в форумах скрипт и он прекрасно работает, оставалось только его в пхп страницу вставить. И вот тут начались проблемы. Несколько дней собственных усилий и поисков в форуме ничего не дали, подобные темы несколько раз поднимались, но ни к чему не привели. А мне кажется, что такой маленький скрипт понадобится многим.

Первая проблема заключается в том, когда я делаю запрос из базы, iframe не наполняется ... а остаётся пустым. Если давать значение вручную

PHP:
<?php
$text="Text in Textarea";
?>

<script type="text/javascript"><!--

   .....//--></script>

</head>
<body onload="initEdit('form_content','edit','<?php echo "$text";?>')">

<div style="position:absolute;left:10px;top:10px">.....
то все прекрасно работает, текст (в данном случае "Text in Textarea") стоит в текст ареа. При запросе из базытекстареа остеется пустым, хотя данные из базы приходят - проверено с помощью echo.

PHP:
<?php

mysql_connect("$DBHost","$DBUser","$DBPass");

$result=mysql("$DBName","SELECT text FROM esm  WHERE name='buch'");
while ($row  =  mysql_fetch_row($result)) {
$text=$row[0];
}
echo "$text";
?><script type="text/javascript"><!--

   .....//--></script>

</head>
<body onload="initEdit('form_content','edit','<?php echo "$text";?>')">

<div style="position:absolute;left:10px;top:10px">.....
На всякий случай посылаю полный текст

PHP:
<?php

mysql_connect("$DBHost","$DBUser","$DBPass");

$result=mysql("$DBName","SELECT text FROM esm  WHERE name='buch'");
while ($row  =  mysql_fetch_row($result)) {
$text=$row[0];
}
echo "$text";
?>

<script type="text/javascript"><!--

    var    formu, ifrm, uagent=navigator.userAgent.toLowerCase(),
        isGecko = ( uagent.match('gecko') && navigator.productSub>=20030210 ),
        isIE = uagent.match('msie') && !uagent.match('opera') && (!uagent.match('msie 5.5')||!uagent.match('msie 6.'));

    function initEdit(strFormu,strEdit,strDefTxt) {
        formu = document.getElementById(strFormu);
        if (isIE)
            ifrm = window.frames[strEdit].document;
        if (isGecko)
            ifrm = document.getElementById(strEdit).contentWindow.document;
        ifrm.designMode = 'on';
        if (strDefTxt)
            with (ifrm) {
                open();
                write(strDefTxt);
                close();
            }
        var kids = document.getElementsByTagName('div');
        for (i in kids)
            if (kids[i].className == 'imagebutton')
                kids[i].onclick = tbclick;
        document.getElementById(strEdit).contentWindow.focus();
    }

    function tbclick() {
        var id = this.id;
        if (id == 'CreateLink' && isIE)
            ifrm.execCommand(id);
        else {
            if (id=='FontName' || id=='FontSize') {
                sel = document.getElementById(id).childNodes;
                sel = isIE ? sel[0] : sel[1];
                arg = sel.options[sel.selectedIndex].firstChild.data; }
            else if (id == 'InsertImage')
                arg = prompt('Enter a image location:', 'http://');
            else if (id == 'CreateLink')
                arg = prompt('Enter a URL:','http://');
            else
                arg = null;
            ifrm.execCommand(id,false,arg);
        }
    }

    function processData() {
        formu.content.value = ifrm.body.innerHTML;
          if( !formu.content.value.replace(/<br>|s| /ig,'') ) {
            alert('You did not enter any Text!');
            return false;
        }
        return true;
    }
//--></script>

</head>
<body onload="initEdit('form_content','edit','<?php echo "$text";?>')">

<div style="position:absolute;left:10px;top:10px">

<?
echo "<form onsubmit='return processData()' id='form_content' action='weiter.php? method='post'>";
?>

<div>
    <div class="imagebutton" id="FontSize">
        <select>
        <option>1</option>
        <option>2</option>
        <option selected="selected">3</option>
        <option>4</option>
        <option>5</option>
        <option>6</option>
        <option>7</option>
       </select>
    </div>  

    <div class="imagebutton" id="FontName">
        <select>
            <option>Arial</option>
            <option selected="selected">Times New Roman</option>
            <option>Comic Sans MS</option>
<option>Verdana</option>

        </select>
    </div><br>

    <div class="imagebutton" id="bold">
            <a href="#" onclick="return false" style="font-weight:bold"><img src="pics/newpage/ed_format_bold.gif"></a>
    </div>  

    <br />
    <iframe id="edit" name="edit" width="400" height="200" frameborder="2" marginheight="0" marginwidth="0"></iframe>
    <textarea name="text" style="display:none"></textarea>

    <div style="width: 400px;" align="right">

        <input type="submit" value="Submit!" />
    </div>
</div></form>

</div></body></html>
 

WP

^_^
Не могла бы ты закачать куда-нибудь результат работы скрипта и дать ссылку?
 

anna1978

Новичок
Автор оригинала: Romantik
action не имеет закрывающейся кавычки
Это сделано, но причина в чем.то другомб все работает так же


echo "<form onsubmit='return processData()' id='form_content' action=\"weiter.php? method='post'\">";
 

anna1978

Новичок
Автор оригинала: Romantik
<form name="name" method="POST" action="file.php">
Это мы тоже пробовали.
Мне кажется, дело в <body > таг и javascript.
Ведь переменная $text только там. И когда эта переменная выставляется вручную, то все в порядке, а если из базы данных, то не проходит.
Из базы данных мы же тоже получаем string?

-~{}~ 10.11.06 16:45:

Автор оригинала: WP
А зачем базу данных? Я попросил чистый HTML - результат работы скрипта.
PHP FAQ: Самые основы. Как работает РНР, где он выполняется?
При чем тут основы? Сейчас зарегестрируюсь там и закачаю скрипт.
 

WP

^_^
anna1978
Покажите же HTML, чего гадать на кофейной гуще, давно бы отладили.
 

anna1978

Новичок
Так я же послала и полный текст с html

<?php

mysql_connect("$DBHost","$DBUser","$DBPass");

$result=mysql("$DBName","SELECT text FROM esm WHERE name='buch'");
while ($row = mysql_fetch_row($result)) {
$text=$row[0];
}
echo "$text";
?>

<script type="text/javascript"><!--

var formu, ifrm, uagent=navigator.userAgent.toLowerCase(),
isGecko = ( uagent.match('gecko') && navigator.productSub>=20030210 ),
isIE = uagent.match('msie') && !uagent.match('opera') && (!uagent.match('msie 5.5')||!uagent.match('msie 6.'));

function initEdit(strFormu,strEdit,strDefTxt) {
formu = document.getElementById(strFormu);
if (isIE)
ifrm = window.frames[strEdit].document;
if (isGecko)
ifrm = document.getElementById(strEdit).contentWindow.document;
ifrm.designMode = 'on';
if (strDefTxt)
with (ifrm) {
open();
write(strDefTxt);
close();
}
var kids = document.getElementsByTagName('div');
for (i in kids)
if (kids.className == 'imagebutton')
kids.onclick = tbclick;
document.getElementById(strEdit).contentWindow.focus();
}

function tbclick() {
var id = this.id;
if (id == 'CreateLink' && isIE)
ifrm.execCommand(id);
else {
if (id=='FontName' || id=='FontSize') {
sel = document.getElementById(id).childNodes;
sel = isIE ? sel[0] : sel[1];
arg = sel.options[sel.selectedIndex].firstChild.data; }
else if (id == 'InsertImage')
arg = prompt('Enter a image location:', 'http://');
else if (id == 'CreateLink')
arg = prompt('Enter a URL:','http://');
else
arg = null;
ifrm.execCommand(id,false,arg);
}
}

function processData() {
formu.content.value = ifrm.body.innerHTML;
if( !formu.content.value.replace(/<br>|s| /ig,'') ) {
alert('You did not enter any Text!');
return false;
}
return true;
}
//--></script>

</head>
<body onload="initEdit('form_content','edit','<?php echo "$text";?>')">

<div style="position:absolute;left:10px;top:10px">

<?
echo "<form onsubmit='return processData()' id='form_content' action='weiter.php? method='post'>";
?>

<div>
<div class="imagebutton" id="FontSize">
<select>
<option>1</option>
<option>2</option>
<option selected="selected">3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
</select>
</div>

<div class="imagebutton" id="FontName">
<select>
<option>Arial</option>
<option selected="selected">Times New Roman</option>
<option>Comic Sans MS</option>
<option>Verdana</option>

</select>
</div><br>

<div class="imagebutton" id="bold">
<a href="#" onclick="return false" style="font-weight:bold"><img src="pics/newpage/ed_format_bold.gif"></a>
</div>

<br />
<iframe id="edit" name="edit" width="400" height="200" frameborder="2" marginheight="0" marginwidth="0"></iframe>
<textarea name="text" style="display:none"></textarea>

<div style="width: 400px;" align="right">

<input type="submit" value="Submit!" />
</div>
</div></form>

</div></body></html>
 

anna1978

Новичок
Открыла в броузере источник и вот копия (PROBA TEXTA W EDITOR . в оригинале там пхп взыов текста из базы


PROBA TEXTA W EDITOR


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<style type="text/css">
.imagebutton {
width: 20px;
height: 20px;
border: 0px;
border-color: #FFFFFF;
display: inline; }
img {
border: 0px;
}
#edit {
border: solid 1px #CDCDCD; }
a {
text-decoration:none; }
a:hover {
color: #33FFFF; }
a:visitied {
color:#0000FF;
}
</style>
<script type="text/javascript"><!--

var formu, ifrm, uagent=navigator.userAgent.toLowerCase(),
isGecko = ( uagent.match('gecko') && navigator.productSub>=20030210 ),
isIE = uagent.match('msie') && !uagent.match('opera') && (!uagent.match('msie 5.5')||!uagent.match('msie 6.'));

function initEdit(strFormu,strEdit,strDefTxt) {
formu = document.getElementById(strFormu);
if (isIE)
ifrm = window.frames[strEdit].document;
if (isGecko)
ifrm = document.getElementById(strEdit).contentWindow.document;
ifrm.designMode = 'on';
if (strDefTxt)
with (ifrm) {
open();
write(strDefTxt);
close();
}
var kids = document.getElementsByTagName('div');
for (i in kids)
if (kids.className == 'imagebutton')
kids.onclick = tbclick;
document.getElementById(strEdit).contentWindow.focus();
}

function tbclick() {
var id = this.id;
if (id == 'CreateLink' && isIE)
ifrm.execCommand(id);
else {
if (id=='FontName' || id=='FontSize') {
sel = document.getElementById(id).childNodes;
sel = isIE ? sel[0] : sel[1];
arg = sel.options[sel.selectedIndex].firstChild.data; }
else if (id == 'InsertImage')
arg = prompt('Enter a image location:', 'http://');
else if (id == 'CreateLink')
arg = prompt('Enter a URL:','http://');
else
arg = null;
ifrm.execCommand(id,false,arg);
}
}

function processData() {
formu.content.value = ifrm.body.innerHTML;
if( !formu.content.value.replace(/<br>|s|&nbsp;/ig,'') ) {
alert('You did not enter any Text!');
return false;
}
return true;
}
//--></script>

</head>

<body onload="initEdit('form_content','edit','')">
<div style="position:absolute;left:10px;top:10px">

<form onsubmit='return processData()' id='form_content' action='updateTextResponce123.php?sprache=deutsch' method='post'>


<div>
<div class="imagebutton" id="FontSize">
<select>
<option>1</option>
<option>2</option>
<option selected="selected">3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
</select>
</div>&nbsp;&nbsp;

<div class="imagebutton" id="FontName">
<select>
<option>Arial</option>
<option selected="selected">Times New Roman</option>
<option>Comic Sans MS</option>
<option>Verdana</option>

</select>
</div><br />

<div class="imagebutton" id="bold">
<a href="#" onclick="return false" style="font-weight:bold"><img src="pics/newpage/ed_format_bold.gif"></a>
</div>&nbsp;&nbsp;

<div class="imagebutton" id="italic">
<a href="#" onclick="return false" style="font-style:italic"><img src="pics/newpage/ed_format_italic.gif"></a>

</div>&nbsp;&nbsp;

<div class="imagebutton" id="underline">
<a href="#" onclick="return false" style="text-decoration:underline"><img src="pics/newpage/ed_format_underline.gif"></a>
</div>&nbsp;&nbsp;

<div class="imagebutton" id="justifyleft">
<a href="#" onclick="return false"><img src="pics/newpage/ed_align_left.gif"></a>
</div>&nbsp;&nbsp;

<div class="imagebutton" id="justifycenter">
<a href="#" onclick="return false"><img src="pics/newpage/ed_align_center.gif"></a>
</div>&nbsp;&nbsp;

<div class="imagebutton" id="justifyright">
<a href="#" onclick="return false"><img src="pics/newpage/ed_align_right.gif"></a>
</div>&nbsp;&nbsp;

<div class="imagebutton" id="insertorderedlist">
<a href="#" onclick="return false"><img src="pics/newpage/ed_list_num.gif"></a>
</div>&nbsp;&nbsp;

<div class="imagebutton" id="insertunorderedlist">
<a href="#" onclick="return false"><img src="pics/newpage/ed_list_bullet.gif"></a>
</div>&nbsp;&nbsp;

<div class="imagebutton" id="CreateLink">

<a href="#" onclick="return false"><img src="pics/newpage/ed_link.gif"></a>
</div><br />
<div class="imagebutton" id="indent">
<a href="#" onclick="return false"><img src="pics/newpage/"></a>
</div>&nbsp;&nbsp;

<div class="imagebutton" id="outdent">
<a href="#" onclick="return false"><img src="pics/newpage/"></a>

</div>&nbsp;&nbsp;
<div class="imagebutton" id="InsertImage">
<a href="#" onclick="return false"><img src="pics/newpage/ed_image.gif"></a>
</div>

<br />
<iframe id="edit" name="edit" width="400" height="200" frameborder="2" marginheight="0" marginwidth="0"></iframe>
<textarea name="text" style="display:none"></textarea>

<div style="width: 400px;" align="right">

<input type="hidden" name="name" value="kunden">

<input type="submit" value="Submit!" />
</div>
</div></form>

</div></body></html>
 

AmadMike

Новичок
Короче говоря у вас после выполнения скрипта в этом месте:

<body onload="initEdit('form_content','edit','<?php echo "$text";?>')">

получается просто

<body onload="initEdit('form_content','edit','')">

правильно?

Не знаю в чем проблема, по идее тут какая-то проблема в самом php, вообще я никогда не смешиваю html код с php, попробуйте разделить их (самый лучший вариант класс шаблонов).
Другой вариант просто указать в iframe атрибут src и направить его на скрипт который будет просто выбирать текст из базы и отдавать браузеру простым echo. Попробуйте еще ob_start может поможет

нет Вашого текста и база тут не причем
Здорово! А о чем тут во всей этой теме написано??? как раз в этом то и проблема, что по всем признакам текст должен быть, а его там нет...

Попробуйте в конце концов стереть весь текст и просто сделать две разделенные html кодом строки, сначала выборка из базы данных, потом ?> html-код и <?=$text?> если и так не пройдет то проблема точно в пхп, попробуйте на каком-нибудь другом хостинге...
 

anna1978

Новичок
Так все правильно! В этом и вопрос . когда идет та же программа, но в пхп я задаю данные вручную, вот так
<?php
$text="Text in Textarea";
?>
тогда если все работает и если посмотреть в броузере, то стоит
<body onload="initEdit('form_content','edit','Text in Textarea')">

(это чтобы весь текст не посылать . все то же самое кроме body и наверху текста нет . в первом варианте он приходит из базы а во втором я его вручную задаю

-~{}~ 10.11.06 17:40:

Вы совершенно правильно сформулировали проблему. То есть надо будет в отельной странице получать текст, вызывать его и т.д. Но некрасиво это как-то
 
Сверху