2

I found the very nice demo by Oleg (http://www.ok-soft-gmbh.com/jqGrid/FillToolbarSearchFilter.htm) which shows a "jqGrid toolbar search with autocomplete using local data" but have trouble to get this to work for json via ajax. Is there a good reason why the autocomplete feature won't work - even if I force the grid to be local after loading?

$(document).ready(function() {

    var mygrid = $("#mylist"),
    mygetUniqueNames = function(columnName) {
        var texts = mygrid.jqGrid('getCol',columnName), uniqueTexts = [],
            textsLength = texts.length, text, textsMap = {}, i;
        for (i=0;i<textsLength;i++) {
            text = texts[i];
            if (text !== undefined && textsMap[text] === undefined) {
                // to test whether the texts is unique we place it in the map.
                textsMap[text] = true;
                uniqueTexts.push(text);
            }
        }
        return uniqueTexts;
    };





    mygrid.jqGrid({
            url:'autocompleteTest.php',
            datatype: "json",
            colNames:['name', 'City','stateCd'],
            colModel:[                      
                    {name:'name',index:'name',width:225, search: true},
                    {name:'City',index:'City',width:125},
                    {name:'stateCd',index:'stateCd',width:75},
                  ],

         rowNum: 100,
        loadonce : true,
         sortname: 'name',
        sortorder: 'desc',
         sortable: true,
        viewrecords: true,
        rownumbers: true,
        sortorder: "desc",
        ignoreCase: true,
        pager: '#mypager',
        height: "auto",
        caption: "How to use filterToolbar better with data from server"
    }).jqGrid('navGrid','#mypager',
              {edit:false, add:false, del:false, search:false, refresh:false});

    mygrid.jqGrid('setColProp', 'name',
            {
                searchoptions: {
                    sopt:['bw'],
                    dataInit: function(elem) {
                        $(elem).autocomplete({
                            source:mygetUniqueNames('name'),
                            delay:0,
                            minLength:0
                        });
                    }
                }
            });

    mygrid.jqGrid('filterToolbar',
            {stringResult:true, searchOnEnter:true, defaultSearch:"bw"});

    });
J. Kaufman
  • 33
  • 1
  • 1
  • 5
  • http://stackoverflow.com/questions/5328072/can-jqgrid-support-dropdowns-in-the-toolbar-filter-fields?tab=votes#tab-top – J. Kaufman May 17 '11 at 21:03
  • you should use `dataInit` option of `colModel` to initialize the jQuery UI Autocomplete control. Because jqGrid has no direct support of [jQuery UI Autocomplete](http://jqueryui.com/demos/autocomplete/#remote) you should just implement in your server code the corresponding part. Because you don't posted any code it it unclear whether you has problems on the client or on the server side. If you post the code one can gives you more advices. – Oleg May 18 '11 at 21:08
  • [Hallo! Schoen dass Sie gescrhieben haben.] I used your code from that demo word for word; and so used datainit as you describe. I will post the code example in a bit. mfg, J – J. Kaufman May 19 '11 at 18:16
  • @J. Kaufman: The url which I posted shows (if you click on "View Source" link on the page) that in case of ajax call to the server the `source` parameter of `autocomplete` should be **the server url** which provide the data. – Oleg May 19 '11 at 20:53
  • @Oleg, since I have the data in the grid already I was hoping that I could create the array that the source parameter is expecting. Are you saying that I should have a separate server url to get the result in expected form. Do you think that is a promising approach? Sorry if I am being daft... – J. Kaufman May 19 '11 at 21:26
  • @J. Kaufman: Probably there are misunderstanding. It was your question how to change my old for remote data from the server. You wrote that you know my demo where the `source` parameter is local data, "but have trouble to get this to work for json via ajax". So what you really want to implement? – Oleg May 19 '11 at 21:38
  • @Oleg, I used your code for getUniqueNames on a grid in the same exact way to populate source for autocomplete. The only difference was that I had populated my grid via json - not local. I could not get the demo to work in that way. I then tried to change the grid to be local - thinking that might be problem. Can you update your demo to read its data from some db via url to see if the non-local grid can autocomplete? I can understand if you don't want to try, just let me know if I was clear in explaining what I think is the problem. – J. Kaufman May 20 '11 at 20:42
  • Ooh, good thing I Googled jqgrid autocomplete search or else I might have ran into some difficulties setting this up when it comes to implementation time. *adds to Favs so he can find it later* – Powerlord Jul 17 '12 at 14:29
  • Revisa este enlace (check this link) http://stackoverflow.com/questions/17179777/search-with-autocomplete-in-codeigniter-and-jqgrid/17195094#17195094 – Rudolph Fentz Jun 19 '13 at 15:39

1 Answers1

3

It is difficult to provide an example in case of the usage of remote source parameter of jQuery UI Autocomplete. The main problem is that your question is about jqGrid which is pure JavaScript solution. If we would discuss the server part of tha solution we would have too options. Many users uses different languages: Java, C#, VB, PHP and so on. For example I personally prefer C#. Then we would have to choose the technology which we use: ASP.NET MVC, WCF, ASPX web service and so on. For example I would choose WCF. Then we should define the database access technology, for example, Entity Framework, LINQ to SQL, SqlDataReader, SqlDataAdapter and so on. Let us I would choose Entity Framework and would provide you the corresponding code example, but it would help you not really if you use for example PHP and MySQL.

So I just describe which interface should have the server for the remote source parameter of jQuery UI Autocomplete without any code.

You should replace in my example the source parameter to your server url like following:

dataInit: function(elem) {
    $(elem).autocomplete({
        source:'yourSearchUrl.php',
        minLength:2
    });
}

If the user types two characters (the value can be changed by minLength option), for example 'ab' then the autocomplete will make HTTP GET request with the parameter term=ab:

yourSearchUrl.php?term=ab

your server should answer with the JSON data in the same format as for the local source. I used the string array format in my previous example. Another supported format is array of objects with label/value/both properties like

[
    {
        "id": "Dromas ardeola",
        "label": "Crab-Plover",
        "value": "Crab-Plover"
    },
    {
        "id": "Larus sabini",
        "label": "Sabine`s Gull",
        "value": "Sabine`s Gull"
    },
    {
        "id": "Vanellus gregarius",
        "label": "Sociable Lapwing",
        "value": "Sociable Lapwing"
    },
    {
        "id": "Oenanthe isabellina",
        "label": "Isabelline Wheatear",
        "value": "Isabelline Wheatear"
    }
]

read the documentation for more information.

If you need to implement more complex scenario and send some additional data to the server or convert the server response in any way you can use custom source callback function. In the case you should use source: function(request, response) {/*your implementation*/}, where the request would be an object having term property (request.term). Inside of your implementation your should make ajax request to the server manually. The response would be callback function which you should call after your custom ajax request will be finished (inside of success event handler). The response function should be called with the parameter which should be array in the same format as mygetUniqueNames returns. I recommend you to examine the source code from the jQuery Autocomplete demo.

To de able to provide unique data from one column of tabele you should just use SELECT DISTINCT SQL statement which are supported in the most databases.

I hope that my description would help you.

UPDATED: If you have the local source the solution you could find in my old answer which you already use. What you just need to do is to call the filterToolbar after the source array are filled. Because you load the data from the server your should move the call of filterToolbar inside of loadComplete. You use loadonce:true jqGrid option which switch the datatype from 'json' to 'local' after the first data loading. So you can include in the loadComplete event handler of your grid the code like the following:

var grid = $('#list');
grid({
    url:'autocompleteTest.php',
    datatype: 'json',
    loadonce: true,
    // ... other parameters
    loadComplete: function(data) {
        if (grid.getGridParam('datatype') === 'json') {
            // build the set 'source' parameter of the autocomplete
            grid.jqGrid('setColProp', 'name', {
                searchoptions: {
                    sopt:['bw'],
                    dataInit: function(elem) {
                        $(elem).autocomplete({
                            source:mygetUniqueNames('name'),
                            delay:0,
                            minLength:0
                        });
                    }
                }
            });
            mygrid.jqGrid('filterToolbar',
                          {stringResult:true,searchOnEnter:true,
                           defaultSearch:"bw"});
        }
    }
});

If you will need to reload the data from the server (change the datatype to 'json' and call grid.trigger('reloadGrid')) you will have to change the code above so that you first destroy the autocomplete widget with $('#gs_name').autocomplete('destroy') and then create it one more time with the same code like inside of dataInit.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • I appreciate very much your effort, but I already have the data in the grid - so I fail to see why I need to query server again for data that jqGrid already knows about. I want to take the data from a column in the grid and enable autocomplete in the same way you did for local data. I think that my question was only about jqgrid and autocomplete - not where or how I got the data from server... – J. Kaufman May 23 '11 at 20:49
  • @: If you have the local source the solution you could find in [my old answer](http://stackoverflow.com/questions/5328072/can-jqgrid-support-dropdowns-in-the-toolbar-filter-fields/5329014#5329014). What you just need is to call `filterToolbar` **after** the `source` array are filled. So your should move the call of `filterToolbar` inside of `loadComplete`. You should call it only on the first grid loading (if `datatype` is still 'json'). – Oleg May 24 '11 at 06:32
  • YES! That was it. Really great to have had your answer. Would you put that last bit as an answer to this question? I don't think I can vote yet but I want to thank you. – J. Kaufman May 24 '11 at 14:03
  • @J. Kaufman: I updated the answer to describe all more clear. You will be able to vote up questions or answers after the first 15 points of reputation. – Oleg May 24 '11 at 14:38
  • @Oleg, and again this is a great answer. i got one problem, if you look at my code at this question [link](http://stackoverflow.com/questions/8500878/jqgrid-cant-select-rows-cannot-call-method-indexof-of-undefined), i get my data from webservice, and if i do this: `dataInit: function(elem) { $(elem).autocomplete({ source:'./WebService.asmx/ViewNQueryData', minLength:2 }); }` with my url i get a browser exception. it never gets to the server, what has to changed? – Ovi Dec 14 '11 at 09:37
  • @Ovi: I just answered on your question. the error was because of is duplicates which is not permitted. – Oleg Dec 14 '11 at 09:40
  • @Oleg, thanks for all answers, i fixed that problem i had, but still with the above code i wrote in the comment the grid tries to go to `/WebService.asmx/ViewNQueryData?term=gg` and cant do it. – Ovi Dec 14 '11 at 09:49
  • @Ovi: I am not sure that I understand you correctly. Do you have an exception? Where? In what line of code? Which code you use exactly. Do you can see that the request with the parameter `term=gg` will be send to the server? Do you receive the request in the server code (can you set the breakpoint)? ... – Oleg Dec 14 '11 at 10:05
  • @Oleg, i posted a new question [here](http://stackoverflow.com/questions/8502962/jqgrid-toolbar-search-with-auto-complete-from-server-using-json), thanks – Ovi Dec 14 '11 at 10:30