如何使用$ _POST来保存div是contentEditable =“true”?

时间:2013-09-03 10:46:54

标签: php javascript jquery html ajax

我正在尝试将Div的可编辑内容存储在SQL数据库中。但是从我所知道的isset($_POST["des"])永远不会返回真实。

(我没有做太多的网站编码所以我可能遗漏了一些非常基本/微不足道的东西)

overview_page.php:

<?php session_start();
include_once("php_includes/check_login_status.php");
?>

<?php
    if(isset($_POST["des"]))
    {
    echo "Inside IF statement";
    include_once("php_includes/db_conx.php");
    $des = mysqli_real_escape_string($db_conx, $_POST['des']);    
    $sql = "UPDATE users SET project_description='$des' WHERE   username='$log_username'";
    }
?>

<!DOCTYPE html>
<html>
<head>

    <script src="js/main.js"></script> <!--Points to external java script file-->
    <script src="js/ajax.js"></script> <!--Points to external java script file-->

    <script type="text/javascript">

    function save_description()
    {
        var des = _("project_description").value;
        var ajax = ajaxObj("POST", "overview_page.php"); 
        //ajax.onreadystatechange = function() sorry this one shouldn't be here
        ajax.send("des="+des); 
    }

    </script>
</head>    
<body>    

  <?php include_once("template_pagetop.php"); ?>  

  <div id="pageMiddle">
    <div id="left_window">

            <div id="project_description" name="project_description" contentEditable="true">
            Please enter project description...
            </div>
            <center>
            <button id="save" onclick="save_description()">Save</button>
            </center>
    </div>
  </div>      
</body>    
</html>

和外部脚本:

ajax.js:

function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
   return true; 
}}

main.js:

function _(x)
{
return document.getElementById(x);
}

2 个答案:

答案 0 :(得分:1)

所以我把你的代码带到了jsFiddle并创建了a new fiddle并且控制台中出现的第一件事(浏览器中的F12 - 至少在Chrome中)是事件实际上并未触发。< / p>

所以我将您的save_description()方法移动到事件绑定中(还有其他方法):

document.getElementById('save').onclick = function () {
    var des = _("project_description").innerHTML;
    var ajax = ajaxObj("POST", "overview_page.php");
    //ajax.onreadystatechange = function() sorry this one shouldn't be here
    ajax.send("des=" + des);
}

另请注意,我更改了des = _("project_description")对innerHTML的访问权限。

这似乎至少使请求具有值。之后,检查服务器端脚本。

答案 1 :(得分:0)

我会假设你的帖子发送了“des”值。

但您的代码位于“overview_page.php”文件中?如果没有,则将“des”值发送到不存在的文件,或者该文件中没有代码。 在这种情况下,你的if(isset($ _ POST [“des”]))永远不会返回true。

您需要拥有overview_page.php文件。

如果您不确定您的ajax代码是否按要求工作,请在“save_description()”函数中使用一些Jquery post函数。