Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Maison012's avatar

Display data from json on select2 list

I am trying ti display all citys of ex:London from an json file downloaded from here: (https://simplemaps.com/data/gb-cities) to my select option . But something is going wrong, the select show me no data. But in console log i can see all city in return

var data = fetch('../json/gb.json')
    .then(response => response.json())
    .then(json => json.map(x => x.city));
    console.log(data);

var placeholder = "select";
$(".mySelect").select2({
    data: data,
    placeholder: placeholder,
    allowClear: false,
    minimumResultsForSearch: 5
});

console.log(data) return me this

Promise {<pending>}
[[Prototype]]
: 
Promise
[[PromiseState]]
: 
"fulfilled"
[[PromiseResult]]
: 
Array(2680)
 0 : "London"
1:"Birmingham"
2: "Manchester"
3: "Leeds"
4: "Newcastle"
.....

//My select neturn no data

``` ```
0 likes
5 replies
MohamedTammam's avatar
Level 51

You need to wait for the response to finish

let data = fetch('../json/gb.json')
    .then(response => response.json())
    .then(json => {
		let cities = json.map(x => {"id": x.city, "text": x.city});
		let placeholder = "select";

		$(".mySelect").select2({
    		data: cities,
    		placeholder: placeholder,
    		allowClear: false,
   	 		minimumResultsForSearch: 5
		});
		
	});
    console.log(data);


1 like
Maison012's avatar

@silencebringer I didnt know about built-in remote data support of select2? https://select2.org/data-sources/ajax but this solution of @mohamedtammam worked for me.

Anyway can someone tell me how can i pass value from select2 on v-model on vue js. I need to save this data on my db also.

<div class="add-new-territory">
       <select v-model="add_territory" class="mySelect form-select" multiple="multiple" style="width: 100%;"></select>
     <button @click="addTerritory()" type="button" class="btn btn-sm btn-success">
            Save
    </button>
</div>

export default {
        data() {
            return {
                add_territory: [],
            }
        },

        methods: {
            addTerritory() {
                axios.post('/territory', {
                    territory_name: this.add_territory,
                })
                .then(response => {
                    console.log(response);
                })
            }
        },
    }
MohamedTammam's avatar

@Leon012 If your problem got solved, that's great. Please close the discussion and open a new one for other problem with more details.

Please or to participate in this conversation.