createTag fires before tag is selected


#1

I am trying to create a person in my database when a tag is created and selected in the select2. The createTag is firing before I actually select the tag I am creating. Not sure if I am doing something wrong or not.

$("#customer").select2({
	ajax: {
		method: "GET",
		url: "https://SOMEURL",
		dataType: "json",
		processResults: function(data){
			return { results: $.map(data, function (obj){
				obj.text = obj.text || obj.name;
				return obj;
			}) };
		}
	},
	tags: true,
	minimumInputLength: 3,
	createTag: function(params){
		var term = $.trim(params.term);

		if(term === ""){
			return null;
		}

		var data = {
			name: "",
			emailAddress: "",
			cellPhone: "",
			note: ""
		};

		if($.isNumeric(term)){
			data.cellPhone = term;
		} else if(term.includes("@")){
			data.emailAddress = term;
		} else {
			data.name = term;
		}

		$.ajax({
			method: "PUT",
			url: "https://SOMEURL",
			data: data
		}).then(
			function(response){
				return {
					id: response.id,
					text: term,
					newTag: true
				};
			}
		);
	}
});

#2

I am having this same issue. createTag is firing on each keypress, shouldn’t it only fire when the user has selected the new tag?