Including form state in select2 AJAX

Including form state in select2 AJAX

990consulting990consulting Posts: 23Questions: 7Answers: 0

I have a form with multiple dependent fields (cascading like, eg, country->region). Some of those fields have thousands of options, so I want to use select2. However, if I return all of them at once, I crash the browser--it needs to be handled server-side. Thing is, since the select2 AJAX feature is not editor-specific, it only sends state information about the state of the select2 object itself (as far as I can tell). So I'm not sure how to tell the control which options to have as the master set (i.e., before the user starts typing in the select)?

Sorry if this question has been answered before--I'm a novice at Javascript, and it took me awhile even to figure out the relationship between "opts" and the select2 control, so I'm not even sure how to search the forums for the appropriate answer.

This question has an accepted answers - jump to answer

Answers

  • 990consulting990consulting Posts: 23Questions: 7Answers: 0

    Clarification: I'm just trying to figure out what to write client-side, in terms of conveying the form state in the AJAX sent to the server by select2 as the user types. Once it's on the server side, I'm in my element.

  • bindridbindrid Posts: 730Questions: 0Answers: 119
    edited February 2018 Answer ✓

    from Select2 site, their ajax looks like:

    $('#ddlCounty').select2({
      ajax: {
        url: 'https://api.github.com/orgs/select2/repos',
        data: function (params) {
          var query = {
            search: params.term,
            type: 'public'
          }
    
          // Query parameters will be ?search=[term]&type=public
          return query;
        }
      }
    });
    

    that being the case, then you can modify it to look like

    $('#ddlCounty').select2({
      ajax: {
        url: 'https://api.github.com/orgs/select2/repos',
        data: function (params) {
          var query = {
            search: params.term,
            type: 'public'
          }
         // add this to get the parent id
          query.state = $("#ddlState").val();
    
          // Query parameters will be ?search=[term]&type=public&state=WA
          return query;
        }
      }
    });
    
  • bindridbindrid Posts: 730Questions: 0Answers: 119

    opps, sorry about the double post. Just pay attention to the second one

  • 990consulting990consulting Posts: 23Questions: 7Answers: 0

    Brilliant! Can't wait to try it. Thank you so much.

This discussion has been closed.