在div中显示表单的结果

时间:2014-02-01 19:05:48

标签: javascript php html ajax forms

我是新手,所以请耐心等待:)。

我有一个这样的表格(从php文件回显):

<form id= \"myForm\" class=\"friendForm\" action=\"messages.php\" method=\"GET\" > 
        <input class=\"friendInput\" type=\"text\" name=\"idprijemce\" value='$idprijemce' hidden>  
        <input class=\"friendSubmit\" id=\"friendSubmit\" type=\"submit\" value='$cele_jmeno'>   
</form>

PHP文件如下所示:

<?php                                                             
session_start();
 include('dbconnect.php'); 
  $idprijemce = "";
 if (isset($_GET["idprijemce"])) {    
 }                    
  $_SESSION['idprijemce'] = $idprijemce;    

    $idprihlaseneho = $_SESSION['idprihlaseneho'];

    $vyber = "SELECT zprava FROM chat 
      WHERE IDodesilatel='" . $_SESSION['idprihlaseneho'] . "' AND IDprijemce='" . $_SESSION['idprijemce'] . "' OR IDodesilatel='" . $_SESSION['idprijemce'] . "' AND IDprijemce='" . $_SESSION['idprihlaseneho'] . "' ORDER BY cas ASC";
   $vezmijmeno = "SELECT cele_jmeno FROM uzivatele WHERE ID='". $_SESSION['idprihlaseneho'] ."'";
   $jmeno = mysql_query($vezmijmeno) OR die("Error");

   while($radekjmeno=mysql_fetch_assoc($jmeno)){

     echo ("<b>".$radekjmeno['cele_jmeno'].":</b> <br>"); 
   }


   $result = mysql_query($vyber) OR die("Error: $vyber </br>".mysql_error());
    while($radek = mysql_fetch_assoc($result)){
    echo ($radek['zprava'] . "<hr><br>");      
}                        

        mysql_close();  

?>

这就是事情 - 我需要在div“messages”中显示来自数据库的信息(由php文件拍摄)(在索引页面上,表格也在哪里),也许是通过AJAX,但我没有必要的技能,我已经花了2个多小时寻找解决方案。 php文件正常工作但它会打开一个包含来自DB的信息的全新页面。

你能帮助我使用AJAX脚本吗?我应该把它放在哪里?

1 个答案:

答案 0 :(得分:0)

最简单的实现将包括jQuery(由于浏览器中的不同实现),这里是一个应该工作的示例(你需要转换这个HTML并适应它的PHP当然 - 我没有为php变量放置转义/连接..):

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
function getAjax(){
    var idprijemce = $('#myForm .friendInput').val();
    var friendSubmit = $('#myForm .friendSubmit').val();
    $.ajax({
        type: "GET",
        url: "messages.php",
        data: {idprijemce:idprijemce,submit:friendSubmit}
    }).done(function( result ) {
        $("#msg").html( result );
        console.log('success');
    });
}
</script>
</head>
<body>
    <form id= "myForm" class="friendForm"> 
            <input class="friendInput" type="text" name="idprijemce" value='$idprijemce' hidden>  
            <input class="friendSubmit" id="friendSubmit" type="submit" value='$cele_jmeno' onClick="getAjax();">   
    </form>
    <div id="msg">
    </div>
    </form>
</body>
</html>

如您所见,操作已从表单中删除并添加到直接调用php脚本的javascript例程中,接收输出,然后将其输出到id =“msg”的div。