Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load json from text file

I have the following hard coded json,

var dataLocality = [
    { "label": "Arwen" },
    { "label": "Bilbo Baggins" },
    { "label": "Boromir" },
    { "label": "Frodo Baggins" },
    { "label": "Peregrin Pippin Took" },
    { "label": "Samwise Gamgee" }
];

Which I use to populate an autocomplete textbox with the following script,

$(function () {
    $("#locality").autocomplete(
    {
        source: dataLocality
    })
});

I now have a text file that is dynamically updated via my app named dataLocality.text which i'm able to load and view in an alert box with this code,

function codeAddress() {
    jQuery.get('http://localhost/project/jSonDocs/dataWhat.txt', function (data) {
        var dataLocality = data;
        alert(dataLocality);
    });
}
window.onload = codeAddress;

But I can't seem to work out how to get the data from var dataLocality to source: dataLocality

The data in my text doc looks like this,

[
    { "label": "Arwen" },
    { "label": "Bilbo Baggins" },
    { "label": "Boromir" },
    { "label": "Frodo Baggins" },
    { "label": "Peregrin Pippin Took" },
    { "label": "Samwise Gamgee" }
];
like image 901
Bojangles Avatar asked Mar 15 '23 11:03

Bojangles


1 Answers

Assuming you're using the jQueryUI autocomplete method, you can provide the URL of the JSON to the source method and it will retrieve it for you automatically. Try this:

$("#locality").autocomplete({
    source: 'http://localhost/project/jSonDocs/dataWhat.txt'
});

If you still prefer to retrieve the JSON manually (if you need to change the source after initialisation for example) then you can achieve it like this:

function codeAddress() {
    jQuery.get('http://localhost/project/jSonDocs/dataWhat.txt', function (data) {
        $('#locality').autocomplete('option', 'source', data);
    });
}
like image 175
Rory McCrossan Avatar answered Apr 06 '23 00:04

Rory McCrossan