AJAX / Emplacement d'un div

Nouveau WRInaute
Bonjour,

J'ai un petit soucis en AJAX et j'ai besoin d'aide.


http://www.secret-buzz.com/2009/07/22/romain-sortirait-22-709-votes/

Si vous laissez un commentaire sur cet article, un nouveau bloc va apparaître en bas de tous les commentaires. Mes commentaires étant dans l'ordre croissant, j'aimerai qu'il apparaisse en haut de tous les commentaires.

Mes connaissances en AJAX étant très limitées, pour ne pas dire inexistantes, je viens vous demander de l'aide.

Le fichier JS en question est :

Code:
// wp-content/themes/yuewei File
//short for document.getElementById
function $() {
	if (arguments.length == 1) return get$(arguments[0]);
	var elements = [];
	$c(arguments).each(function(el){
		elements.push(get$(el));
	});
	return elements;
}
function get$(el){
	if (typeof el == 'string') el = document.getElementById(el);
	return el;
}

function $c(array){
	var nArray = [];
	for (i=0;el=array[i];i++) nArray.push(el);
	return nArray;
}

// get parameters of the comment form
function getParams(f){
	if(typeof(f)=='string')	f = $(f);
	var p='';
	var fi = f.getElementsByTagName('input');
	for (i=0; i<fi.length; i++ ) {
		e=fi[i];
		if (e.name!='') {
			if (e.type=='select')
				element_value=e.options[e.selectedIndex].value;
			else if (e.type=='checkbox' || e.type=='radio') {
				if (e.checked==false)	continue;	
				element_value=e.value;
			}
			else {
				element_value=e.value;
			}
			p+="&"+e.name+'='+encodeURIComponent(element_value);
		}
	}
	fi = f.getElementsByTagName('textarea');
	for (i=0; i<fi.length; i++)	p+="&"+fi[i].name+"="+encodeURIComponent(fi[i].value);
	p += "&random="+Math.random();
	return p;
}

// move comment form to proper position to reply exist comments.
function moveForm(a) {
	var id		= $('comment_reply_ID'),
		disp	= $('reRoot').style,
		form	= $('commentform'),
		e		= $('comment-'+a);
	var es = $('commentform').getElementsByTagName('*');
	
	form.parentNode.removeChild(form);
	if (a) {
		var c = e.getElementsByTagName('ul')[0];
		if (c)
			e.insertBefore(form, c);
		else
			e.appendChild(form);
	} else {
		$('cmtForm').appendChild(form);
	}
	disp.display = (a ? 'inline' : 'none');
	if (id) id.value = (a ? a : 0);
	if (a && $('author')) {$('author').focus();}
	return;
}

