Bonjour,<br />
J'ai un formulaire où il y a une div contenteditable = true, dans cette div j'ai un code qui insert des smileys. Mais ce n'est pas tout, il y a aussi une requête ajax qui me renvoie des éléments de ma base de donnée. Malheureusement elle ne place pas le text à inséré là où le curseur de l'utilisateur s'est arrété, mais au début. <br />
*PS*: pour les smileys ça marche.<br />
Voici les codes : <br />
Formulaire**<br />

<script type="text/javascript">
    function getContent(){
        document.getElementById("message").value = document.getElementById("my-content").innerHTML;
    }
</script>
<div id="my-content" tabindex="-1" style="color:black;max-width:96%;width:96%;top:-35px;" contenteditable="true" placeholder="Enter your post here..."></div>
    <textarea cols="25" style="display:none" name="message" id="message" rows="2">
    </textarea>
</form>
<div class="smiley-box" id="smileybox" style="display:none;">
  <a href="#" onclick="document.getElementById('my-content').focus(); insr('<img src=&#x22;interimg/smile.png&#x22; height=&#x22;12&#x22; width=&#x22;12&#x22;  style=&#x22;position:relative;top: 4px;margin: 2px;&#x22;>');"><img src="interimg/smile.png"></a>
  <a href="#" onclick="document.getElementById('my-content').focus(); insr('<img src=&#x22;interimg/big_smile.png&#x22; height=&#x22;12&#x22; width=&#x22;12&#x22;  style=&#x22;position:relative;top: 3px;margin: 2px;&#x22;>');"><img src="interimg/big_smile.png"></a>
</div>

<br />
Partie pour AJAX<br />

div class="people-ident-box" id="PeopleBox" style="display:none;">
<form method="GET">
 <script type="text/javascript">
$(function(){
$(".search_bar_people").keyup(function() 
{ 
    var search_keyword_value = $(this).val();
    var dataString = 'search_bar_people='+ search_keyword_value;
    if(search_keyword_value!='')
    {
        $.ajax({
            type: "GET",
            url: "livesearch_people_ind.php",
            data: dataString,
            cache: false,
            success: function(html)
                {
                    $("#result_people").html(html).show();
                }
        });
    }
    return false;    
});

$("#result_people").live("click",function(e){
    var $clicked = $(e.target);
    var $name = $clicked.find('.country_name').html(); 
    var decoded = $("<div/>").html($name).text();
    $('#search_bar_people_id').val(decoded);
});

$(document).live("click", function(e) { 
    var $clicked = $(e.target);
    if (! $clicked.hasClass("search_bar_people")){
        $("#result_people").fadeOut(); 
    }
});

$('#search_bar_people_id').click(function(){
    $("#result_people").fadeIn();
});
});
</script>
<script type="text/javascript">
$('html').click(function(event){
     if(event.target.id == 'result_people') {
//Do nothing
     } else {
$('#result_people').css({
    display : 'none'
});
     }
 });
</script>
<style type="text/css">
.show-livesearch-people{
  position: relative;
  float: left;
  width: 50%;
  max-width: 100%;
  max-height: 70px;
  overflow: hidden;
  border-bottom: solid 1px rgba(0,0,0,0.07);
  margin-bottom: 2px;
  margin-top: 2px;
}
 #search_keyword_id_people
 {
  width: 700px;
  border: solid 1px #CDCDCD;
  padding: 5px;
  font-size: 14px;
  border-radius: 2px;
  position: absolute;
  left: -250px;
  height: 30px;
  top: -3px;
 }
 span.show-livesearch-live-people{
  width: 33%;
  position: relative;
  left: 40%;
  top: -60px;
  text-align: center;
  font-size: 20px;
 }
 #result_people
 {
  position: absolute;
  width: 100%;
  display: none;
  overflow: auto;
  top: 32px;
  background-color: rgba(255, 255, 255, 1);
  z-index: 800;
  -webkit-box-shadow: 0px 0px 5px 0px rgba(50, 50, 50, 0.1);
  -moz-box-shadow: 0px 0px 5px 0px rgba(50, 50, 50, 0.1);
  box-shadow: 0px 0px 5px 0px rgba(50, 50, 50, 0.1);
  border-radius: 1px;
  max-height: 225px;
 }
 .show
 {
font-family: 'Roboto', sans-serif;
 padding:10px; 
 border-bottom:1px #CDCDCD dashed;
 font-size:15px; 
 }
 .show:hover
 {
 background:#364956;
 color:#FFF;
 cursor:pointer;
 }
