Select2 -> Dynamic input returns as a string (jQuery
-
21-12-2019 - |
Question
The format for my select 2 is as such:
$("#selectPretty").select2({
tokenSeparators: [","],
tags:["1", "2", "3", "php", "tiger", "test", "big bang theory", "bikes", "gh", "sd", "cheese", "food", "name", "jack", "chickens", "yikes!", "testing", "this", "is", "a", "questionj", "new", "question", "s"]
});
Which shows as such:
BUT, when I try to assign data into the box dynamically through AJAX by using this code:
$.ajax({
type: "POST",
url: "grabTags.php",
data: "tags="+$("#selectPretty").val(),
success:
function(msg2) {
alert(msg2);
$("#selectPretty").select2({
tokenSeparators: [","],
tags:[msg2]
});
}
});
It will come out like so:
For some reason the whole string is one option and I can't make it explode the result into different options...
Does anyone know what I can do here?
Note that 'tags:[msg2]' is returned from my grabTags.php file and 'msg2' = "1", "2", "3, etc...
Kindest Regards
Solution
Have you tried splitting the string that comes back from the PHP?
You can invoke the split
method on a string (such as that which is returned from your PHP) and pass it a separator (in your case a ,
).
Something like this should work:
$.ajax({
type: "POST",
url: "grabTags.php",
data: "tags="+$("#selectPretty").val(),
success:
function(msg2) {
//at this point, msg2 is the string: '"1","2","3"'
var myTags = msg2.split(',');
//myTags is now the array: ["1","2","3"]
$("#selectPretty").select2({
//tags needs to be an array, so pass in myTags
tags: myTags
});
}
});
OTHER TIPS
The Select2 tags
need a javascript array, not just a string surrounded by brackets.
So server side, have PHP spit out a json encoded array:
$tags = array("1", "2", "3", "php", "tiger", "test", "big bang theory", "bikes", "gh", "sd", "cheese", "food", "name", "jack", "chickens", "yikes!", "testing", "this", "is", "a", "questionj", "new", "question", "s");
echo json_encode($tags);
Now client side take that response in your ajax success
handler, and assign it directly to tags
.
Note that you may need to set dataType
to json
in your ajax call so that jQuery automatically parses the response as json. Not sure if it will figure that out on its own or not.
You may also be able to get rid of tokenSeparators
if you provide an actual array as your tags.