//the function to get an ajax instance
function getXMLInstant(r)
{
	var xx;
	if(r!=1)ajaxStatus("block");
	if (window.XMLHttpRequest) 
	{ // Mozilla, Safari,...
		xx = new XMLHttpRequest();
	} 
	else if (window.ActiveXObject) { // IE
		try {
			xx = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xx = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!xx) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	
	return xx;
}
//the function to send comment
function AjaxSendComment()
{
   var gi = getXMLInstant(1), r = $('comment_reply_ID').value, t, c, now = parseInt(Math.random()*1000);
	
	if (r == 0) {
		t = 'comments';
		c = $(t);
	} else {
		t = 'comment-'+r;
		var u = $(t).getElementsByTagName('ul')[0];
		if (u) {
			c = u;
		} else {
			c = document.createElement('ul');
			$(t).appendChild(c);
		}
	}
	// backup comment in case of Comment fail
	var content = $("comment").value;
	var author = "admin", email="a@b.c";
	var temp = content;
	if($("author"))author = $("author").value;
	if($("email"))email = $("email").value;
	//check the author and content input area is fixed
	if(content == "" || ( (needemail=="1") && (author == "" || email == ""))){
		if(author ==""){ alert("name is necessary"); if($("authorrequire"))$("authorrequire").style.color="red";$("author").focus();}
		else if(email==""){ alert("email is necessary");; if($("emailrequire"))$("emailrequire").style.color="red";$("email").focus();}
	    else{ alert("comment can not be empty");$("comment").focus();}
	   	return true;
	}
	
	//add comment to local comment list
	content = content.replace(/\r\n\r\n/g, "</p><p>");
	content = content.replace(/\r\n/g, "<br />");
	content = content.replace(/\n\n/g, "</p><p>");
	content = content.replace(/\n/g, "<br />");
	var dateObj = new Date();
	c.innerHTML = c.innerHTML + "<li id='newComment"+now+"'><div class=\"commenthead newcomment\">At "+dateObj.toLocaleString()+", <span class=\"author\">"+ author+ "</span> said: </div><div class=\"body\"><p>"  + content+ "</p></div><div class='meta' id='submitcomment'>You submit a new comment...</div></div></li>";
	
	//the state function of ajax 
	gi.onreadystatechange = function()
    {
        if (gi.readyState == 4) {
            if (gi.status == 200) {
               $('newComment'+now).innerHTML=gi.responseText;
					// ajaxStatus("none");
					if(gi.responseText.search(/Slow down cowboy/) > -1 || gi.responseText.search(/Duplicate comment detected/) > -1)
						$('comment').value = temp;
            } else {
				$('comment').value = temp;
				$('submitcomment').innerHTML = 'Submit failed, you submit too fast or submit a duplicate comment...';
				alert('Failed to add your comment. ');
            }
        }
    }
	
	//send form by ajax
	var p=getParams("commentform"); // get parameters of form
	gi.open('POST', blogurl+"/wp-content/plugins/ajaxcomment/comments-ajax.php", true);
   gi.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   gi.setRequestHeader("Content-length", p.length);
   gi.setRequestHeader("Connection", "close");
   gi.send(p);
    
	//after send form, move the comment form to original position.
   comment_preview(false);
   moveForm(0);

   $('comment').value = '';
   
   return true;
}

function ajaxPost(u, p, e, s, m){
	var g = getXMLInstant();
    	
	if ($(e))	e = $(e); 
	
	g.onreadystatechange = function(){
		if (g.readyState == 4) {
      		if (g.status == 200) {
				if (typeof(m) != "undefined" && m == "delete") { if (e) e.parentNode.removeChild(e); }
         		else { if (e) e.innerHTML = g.responseText; }
				if (s) 	eval(s);
				ajaxStatus("none");
			} else {
         		alert('There was a problem with the request.');
         	}
		}
	}
    
	g.open('POST', u, true);
   	g.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   	g.setRequestHeader("Content-length", p.length);
   	g.setRequestHeader("Connection", "close");
   	g.send(p);
	
}

// Get content by AJAX, u:url; e:element; j:jump; s:alert message; m: method

function ajaxShowPost(u, e, j, s, m){
	if ("undefined"!=typeof(nowurl) && u==nowurl) {
		window.location.href="#"+j;
		return;
	}
	if ( u.match(/getpost/) )	nowurl=u;
	var g = getXMLInstant();
    	
	if ($(e))	e = $(e); 
	
	g.onreadystatechange = function(){
		if (g.readyState == 4) {
      		if (g.status == 200) {
				if (typeof(m) != "undefined" && m == "delete") { if (e) e.parentNode.removeChild(e); }
         		else { if (e) e.innerHTML = g.responseText; }
				if (j)	window.location.href = "#"+j;
				if (s) 	eval(s);
				ajaxStatus("none");
			} else {
         		alert('There was a problem with the request.');
         	}
		}
	}
    
   g.open('GET', u, true);
   g.send(null);
}

// toggle #ajax status
function ajaxStatus(s) {
	if (!$("ajax")) return;
	$("ajax").style.display = s;
}

function comment_preview(i) {
	if (typeof(i)=='undefined' && $('copreview').style.display != 'block' || typeof(i) != 'undefined' && i == true) {
		if ($('copreview').style.display != 'block') {
			var p=getParams("commentform");
			ajaxPost(blogurl + '/wp-content/plugins/ajaxcomment/preview.php', p, 'copreview', "$('commentdiv').style.display = 'none';$('copreview').style.display = 'block';$('prectr').value = 'Edit';");
		}
	} else {
		if ($('copreview').style.display != 'none') {
			$('prectr').value = 'Preview';
			$('commentdiv').style.display = 'block';
			$('copreview').style.display = 'none';
			$('comment').focus();
		}
	}
}


Merci ;)
 
WRInaute accro
Pas testé, mais je pense que si tu remplaces:

Code:
         $(t).appendChild(c);
par
Code:
         $(t).insertBefore(c,$(t).firstChild);

Ca devrait le faire, non?

Jacques.
 
WRInaute passionné
il faut aller dans le template et deplacer l'endroit qui fait office de postage et de le repositioner au dessus du bloc de coms
 
Nouveau WRInaute
Pas moyen de trouver l'endroit :(

comments.php

