Faz tempo que estou tentando fazer algo, porém não encontro solução..
Estou fazendo um sistema de comentário, porém não está funcionando ajax. Antes, quando fazia direto com PHP e Mysql tudo funcionava, porém agora mudei para usá-lo com ajax, mas não me dá resposta de nada... envio-lhe os códigos que uso:
Isto é onde mostro os comentários... e o formulário para criar os comentários se chama: shownews.php
<?php
$link = mysql_connect("localhost","root"," Mqq46@ho");
mysql_select_db("mywebdb", $link) or die("Error");
$idn = $_GET["id"];
$result = mysql_query("SELECT idnews, titlenews, fullnews FROM tnews
WHERE (idnews=$idn)", $link);
//id, titulo, noticia, autor, priority
$my_error = mysql_error($link);
while ($row = mysql_fetch_row($result))
{
echo "Titulo: <h4><em><strong>$row[1]
</strong></em></h4> </br>";
echo "Noticia: <h4><em><strong>$row[2]
</strong></em></h4></br>";
}
?>
<html xmlns="http://www.w3.org/1999/xhtml ">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script language="JavaScript" type="text/javascript" src=" ajax.js"></script>
</head>
<body>
<br />
<div id="commentlist">
</div>
<div id="commentsform">
<h2>Pode deixar um comentário:</h2>
<form name="comentform" method="post" id="commentform"
onSubmit="return send
('/addcomentario.php', 'id', 'nick', 'comment', 'url', 'email', 'commentlist')"
>
<p style="margin-top:0;">
<textarea name="comment" id="comment" cols="100%"
rows="10" tabindex="1"></textarea>
</p>
<p>
<input type="text" name="nick" id="author" value="" size="22" tabindex="2" />
<label class="label" for="author">Nick</label>
</p>
<p>
<input type="text" name="email" id="email" value="" size="22" tabindex="3" />
<label class="label" for="email">Correio eletrônico (obrigatório)</label>
</p>
<p>
<input type="text" name="url" id="url" value="" size="22"
tabindex="4" />
<label class="label" for="url">Web (opcional)</label>
</p>
<p>
<input name="submit" type="submit" id="submit" tabindex="6" value="Enviar Comentário" />
<input name="id" type="hidden" value="<? echo
$idn; ?>">
</p>
</form>
</div>
<div id="testing">
asdasd
<?php include("showcomment.php"); ?>
</div>
</body>
</html>
<?php
mysql_free_result($result);
mysql_close();
?>
agora este é o arquivo ajax.js
function simple_ajax(){
var xmlhttp=false;
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject(" Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function LoadContent(callback, url, query_string, method, iditem){
method = method.toUpperCase();
var ajax=simple_ajax();
fullquery = url +"?" + query_string;
if (method == 'GET') {
ajax.open(method, url +"?" + query_string, true);
} else {
ajax.open(method, url, true);
}
ajax.onreadystatechange=function() {
if(ajax.readyState==1) {
callback(query_string, ajax.responseXML, 'testing');
} else {
if (ajax.readyState==4) {
callback(ajax.responseText, ajax.responseXML, iditem);
}
}
}
if (method == 'GET') {
ajax.send(null)
} else {
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
ajax.send(query_string);
}
}
function send(url, vid, vnick, vcom, vurl, vemail, divused)
{
/*Obter onde se mostrará o conteúdo*/
divResultado = document.getElementById(iditemuse);
/*Obter os valores do formulário*/
obj_id = document.getElementById(vid);
obj_nick = document.getElementById(vnick);
obj_com = document.getElementById(vcom);
obj_url = document.getElementById(vurl);
obj_email = document.getElementById(vemail);
/* Obter Mensagem por Item*/
/* obter o objeto msg */
obj_msg = vid'='+obj_id.value;
//*+'&nick='+obj_nick.value+'&comment='+obj_com.value+'&url='+obj_url.value+'&email='+obj_email.value;
/* Construir o query_string (variáveis que serão enviadas na petição). */
/* O formato desta cadeia é "v1=valor1&v2=valor2& .. &vn=valorn" */
query_string = obj_msg.value;
LimparCampos();
/*obj_msg.focus();*/
/* Enviar a petição */
LoadContent(send_callback, url, query_string, 'POST', divused);
return false;
}
function send_callback(text, xml, idclearelem)
{
/* obter o objeto main */
LimparCampos(idclearelem);
obj_main = document.getElementById(idclearelem);
obj_div = document.createElement('div');
obj_div.innerHTML = text;
obj_main.appendChild(obj_div);
}
function LimparCampos(){
document.comentform.comment.value = "";
document.comentform.nick.value = "";
document.comentform.email.value = "";
document.comentform.url.value = "";
document.comentform.comment.focus();
}
este é o arquivo para agregar os comentários se chama: addcomentario.php
<?php
$link = mysql_connect("localhost","root","Mqq46@ho");
mysql_select_db("mywebdb", $link);
if(isset($HTTP_POST_VARS["id"]) && isset($HTTP_POST_VARS["nick"]) && isset($HTTP_POST_VARS["comment"]) && isset($HTTP_POST_VARS["url"]) && isset($HTTP_POST_VARS["email"]))
{
if($HTTP_POST_VARS["comment"] != "")
{
if($HTTP_POST_VARS["nick"] == "")
{
$nickNovo = "anônimo";
}else
{
$nickNovo = $HTTP_POST_VARS["nick"];
}
$idNoticia = $HTTP_POST_VARS["id"];
$comentarioNoticia = $HTTP_POST_VARS["comment"];
$theurl = $HTTP_POST_VARS["url"];
$theemail = $HTTP_POST_VARS["email"];
$hoydate = date("Y-m-d");
$hoytime = date("H:i:s");
$pageref = getenv('HTTP_REFERER');
echo "$idNoticia: <br /> $comentarioNoticia: <br /> $theurl: <br /> $theemail: <br /> $hoydate: <br /> $hoytime: <br /> $nickNovo:";
$sql = "INSERT INTO comentarios (id_Comentarios, id_noticia, nick, data, hora, email, url, comentario) ";
$sql.= "VALUES ('','$idNoticia','$nickNovo','$hoydate','$hoytime', '$theemail', '$theurl','$comentarioNoticia')";
$es = mysql_query($sql, $link) or die("Erro ao gravar uma mensagem: ".mysql_error);
//echo "Comentario Enviado Com Sucesso.<BR>Espere Uns Segundos...<SCRIPT LANGUAGE=\"javascript\">window.location.href = \"$pageref\"</SCRIPT>";
}else
{
echo "Deve Introduzir Um Comentário.";
}
}
include("showcomment.php");
mysql_close();
?>
Porém, não me responde nada... nem erroe nem nada, se alguém pudesse me ajudar....
Se você diz que não lhe devolve nada, imagino que se refere a que não mostra nenhuma mudança em tela.
Recomendo a extensão Firebug para Firefox, lhe mostra cada request que realiza ao server e que devolve o servidor, ademais traz um depurador para javascript e várias coisas muito úteis. Portanto, instale-o e veja o que o servidor está lhe devolvendo.
Por Roberto Erhard