0

I have wordpress site. I made custom table and sotred values in one row. Now I made admin menu and added input field into it.

<input id="location1" type="text" />

I need to predict search while I type. So if I have stored word "computer" and "company" and I start typing comp, under search box results computer and company should appear.

I added jquery:

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script>
$( "#location1" ).autocomplete({
        source: "ajaxurl",
        minLength: 1,
        select: function( event, ui ) {
            log( ui.item ?
                "Selected: " + ui.item.value + " aka " + ui.item.id :
                "Nothing selected, input was " + this.value );
        }
    });
    </script>
function search_ajax_callback_function() {
    // Implement ajax function here
}
add_action( 'wp_ajax_search_db', 'search_ajax_callback_function' ); 

and I have php:

$servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "database";

// Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }


    $sql = "SELECT * FROM locations";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while ($row = $result->fetch_assoc()) {

        }
    } else {

    }
    $conn->close();

So does anybody knows how to add predictions to my search ?

1

So in php it needs to be:

$query = 'SELECT Location FROM locations';
$result = mysqli_query($link, $query);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
 $rows[] = $r['Location'];
 }

and jquery ui autocomplete:

$("#location1").autocomplete({
            source: <?php echo json_encode($rows);?>,
// this part is only if you want to force autocomplete select
change: function (event, ui) {
    if(!ui.item){
        $(event.target).val("");
    }
}, 
focus: function (event, ui) {
    return false;
} //end autocomplete force
        });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.