Code:
<?php // Do not delete these lines
	 $comments = array_reverse($comments);
	global $ajaxpost, $comments_b, $total_comment, $comments_per_page;
	$comments_b = $comments;
	$total_comment = count($comments);
	$comments = array_slice($comments, -$comments_per_page);//$comments_per_page);
	if ('comments.php' == basename($_SERVER['SCRIPT_FILENAME']))
		die ('Please do not load this page directly. Thanks!');
        if (!empty($post->post_password)) {
            if ($_COOKIE['wp-postpass_' . COOKIEHASH] != $post->post_password) {
				?>
				<p class="nocomments">This post is password protected. Enter the password to view comments.</p>
				<?php
				return;
            }
        }
	if(!$tablecomments && $wpdb->comments)
		$tablecomments = $wpdb->comments;
	// = $wpdb->get_results("SELECT * FROM $tablecomments WHERE comment_post_ID = '$id' AND comment_approved = '1' ORDER BY comment_date");
// You can start editing here
	$GLOBALS['comments_reply'] = array();

	function write_comment(&$c, $deep_id = -1, $color = true) {
		global $max_level;
		$comments_reply = $GLOBALS['comments_reply'];
		if ($c->comment_author_email== get_the_author_email())
			$style = ' class="mine"';
		else if ($color==true){$style=' class="borderc1"';$color=!$color;}
		else{$style=' class="borderc2"';$color=!$color;}
?>
		<li id="comment-<?php echo $c->comment_ID ?>" <?php echo $style?>>
		<div class="commenthead">At <?php echo mysql2date('Y.m.d H:i', $c->comment_date);?>, <a name='comment-<?php echo $c->comment_ID ?>'></a><span><?php echo get_comment_author_link();?></span> said: </div>
		<div class="body">
			<?php if(function_exists('get_avatar'))echo get_avatar($c->comment_author_email, '80'); ?>
			<?php comment_text();?>
		</div>
		<div class="meta">
			<?php
			global $user_ID, $post;
			get_currentuserinfo();
			if (user_can_edit_post_comments($user_ID, $post->ID) || ($GLOBALS['cmtDepth'] < $max_level))
				echo '[';
				// delete link
				if (user_can_edit_post_comments($user_ID, $post->ID)) {
					$deleteurl = get_bloginfo("siteurl") . '/wp-admin/comment.php?action=deletecomment&amp;p=' . $c->comment_post_ID . '&amp;c=' . $c->comment_ID;
					$deleteurl = wp_nonce_url($deleteurl, 'delete-comment_'.$c->comment_ID);	
					echo "<a href='$deleteurl' onclick='ajaxShowPost(\"$deleteurl\", \"comment-{$c->comment_ID}\", \"\", \"alert(\\\"comment is deleted\\\")\", \"delete\");return false;'>delete</a>|";
					$spamurl = get_bloginfo("siteurl") . '/wp-admin/comment.php?action=deletecomment&amp;dt=spam&amp;p=' . $c->comment_post_ID . '&amp;c=' . $c->comment_ID;
					$spamurl = wp_nonce_url($spamurl, 'delete-comment_'.$c->comment_ID);
					echo "<a href='$spamurl' onclick='ajaxShowPost(\"$spamurl\", \"comment-{$c->comment_ID}\", \"\", \"alert(\\\"comment is spamed\\\")\", \"delete\");return false;'>spam</a>|";
					edit_comment_link('Edit', '',(($GLOBALS['cmtDepth'] < $max_level)?'|': ''));
				}
					if ($GLOBALS['cmtDepth'] < $max_level) {
						if ( get_option("comment_registration") && !$user_ID )
							echo '<a href="'. get_option('siteurl') . '/wp-login.php?redirect_to=' . get_permalink() .'">Log in to Reply</a> ]';
						else
							echo '<a href="javascript:moveForm('.$c->comment_ID.')" title="reply">Reply</a>';
					}
			if (user_can_edit_post_comments($user_ID, $post->ID) || ($GLOBALS['cmtDepth'] < $max_level))
				echo ']</div>';
					if ($comments_reply[$c->comment_ID]) {
						$id = $c->comment_ID;
						if($GLOBALS['cmtDepth'] < $max_level )
							echo '<ul>';
							$first_c = true;
		foreach($comments_reply[$id] as $c) {
							if ($first_c){$first_c=false;continue;}
							$GLOBALS['cmtDepth']++;
							if($GLOBALS['cmtDepth'] == $max_level)
								write_comment($c, $c->comment_ID, $color);
							else
								write_comment($c, $deep_id, $color);
							$GLOBALS['cmtDepth']--;
		}
						if($GLOBALS['cmtDepth'] < $max_level )
							echo '</ul>';
					}
					echo '</li>';
	}
