自动完成功能无法使用动态HTML

自动完成功能无法使用动态HTML

问题描述:

Iam adding html for input tag dynamically through enterPerson() and then calling onkeyup=changeOnType(this) which on echoing $results in autoInvit.php should display autocomplete, but WHY does my autocomlete code does not work,infact data shows if I alert it. can any one please help me out ? Thank you in advance :)

header files for jquery and autocomplete:

<link rel="stylesheet" href="//code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />  
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
<script src="//code.jquery.com/jquery-1.8.3.js"></script>
<script src="//code.jquery.com/ui/1.10.0/jquery-ui.js"></script>

autocomplete in "main.php" :

<script>    
function changeOnType(x){

    $.post(
    "autoInvit.php",
    {
         vals: $(x).val()
    },
    function(data){

    $("#"+x.id).autocomplete( {source:"autoInvit.php" }  );

    //alert(data);  
    }
    );

}
</script>

here's the dynamic html's php code in "invities.php":

<?php 

echo '<input class="e" type="email" id="email"  onkeyup="changeOnType(this)"  autocomplete="on" role="textbox" aria-autocomplete="list" aria-haspopup="true"  />';
?>

Here's my php file "autoInvit.php" which echos the result:

 <?php

    include("includes/connection.php"); 

    $value = strip_tags($_POST['vals']);

    $req = "SELECT email as name "
        ."FROM members "
        ."WHERE email LIKE '".$value."%' "; 


    $query = mysql_query($req);

    while($row = mysql_fetch_array($query))
    {
        $results[] = $row['name'];
    }


    echo json_encode($results);

    ?>

Please help

There's no need to make the post request. Edit: There's no need to call a separate function or attach a listener to the input, just register the autocomplete plugin. This will need to be called once the DOM is ready, so you will need to wrap it in a ready function. This should be all the javascript you need:

$(function() {
    $("#"+x.id).autocomplete( {source:"autoInvit.php" }  );
});

What the user has typed will be passed with the request as the parameter term

From the jQuery docs for autocomplete:

String: When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.

Also, you'll want to be careful when passing content from the user directly to the DB. You can open yourself to SQL injection.