简体   繁体   中英

Unable to pass json data to typeahead with php

I want to pass an array of data from php to typeahead, but its not working, I dont know what I am doing wrong. I have checked other questions but unable to get solution. I tried displaying the response on console and it displays the array of strings but nothing in typeahead field

PHP

$resp = array();
        $states = $this->cj_model->list_all_states();
        foreach($states as $row){
            $resp[] = $row['name'];
        }
        echo json_encode($resp);

JS

var substringMatcher = function(strs) {
    return function findMatches(q, cb) {
        var matches, substringRegex;

        // an array that will be populated with substring matches
        matches = [];

        // regex used to determine if a string contains the substring `q`
        substrRegex = new RegExp(q, 'i');

        // iterate through the pool of strings and for any string that
        // contains the substring `q`, add it to the `matches` array
        $.each(strs, function(i, str) {
            if (substrRegex.test(str)) {
                matches.push(str);
            }
        });

        cb(matches);
    };
};

AJAX

 function get_states()
    {
        $.ajax({
            url:  'country/get_states/',
            dataType: 'json',
            type: 'get',
            async: true,
            success: function(response){
               return (response);
            },
            error: function(jqxhr, textStatus, error){
                console.log(error);
            }
        });
    }

   var states = get_states();

   $('.typeahead').typeahead({
            hint: true,
            highlight: true,
            minLength: 1
        },
        {
            name: 'states',
            source: substringMatcher(states)
        });

The problem is you are trying to return something on ajax success function. In that case it is impossible because ajax doing async request. Write your code like this.

$.ajax({
            url:  'country/get_states/',
            dataType: 'json',
            type: 'get',
            async: true,
            success: function(response){
               $('.typeahead').typeahead({
                    hint: true,
                    highlight: true,
                    minLength: 1
                  },
                  {
                   name: 'states',
                   source: substringMatcher(states)
              });
            },
            error: function(jqxhr, textStatus, error){
                console.log(error);
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM