3

I have jQuery UI autocomplete input with AJAX source where I want to show the label and not the id; but my code shows both when the search results come back. How can I show just the label?

PHP:

<?php
require_once '../php/db_conx.php';
$req = "SELECT * 
        FROM ads 
        WHERE bbookname LIKE '%" . strtolower(mysql_real_escape_string($_REQUEST['term'])) . "%' ";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
    $return = array(
        'label' => $row['bbookname'] . ' ' . $row['bbookschool'],
        'value' => $row['adid']
    );
}
echo json_encode($return);
?>

jQuery/AJAX:

$("#BooksSearchInput").autocomplete({
    source: '../Search/BP_Books_Search.php',
    minLength: 1,
    autoFocus: false,
    select: function(event, ui) {
        var SearchBookVal = (ui.item.value)
        $.ajax({
            type: "POST",
            data: {
                data: SearchBookVal
            },
            url: "../php/SearchBooks_results.php"
        }).done(function(feedback) {
            $('#booksads').html(feedback)
        });
    }
});

Please note that I do need the adid to be available in the JavaScript callback, as I use this to reference the result.

4
  • Run your php code by itself (don't call it from the client code) and see what pops up on the screen. This can help you parse your code to exactly the data you want. If you don't have a huge number of books, it might be to your advantage to call php code that passes all the books to the client, then let the client autocomplete iterate through the choices. Commented Dec 14, 2013 at 21:26
  • Drat, what do the two PHP scripts do (BP_Books_Search.php and SearchBooks_results.php)? Commented Dec 17, 2013 at 6:46
  • There's some serious ambiguity in this question. The questioner obviously didn't spend a lot of time going over the code and has trouble articulating what he's looking to achieve Commented Dec 17, 2013 at 6:50
  • SearchBooks_results.php returns a books that is being clicked, and BP_Books_Search.php displays those results on the auto complete. Commented Dec 17, 2013 at 6:52

6 Answers 6

7
+50

You have got a couple of things wrong in your code.

First of all, the following line in the PHP script:

$return = array(...)

means the return variable will be overwritten on each iteration and result will always be an array with one item (or a PHP warning and the string null if no matching rows were found). To fix:

$return = array();
while ($row = mysql_fetch_array($query)) {
    $return[] = array(
        "label" => $row["bbookname"] . " " . $row["bbookschool"],
        "value" => $row["adid"],
        // you can add additional keys without causing problems
        "feedback" => $row["feedback"]
    );
}
echo json_encode($return);

Secondly, to display the label in the textbox you can use the code for onFocus and onSelect from this answer:

// ...
focus: function (event, ui) {
    event.preventDefault();
    $(this).val(ui.item.label);
},
select: function (event, ui) {
    event.preventDefault();
    $(this).val(ui.item.label);
    $("#booksads").html(ui.item.feedback);
}
// ...
Sign up to request clarification or add additional context in comments.

1 Comment

The onFocus/onSelect method is also referenced in the jQuery docs for autocomplete: jqueryui.com/autocomplete/#custom-data
1

I see a couple of issues with the posted code. First, your returned json will always return only one row, the last row, because you are overwriting $return on each loop. This is how the code should read

$return[] = array ('label' => $row['bbookname'] . ' '.$row['bbookschool'],
'value' => $row['adid']
);

This will return all the matched rows. Second, you are including the database value in your array in the value key. If you don't want to display the database id, don't include it in your returned json.

$return[] = array ('label' => $row['bbookname'] . ' '.$row['bbookschool');

If you need the database id in the returned json, but don't want to display it on the screen, you should change the way the returned data is handled. Right now you are outputting the entire result set to the screen with the call to the HTML function.

Your query, which is using the deprecated mysql_query function, is looking for $_REQUEST['term'] but your ajax code is sending the value using data as the variable name.

  data: {data:SearchBookVal},

It should probably read

  data: {term:SearchBookVal},

2 Comments

If you remove 'adid' from php ajax won't get the id of the result being searched and i won't have a way to reference the result when clicked.
I edited my response to account for that. If you don't want the database id to display on screen, you'll need to change the way you display the results in your ajax call.
1

On selecting an item from the autocomplete list, the textbox shows the 'value' attribute of the item. If you want the bookname with bookschool to be shown as value, you can have the same concatenation of strings as you have for label. Since you need the adid for the ajax request, you can add a additional parameter for the same. For example,

$return = array();

while($row = mysql_fetch_array($query))

{

 $dataItem = array (

   'label' => $row['bbookname'] . ' '.$row['bbookschool'],

   'value' => $row['bbookname'] . ' '.$row['bbookschool'],

   'id' => $row['adid']

 );

 $return.push($dataItem);

}

Edit: To return all the rows that the query returns, you have to construct an array of values with the results, and return that array. Instead, the current code will return you only the last row of the query result.

Comments

0

use alert or logging to see on which attribute of object ui, adid is stored, try

alert(JSON.stringify(ui));

Comments

0

try something like this

$main_arr = array();
while($row = mysql_fetch_array($query))
{
    $json_arr = array();
    $json_arr['label'] = $row['bbookname'] . ' '.$row['bbookschool'];
    $json_arr['value'] = $row['adid'];
    array_push($main_arr,$json_arr);
}
echo json_encode($main_arr);

Comments

0

try this:

$return = array();
array_push($return,array("value"=>$row['adid'],"label"=>$row['bbookname'] . ' '.$row['bbookschool']));
$json = json_encode($return);
echo $json;

and use following to display label in textbox:

$('#booksads').html(ui.item.label)  //if you want display value then change it to ui.item.value

or see these

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.