?>



<div class="clear"></div>
<script type="text/javascript"> 
var blogurl="<?php echo get_settings('siteurl');?>"; 
var needemail="<?php echo get_option('require_name_email');?>";
var nowurl="<?php echo $post->ID;?>";
var md5 = "<?php echo md5(get_settings("siteurl"));?>";
</script>

<?php echo '<script type="text/javascript" src="'.get_settings('siteurl').'/wp-content/plugins/ajaxcomment/comment.js"></script>';?>

<?php $remain_comment = $total_comment - $comments_per_page;
if ($total_comment > $comments_per_page)
	echo "<a href='#' onclick='ajaxShowPost(blogurl+\"/wp-content/plugins/ajaxcomment/getcomments.php?id={$post->ID}&s=0&n=10000\", \"comments\", \"comments\");return false;'>$remain_comment old comments are not displayed. Click to display all comments</a>";
?>
</ul>
<?php if ('open' == $post->comment_status) : ?>
<div id="cmtForm">
<?php if ( get_option('comment_registration') && !$user_ID ) : ?>
<p>You must be <a href="../../themes/default/<?php echo get_option('siteurl'); ?>/wp-login.php?redirect_to=<?php the_permalink(); ?>">logged in</a> to post a comment.</p>
<?php else : ?>
<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform" onsubmit="AjaxSendComment();return false;">
<?php if ( $user_ID ) : ?>
<p>Logged in as <a href="<?php echo get_option('siteurl'); ?>/wp-admin/profile.php"><?php echo $user_identity; ?></a>. <a href="<?php echo get_option('siteurl'); ?>/wp-login.php?action=logout" title="Log out of this account">Logout &raquo;</a></p>
<input type="checkbox" name="comment_email_back" id='comment_email_back' />Email notification
<?php else : ?>
<div id="caie">
<input type="text" name="author" id="author" value="<?php echo $comment_author;?>" tabindex="11" onclick="this.select();"/><label for="author"><?php _e('Name'); ?></label><span id="authorrequire"><?php _e(" (Required)");?></span><br/>
<input type="text" name="email" id="email" value="<?php echo $comment_author_email;?>" tabindex="12"  onclick="this.select();"/><label for="email"><?php _e('Mail');?></label><span id="emailrequire"><?php _e(" (Required, will not be published)");?></span><br/>
<input type="text" name="url" id="url" value="<?php echo $comment_author_url; ?>" tabindex="13"  onclick="this.select();"/><label for="url"><?php _e('Website'); ?></label>
</div>
<?php endif; ?>

<div id='commentarea'>
<div id='commentdiv'><textarea name="comment" id="comment" tabindex="14" rows="6" cols="70"></textarea></div>
<div id='copreview' ondblclick="comment_preview();"></div>
<div id='comoper'><input value="Say it!" name="submit" type="submit" tabindex="15"/>
<input value='Preview' name="preview" type='button' onclick="javascript:comment_preview();" tabindex="16" id='prectr'/>
<input id="reRoot" type="button" onclick="javascript:moveForm(0)" style="display:none" value="Cancel" tabindex="17"/>
<input type="hidden" name="comment_post_ID" value="<?php echo $id; ?>" />
<input type="hidden" name="comment_reply_ID" id="comment_reply_ID" value="0" /></div>
</div>
<?php do_action('comment_form', $post->ID); ?>
</form>

<?php endif; // If registration required and not logged in ?>
</div>
<?php endif; // if you delete this the sky will fall on your head ?>


<h3><?php comments_number(__('No Comments'), __('1 Comment'), __('% Comments'));?></h3>
<ul class="commentslist" id="comments">
	<?php
		if ($comments) :
			foreach ($comments as $c) {
				$GLOBALS['comments_reply'][$c->comment_ID][] = $c;
				if (isset($GLOBALS['comments_reply'][$c->comment_reply_ID]))
					$GLOBALS['comments_reply'][$c->comment_reply_ID][] = $c;
				else 
					$GLOBALS['comments_reply'][0][] = $c;
			}
			$GLOBALS['cmtDepth'] = 0;$color=true;
			foreach($GLOBALS['comments_reply'][0] as $cmt) {
				$GLOBALS['comment'] = &$cmt;
				write_comment($GLOBALS['comment'], '-1', $color);
				$color=!$color;
			}
		else:
		endif;
	?>

