3

I did a lot of searching and I got a lot of results similar to my case, listed below:

Data source is from text file which format like this:

postcode,suburb,state,lat,lon
200,AUSTRALIAN NATIONAL UNIVERSITY,ACT,-35.277272,149.117136
221,BARTON,ACT,-35.201372,149.095065
800,DARWIN,NT,-12.801028,130.955789
801,DARWIN,NT,-12.801028,130.955789
804,PARAP,NT,-12.432181,130.84331
810,ALAWA,NT,-12.378451,130.877014
810,BRINKIN,NT,-12.367769,130.869808
810,CASUARINA,NT,-12.376597,130.850489
810,JINGILI,NT,-12.385761,130.873726
810,LEE POINT,NT,-12.360865,130.891349 

The data I'm trying to include as source of auto-complete field is the first and second(postcode and suburb) fields of each row. But the postcode and suburb filter with state. For example ACT is the active state all the postcode and suburb is the source of auto-complete. And I used array_unique() to remove the repeated data.

//take area from state
function take_area(){
    global $wpdb;
    $uploads = wp_upload_dir();
    $upload = $uploads[baseurl];
    $file = $upload.'/csv/suburb_and_area.txt';
    $f = fopen($file, 'r');
    $state = $_POST['state'];
    $counter = 0;
    while($line = fgets($f, 4096)){
        $details = explode(',', $line); 
        $counter++;
        if(trim($details[2]) == $state){
            $state_arr[$counter] = $details[1];
        }
    }
    $option = '';
    if($state!=''){
        $c=0;
        $area_of_state = array_unique($state_arr);
        foreach($area_of_state as $area){
            if($c>0){$option .= ', ';}
            $option .= '"'.$area.'"';
            $c++;
        }
    }
    echo $option;
}

and the JavaScript:

    $("#state").change(function(){
    var state = $('#state :selected').attr('data-value');
    if(!state){
        state = $('#state').val();
    }
    $.ajax({
        url:"<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php", 
        type:'POST',
        data:'action=take_area_from_state&state=' + state,
        success:function(results){
            if(results!=0){
                $("#area").removeAttr("disabled"); 
                $("#area").empty();
                var source = [results];
                $("#area").autocomplete({source: source});
            }else{
                $("#area").attr("disabled", "disabled"); 
            }
        }
    });

});

And the Response

"AUSTRALIAN NATIONAL UNIVERSITY", "BARTON", "HMAS CRESWELL", "JERVIS BAY", "CANBERRA", "DEAKIN", "DEAKIN WEST", "DUNTROON", "HARMAN", "HMAS HARMAN", "PARKES", "PARLIAMENT HOUSE", "RUSSELL", "YARRALUMLA", "ACTON", "BLACK MOUNTAIN", "AINSLIE", "DICKSON", "DOWNER", "HACKETT", "LYNEHAM", "O'CONNOR", "WATSON", "FORREST", "GRIFFITH", "MANUKA", "RED HILL", "CAUSEWAY", "KINGSTON", "NARRABUNDAH", "CURTIN", "GARRAN", "HUGHES", "CHIFLEY", "LYONS", "O'MALLEY", "PHILLIP", "SWINGER HILL", "WODEN", "FARRER", "ISAACS", "MAWSON", "PEARCE", "TORRENS", "CIVIC SQUARE", "CANBERRA INTERNATIONAL AIRPORT", "FYSHWICK", "MAJURA", "PIALLIGO", "SYMONSTON", "CHAPMAN", "DUFFY", "FISHER", "HOLDER", "MOUNT STROMLO", "PIERCES CREEK", "RIVETT", "STIRLING", "URIARRA", "URIARRA FOREST", "WARAMANGA", "WESTON", "WESTON CREEK", "BRADDON", "CAMPBELL", "REID", "TURNER", "ARANDA", "COOK", "HAWKER", "JAMISON CENTRE", "MACQUARIE", "PAGE", "SCULLIN", "WEETANGERA", "CHARNWOOD", "DUNLOP", "FLOREY", "FLYNN", "FRASER", "HIGGINS", "HOLT", "KIPPAX", "LATHAM", "MACGREGOR", "MELBA", "SPENCE", "BELCONNEN", "BRUCE", "EVATT", "GIRALANG", "KALEEN", "LAWSON", "MCKELLAR", "UNIVERSITY OF CANBERRA", "HALL", "HUME", "KOWEN FOREST", "OAKS ESTATE", "THARWA", "TOP NAAS", "GREENWAY", "TUGGERANONG", "KAMBAH", "ERINDALE CENTRE", "OXLEY", "WANNIASSA", "FADDEN", "GOWRIE", "MACARTHUR", "MONASH", "BONYTHON", "CALWELL", "CHISHOLM", "GILMORE", "ISABELLA PLAINS", "RICHARDSON", "THEODORE", "BANKS", "CONDER", "GORDON", "CRACE", "MITCHELL", "GUNGAHLIN", "FRANKLIN", "GINNINDERRA VILLAGE", "NGUNNAWAL", "NICHOLLS", "PALMERSTON", "AMAROO", "BONNER", "FORDE", "HARRISON"

The data is displayed like this: enter image description here

I know I've done wrong to my code but I can't figure it out.