</style>
        <input type="text" autocomplete="off" class="search_bar_people" id="search_bar_people_id" name="search_friend_ind" placeholder="Friend"/>
        <div id="result_people">
        </div>
</form>
</div>

<br />
Partie AJAX (livesearch_people_ind.php)<br />

<script type="text/javascript" src="//code.jquery.com/jquery-1.8.0.min.js"></script>
<?php

    define('_HOST_NAME', 'localhost');
    define('_DATABASE_USER_NAME', 'root');
    define('_DATABASE_PASSWORD', '');
    define('_DATABASE_NAME', 'bdd');

    $dbConnection = new mysqli(_HOST_NAME, _DATABASE_USER_NAME, _DATABASE_PASSWORD, _DATABASE_NAME);
    if ($dbConnection->connect_error) {
        trigger_error('Connection Failed: '  . $dbConnection->connect_error, E_USER_ERROR);
    }

    if(isset($_GET['search_bar_people']))
    {
        $search_keyword = $dbConnection->real_escape_string($_GET['search_bar_people']);
        $sqlCountries="SELECT id,username,prof_img,society FROM usr WHERE username LIKE '%$search_keyword%'";
        $resCountries=$dbConnection->query($sqlCountries);

        if($resCountries === false) {
            trigger_error('Error: ' . $dbConnection->error, E_USER_ERROR);
        }else{
            $rows_returned = $resCountries->num_rows;
        }

  $bold_search_keyword = '<b style="color:darkgrey;font-weight: 300;">'.$search_keyword.'</b>';
  if($rows_returned > 0){
            while($rowCountries = $resCountries->fetch_assoc()) 
            {   
                      ?>
                       <div class="show-livesearch-people" align="left">
<a href="#" style="color: rgb(47, 47, 47);text-decoration: none;" onclick="document.getElementById('my-content').focus(); insr('<a href=&#x22;usr.php?id=<?php echo $rowCountries['id']; ?>&#x22;><?php echo $rowCountries['username']; ?></a>');">       
                        <div class="prof_img_search" style="left: 18px;"><img src="usr/gallery/<?php echo $rowCountries['prof_img']; ?>"></div>
                        <span class="show-livesearch-live-people"><?php echo str_ireplace($search_keyword,$bold_search_keyword,$rowCountries['username']); ?></span><br />
                        <span class="show-livesearch-live-people" style="font-size:13px;color:darkgrey;"><?php echo str_ireplace($search_keyword,$bold_search_keyword,$rowCountries['society']) ?></span>
                       </a>
                      </div>
                      <?php  
            }
        }else{
            echo '<div class="show-livesearch-people" align="center" style="width:100%;text-align:center;font-size:25px;"><b>No result.</b></div>';   
        }
    } 
?>

1 réponse


Salut,

Alors déjà ton soucis est sur le front et concerne le JS, tu n'avais pas besoin de nous mettre ton CSS et ton PHP.
Ensuite, l'utilisation de la fonction jQuery live() n'est pas conseillée. Utilises plutôt on() (elle s'utilise exactement de la même manière).
Enfin, venons-en à ton problème: Ce que tu souhaites c'est insérer ce que te renvoie ton appel Ajax là où se trouve le curseur c'est bien ça ?
Si tel est le cas, essaye ceci (trouvé sur stackoverflow après 1 minute de recherches...):

    $(".search_bar_people").keyup(function() 
{ 
    var search_keyword_value = $(this).val();
    var dataString = 'search_bar_people='+ search_keyword_value;
    if(search_keyword_value!='')
    {
        $.ajax({
            type: "GET",
            url: "livesearch_people_ind.php",
            data: dataString,
            cache: false,
            success: function(html)
                {
                    var caretPos = document.getElementById("result_people").selectionStart;
                    var textAreaTxt = $("#txt").val();
                    var txtToAdd = html;
                    $("#result_people").val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) ).show();
                }
        });
    }
    return false;    
});