Typeahead.js include dynamic variable in remote url
Asked Answered
F

6

14

I have tried for hours now, to get a variable in my "remote" path. The variable will change, depending on another input. Here is the code:

school_value = $('#school').val();
$('#school').change(function () {
    school_value = $(this).val();
    $('#programme').typeahead('destroy'); // I have also tried with destroy - but it doesnt work.
});
$('#programme').typeahead({
    remote: 'typeahead.php?programme&type=1&school_name=' + school_value,
    cache: false,
    limit: 10
});

The variable 'school_type' is not set in the remote addr, and therefore not called.

Do you have any clue how to get it working? I have just switched from Bootstrap 2.3 to 3, and then noticed typeahead was deprecated. Above code worked on Bootstrap 2.3, but it seems like when the script is initialized, the remote path is locked.

Federal answered 8/9, 2013 at 21:37 Comment(7)
I guess those backslashes are remnants of this being printed by PHP or similar? You should remove them here.Rajewski
Or just use single quotes ', with no backslash like the rest of your code.Kenward
Mattias, I edited your post to fix indent on code and replaced the quotes as in the comments. Hope it was ok :)Kenward
Well, with the code more readable, I have no idea what's being asked. You mention school_type, which I don't see but assume is some other field you want to include in this request. Yet you say it used to work? Is this about doing something new or fixing something which broke with an update?Rajewski
Thanks for your suggestions. Yes the backslashes is used, because it is implied in a PHP-code. I have now tried without, and it doesn't work. The "school_value" is a variable with gets the value from another text-field. It is because typeahead needs to search in a specific category based on school_value's value. The problem is in setting the value of school_value, it is supposed to change the value, when #school changes, but it doesn't. If I predefine "school_value" like this: school_value = 'testing' it then works perfectly. But it just wont change, when I type in something in #school.Federal
Saw somebody else has same problem, see: github.com/twitter/typeahead.js/issues/418Federal
Also here: github.com/twitter/typeahead.js/issues/655Tribade
F
14

I have found the solution! Code:

$('#programme').typeahead({
    remote: {
        url: 'typeahead.php?programme&type=1&school_name=',
        replace: function () {
            var q = 'typeahead.php?programme&type=1&school_name=';
            if ($('#school').val()) {
                q += encodeURIComponent($('#school').val());
            }
            return q;
        }
    },
    cache: false,
    limit: 10
});

Based on this threads answer: Bootstrap 3 typeahead.js - remote url attributes

See function "replace" in the typeahead.js docs

Federal answered 9/9, 2013 at 8:19 Comment(1)
this answer already outdated. see @andrewtweber answerBarnabas
P
11

I believe the accepted answer is now out of date. The remote option no longer has replace. Instead you should use prepare:

$('#programme').typeahead({
    remote: {
        url: 'typeahead.php?programme&type=1&school_name=',
        prepare: function (query, settings) {
            settings.url += encodeURIComponent($('#school').val());

            return settings;
        }
    }
});

One issue I ran into was pulling the value from another typeahead object. Typeahead essentially duplicates your input, including all classes, so you have two nearly identical objects, one with the tt-hint class and the other with tt-input. I had to specify that it was the tt-input selector, otherwise the value I got was an empty string.

$('.field-make').val();  // was "" even though the field had a value
$('.field-make.tt-input').val();  // gave the correct value

Bloodhound remote options

Piccadilly answered 26/9, 2015 at 20:54 Comment(1)
It should be noted as well that the normal use of the wildcard parameter that defaults to %QUERY will not work if you are using prepare - it is passed in to the callback you specify for prepare and you need to put it into your URL yourself. Glad you added this updated answer as it helped me out.Ahead
A
3

There is actually a slight refinement of Mattias' answer available in the newer Bloodhound js, which reduces duplication and opportunity for error:

$('#programme').typeahead({
    remote: {
        url: 'typeahead.php?programme&type=1&school_name=',
        replace: function (url, query) {
            if ($('#school').val()) {
                url += encodeURIComponent($('#school').val());
            }
            return url;
        }
    },
    cache: false,
    limit: 10
});
Analyzer answered 4/9, 2014 at 14:20 Comment(2)
Great answer. Bear in mind to future visitors that using replace completely overrides the native insertion of the query string into the url so you will need to do this here if you necessary.Tribade
The replace option doesn't seem to exist anymore... Couldn't find it in the docs.England
H
0

@Mattias, Just as a heads up, you could clean up your replace method a little by supplying the optional url parameter.

$('#programme').typeahead({
    remote: {
        url: 'typeahead.php?programme&type=1&school_name=',
        replace: function (url, query) {
            // This 'if' statement is only necessary if there's a chance that the input might not exist.
            if ($('#school').val()) {
                url += encodeURIComponent(('#school').val());
            }
            return url;
        }
    },
    cache: false,
    limit: 10
});
Hagen answered 27/10, 2015 at 18:33 Comment(0)
A
0

Am I looking at the same thing as all of you?

http://www.runningcoder.org/jquerytypeahead/

It looks like it has changed AGAIN! It is not very obvious how to do it in the documentation, but there is example code. I pulled this straight from the code in the documentation.

There is a second example in the documentation where they do it yet a different way! This way is the most succinct I think.

// Set a function that return a request object to have "dynamic" conditions
dynamic: true,
source: {
    tag: {
        ajax: function (query) {
            if (query === "hey") {
                query = "hi"
            }
            return {
                url: "http://www.gamer-hub.com/tag/list.json",
                dataType: "jsonp",
                path: data,
                data: {
                    q: query
                }
            }
        }
    }
}

And here is my working example:

                source: {
                    ajax: function() {
                        var filter = {
                            partnerId: @Model.PartnerId,
                            productTypeId: @Model.ProductTypeId,
                            unitType: $("[name=UnitType]").val(),
                            manufacturer: "",
                            columnName: "@nameof(SaleViewModel.Manufacturer)"
                        };
                        var queryString = $.param(filter);
                        return {
                            url: recentEntriesBaseUrl + "?" + queryString
                        }
                    }
                },
Ashaashamed answered 5/6, 2020 at 13:37 Comment(1)
Ha. I think this is correct. Typeahead was removed from Bootstrap. Now it is a separate plugin.Ashaashamed
M
0

If you want to use wildcard parameter %QUERY, then add url = url.replace("%QUERY", q);

$('#programme').typeahead({
    remote: {
        url: 'typeahead.php?programme&q=%QUERY',
        replace: function (url, q) {
            url = url.replace("%QUERY", q);
            let val = $('#school').val();
            if(val) url += '&school_name=' + encodeURIComponent(val);
            return url;
        }
    },
    limit: 10
});
Mattland answered 1/7, 2022 at 11:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.