8
  • Did you try $("#area").autocomplete({ source: results })? Commented Feb 21, 2013 at 14:18
  • Can you show the response you're getting from the server? Commented Feb 21, 2013 at 15:07
  • Are you using Firebug? Or Chrome's developer tools? You can view the response in Firebug's console or in the net tab in Chrome. Commented Feb 21, 2013 at 15:45
  • by that way sir the code $("#area").autocomplete({ source: results }) that is not display anything. I fail to clear my browser cache. Commented Feb 21, 2013 at 16:02
  • That looks like you aren't referencing the jquery.ui style sheet. Commented Feb 21, 2013 at 16:24

1 Answer 1

1

I think you need to use something like

$(function(){

var src = [];

$('#area').autocomplete({
    minLength: 0,
    source: function( request, response ) {
        response(src)
    }
});

$("#state").change(function(){
    var state = $('#state :selected').attr('data-value');
    if(!state){
        state = $('#state').val();
    }
    $.ajax({
        url:"<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php", 
        type:'POST',
        data:'action=take_area_from_state&state=' + state,
        success:function(results){
            if(results!=0){
                $("#area").removeAttr("disabled"); 
                src = $.map(results.split(','), function(v, i){ <----- Convert the string result into an array of objects
                    return {
                        label: v,
                        varlue: v
                    };
                });
            }else{
                $("#area").attr("disabled", "disabled"); 
            }
        }
    });

});

});

Again I'm not sure about your response data from the server. The result object in the success callback should be array of objects like [{label: '<text-to-appear-in-the-dropdown>', value: '<value>'}, {...}, {...}, ...]

Technical Demo: Fiddle (It doesn't uses ajax based source)

If your ajax query is returning an array, then you can create the src array as given below.

var result = ["AUSTRALIAN NATIONAL UNIVERSITY", "BARTON", "HMAS CRESWELL", "JERVIS BAY", "CANBERRA", "DEAKIN", "DEAKIN WEST", "DUNTROON", "HARMAN", "HMAS HARMAN", "PARKES", "PARLIAMENT HOUSE", "RUSSELL", "YARRALUMLA", "ACTON", "BLACK MOUNTAIN", "AINSLIE", "DICKSON", "DOWNER", "HACKETT", "LYNEHAM", "O'CONNOR", "WATSON", "FORREST", "GRIFFITH", "MANUKA", "RED HILL", "CAUSEWAY", "KINGSTON", "NARRABUNDAH", "CURTIN", "GARRAN", "HUGHES", "CHIFLEY", "LYONS", "O'MALLEY", "PHILLIP", "SWINGER HILL", "WODEN", "FARRER", "ISAACS", "MAWSON", "PEARCE", "TORRENS", "CIVIC SQUARE", "CANBERRA INTERNATIONAL AIRPORT", "FYSHWICK", "MAJURA", "PIALLIGO", "SYMONSTON", "CHAPMAN", "DUFFY", "FISHER", "HOLDER", "MOUNT STROMLO", "PIERCES CREEK", "RIVETT", "STIRLING", "URIARRA", "URIARRA FOREST", "WARAMANGA", "WESTON", "WESTON CREEK", "BRADDON", "CAMPBELL", "REID", "TURNER", "ARANDA", "COOK", "HAWKER", "JAMISON CENTRE", "MACQUARIE", "PAGE", "SCULLIN", "WEETANGERA", "CHARNWOOD", "DUNLOP", "FLOREY", "FLYNN", "FRASER", "HIGGINS", "HOLT", "KIPPAX", "LATHAM", "MACGREGOR", "MELBA", "SPENCE", "BELCONNEN", "BRUCE", "EVATT", "GIRALANG", "KALEEN", "LAWSON", "MCKELLAR", "UNIVERSITY OF CANBERRA", "HALL", "HUME", "KOWEN FOREST", "OAKS ESTATE", "THARWA", "TOP NAAS", "GREENWAY", "TUGGERANONG", "KAMBAH", "ERINDALE CENTRE", "OXLEY", "WANNIASSA", "FADDEN", "GOWRIE", "MACARTHUR", "MONASH", "BONYTHON", "CALWELL", "CHISHOLM", "GILMORE", "ISABELLA PLAINS", "RICHARDSON", "THEODORE", "BANKS", "CONDER", "GORDON", "CRACE", "MITCHELL", "GUNGAHLIN", "FRANKLIN", "GINNINDERRA VILLAGE", "NGUNNAWAL", "NICHOLLS", "PALMERSTON", "AMAROO", "BONNER", "FORDE", "HARRISON"]

src = $.map(result, function(val){
    return {label: val, value: val};
});

Another sample with query param support

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

8 Comments

thanks for answer, I try this before to response(src) and the source display per letter like " A S and so on.
Can you following the below steps and let us know the results. In the ajax callback success:function(results){ add two statements console.log(result); and console.log(typeof result). Then check the console to see the output.
There are two in Console: "AUSTRALIAN NATIONAL UNIVERSITY", "NICHOLLS", "PALMERSTON", "AMAROO", "BONNER", "FORDE", "HARRISON" and string.
that is the problem, the response is of type string not array.
is the double quotes present around each item
|

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.