0

I'm working on an assignment where I'm supposed to build a set of web forms so you can submit data to a database and add an entry to a specific table. I built a field that helps the user with suggestions retrieved from the db through a php request, basically while the user types into the field, a list of suggestions pops up and he/she can select an option.

Let's say I'm adding a new entry in a 'books' table and I can fill the 'author' form only with elements from the 'authors' table (so the user can't put an arbitrary author). To do that I used the autosuggestion method.

The 'books' table has a foreign key 'aut_id' which is the id attribute (primary key) of the 'authors' table.

As I said before I'm using php to retrieve the list of suggestions (author name, author surname and author id as well). But once the user clicks on a suggestion the web form is filled with the author name and surname and I don't know how to take advantage of this query so that when the user clicks "Submit" the aut_id field is properly filled.

I'll put some code, here is the HTML + Script:

<script type="text/javascript">
    function lookup(inputAuthor) {
        if(inputAuthor.length == 0) {
            // Hide the suggestion box.
            $('#suggestions').hide();
        } else {
            $.post("suggestionRetriever.php", {queryString: ""+inputAuthor+""}, function(data){
                if(data.length >0) {
                    $('#suggestions').show();
                    $('#autoSuggestionsList').html(data);
                }
            });
        }
    } // lookup

    function fill(thisValue) {
        $('#inputAuthor').val(thisValue);
        setTimeout("$('#suggestions').hide();", 200);
    }
</script>

...more hrml...

        <div class="form-group">
        <label for="inputAuthor">Author</label>
        <input type="text" class="form-control" id="inputAuthor" placeholder="Author name" onkeyup="lookup(this.value);" onblur="fill();">
    </div>

    <div class="suggestionsBox" id="suggestions" style="display: none;">
            <div class="suggestionList" id="autoSuggestionsList">
                &nbsp;
            </div>
    </div>

And here is the php I'm using to retrieve the suggestion list:

if(!$db) {
    echo 'ERROR: Could not connect to the database.';
} else {
    if(isset($_POST['queryString'])) {
        $queryString = $db->real_escape_string($_POST['queryString']);          
        if(strlen($queryString) >0) {

            $query = $db->query("SELECT aut_name, aut_surname, aut_id FROM author WHERE aut_name LIKE '$queryString%' LIMIT 10");
//I could echo the aut_id but I wouldn't know how to retrieve it on Submit with php
            if($query) {
                while ($result = $query ->fetch_object()) {
                    if(!$result->aut_surname){
                        echo '<li onClick="fill(\''.$result->aut_name.'\'); return false"><a href="">'.$result->aut_name.'</a></li>';
                    }else{
                        echo '<li onClick="fill(\''.$result->aut_name.' ' .$result->aut_surname.'\'); return false"><a href="">'.$result->aut_name.' ' .$result->aut_surname.'</a></li>';
                    }
                }
            } else {
                echo 'ERROR: There was a problem with the query.';
            }
        } else {
            // Dont do anything.
        }
    } else {
        echo 'There should be no direct access to this script!';
    }
}

The form is then filled with the proper name and surname but that's not what I need. So I can't use the $_POST php function as I do for any other field. I know I can solve this problem somehow, but I'd like to know the most proper way to do it. I'm kind of new to php so I might be missing something, I read some people using the DOM to retrieve the proper content. I could do another query to the db on submit so that it would look for the id of the author the user typed and then INSERT the proper data, but I think there might be a way to take advantage of the query I already did to retrieve the suggestions list. I just don't know how.

If I didn't make the problem clear enough please ask me anything and I'll try to do better. Thanks in advance for your time.

1 Answer 1

1

I would return the aut_id in the php script such as

PHP:

if($query) {
                while ($result = $query ->fetch_object()) {
                    if(!$result->aut_surname){
                        echo '<li onClick="fill(\''.$result->aut_name.'\', \'' + $result->aut_id + '\''); return false"><a href="">'.$result->aut_name.'</a></li>';
                    }else{
                        echo '<li onClick="fill(\''.$result->aut_name.' ' .$result->aut_surname.'\', \'' + $result->aut_id + '\''); return false"><a href="">'.$result->aut_name.' ' .$result->aut_surname.'</a></li>';
                    }
                }

You could add a hidden field and then on the form which you would set the value of the hidden field in the fill function.

HTML:

<div class="form-group">
        <label for="inputAuthor">Author</label>
        <input type="text" class="form-control" id="inputAuthor" placeholder="Author name" onkeyup="lookup(this.value);" onblur="fill();">
        <input type="hidden" id="hiddenAutId"/>
    </div>

    <div class="suggestionsBox" id="suggestions" style="display: none;">
            <div class="suggestionList" id="autoSuggestionsList">
                &nbsp;
            </div>
    </div>

Javascript:

function fill(thisValue, autId) {
        $('#inputAuthor').val(thisValue);
        $('#hiddenAutId').val(autId);
        setTimeout("$('#suggestions').hide();", 200);
    }

Also have a look at this question, if you return your authors in JSON format you can skip the hidden field.

how to set id in jquery ui autocomplete source event

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Worked lika a charm! I think I'm gonna stick with this but do you think is bad practice using a hidden field instead of the JSON format ?
It is entirely up to you. I would be sending the data via JSON in anycase but whether you populate the field itself or a hidden field is up to you. In the linked answer (if it didn't redirect), once selected, the actual displayed value would become the id of the item which sometimes is not what you want to display to your users for obvious reasons so you would have to have a hidden field in anycase.

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.