comments-ajax.php

Code:
<?php
require_once('../../../wp-config.php');

global $comment, $comments, $post, $wpdb, $user_ID, $user_identity, $user_email, $user_url;

ignore_user_abort(true);

function fail($s) {
	header('HTTP/1.0 500 Internal Server Error');
	echo $s;
	exit;
}

	

foreach($_POST as $k=>$v) {
	$_POST[$k] = rawurldecode($v);
}

$comment_post_ID = (int) $_POST['comment_post_ID'];

$post_status = $wpdb->get_var("SELECT comment_status FROM $wpdb->posts WHERE ID = '$comment_post_ID'");

if ( empty($post_status) ) {
	do_action('comment_id_not_found', $comment_post_ID);
	fail('The post you are trying to comment on does not curently exist in the database.');
} elseif ( 'closed' ==  $post_status ) {
	do_action('comment_closed', $comment_post_ID);
	fail(__('Sorry, comments are closed for this item.'));
}

$comment_author       = trim($_POST['author']);
$comment_author_email = trim($_POST['email']);
$comment_author_url   = trim($_POST['url']);
$comment_content      = trim($_POST['comment']);
$comment_content	  = preg_replace("/javascript/i", '', $comment_content);

// If the user is logged in
get_currentuserinfo();
if ( $user_ID ) :
	$comment_author       = addslashes($user_identity);
	$comment_author_email = addslashes($user_email);
	$comment_author_url   = addslashes($user_url);
else :
	if ( get_option('comment_registration') )
		fail(__('Sorry, you must be logged in to post a comment.'));
endif;

$comment_type = '';

if ( get_settings('require_name_email') && !$user_ID ) {
	if ( 6 > strlen($comment_author_email) || '' == $comment_author )
		fail(__('Error: please fill the required fields (name, email).'));
	elseif ( !is_email($comment_author_email))
		fail(__('Error: please enter a valid email address.'));
}

if ( '' == $comment_content )
	fail(__('Error: please type a comment.'));

$commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'user_ID');

$new_comment_ID = wp_new_comment($commentdata);

if ( !$user_ID ) :
        setcookie('comment_author_' . COOKIEHASH, stripslashes($comment_author), time() + 30000000, COOKIEPATH, COOKIE_DOMAIN);
        setcookie('comment_author_email_' . COOKIEHASH, stripslashes($comment_author_email), time() + 30000000, COOKIEPATH, COOKIE_DOMAIN);
        setcookie('comment_author_url_' . COOKIEHASH, stripslashes($comment_author_url), time() + 30000000, COOKIEPATH, COOKIE_DOMAIN);
endif;

$comment = $wpdb->get_row("SELECT * FROM {$wpdb->comments} WHERE comment_ID = " . $new_comment_ID);

$post->comment_status = $wpdb->get_var("SELECT comment_status FROM {$wpdb->posts} WHERE ID = {$comment_post_ID}");
$comments = array($comment);
foreach ($comments as $c) {
?>
	<div class="commenthead new">At <?php echo mysql2date('Y.m.d H:i', $c->comment_date);?>, 
			<a name='comment-<?php echo $c->comment_ID ?>'></a>
			<span class="author"><?php comment_author_link()?></span> said: </div>
			<div class="body">			<?php if(function_exists('get_avatar'))echo get_avatar($c->comment_author_email, '80'); ?>
<?php comment_text();?></div>
		<?php echo $email_send_comment;?>
	</div>
<?php
}
?>

Merci, je compte sur vous :wink:
 
WRInaute accro
Comme on ne peut même pas s'inscrire et donc qu'on ne peut pas poster de commentaire sur ton blog, ça va être difficile...

Jacques.
 
WRInaute accro
A l'aveugle: tu peux aussi tenter de remplacer la ligne c.innerHTML = c.innerHTML + "pleindetrucs"; par c.innerHTML = "pleindetrucs" + c.innertHTML;

NB: tout se passe dans AjaxSendComment a priori.

Jacques.
 
Nouveau WRInaute
Désolé Jacques, c'était en effet pas très malin de ma part, désolé :/

Désormais, tu peux poster un commentaire, encore merci pour ton aide :wink:
 
Nouveau WRInaute
ça marche :)

merci! ;)

je me permet de poser une autre question : est-ce que tu (vous) connaîtrais une technique pour actualiser grâce à un lien seulement l'encart des commentaires?

une nouvelle fois : merci :)
 
Discussions similaires
Haut