I try to create newTag and set the new ID from server response, the newTag is successfully identified and inserted to database, but the new ID value not set properly.
I’m using Laravel so the url part are using laravel blade template.
Here’s the server response when newTag successfully inserted to database:
{"response":{"news_tags":"lorem-ipsum","tags_id":61290}}
and this is my Select2 code :
$(".tags").select2({
ajax : {
url : "{{ url('get_tags/') }}",
data : function(params){
var query = {
keywords : params.term
}
return query;
},
processResults : function(data){
return {
results : $.map( data.items, function( obj ) {
return {
text : obj.news_tags,
id : obj.tags_id
};
})
};
}
},
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term,
newTag: true // add additional parameters
}
},
minimumInputLength : 3,
tags: true
}).on("select2:select", function (e){
if(e.params.data.tag == false) {
return;
}
var select2element = $(this);
if(e.params.data.newTag === true)
{
$.ajax({
url : "{{ url('new_tags/') }}",
data: { "new_tags" : e.params.data.text },
type: "POST",
success: function( res )
{
data = {
"id" : res.response.tags_id,
"text" : res.response.news_tags
}
var selection = select2element.val();
var index = selection.indexOf( res.response.news_tags );
if( index !== -1 )
{
selection[index] = res.response.tags_id.toString();
}
select2element.val(selection).trigger("change");
},
});
}
});