Preselecting options in an remotely-sourced (AJAX) Select2 with custom data atribute

hi, i use:
https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js

my html:

<select name="serv_id" id="serv_id" class="form-control select2s" style="width: 100%;"></select>

initilalization:

$('.select2s').select2({
	
	placeholder: 'Select an service',
	ajax: {
	  url: '_get_services.php',
	  dataType: 'json',
	  delay: 250,
		/*
	  processResults: function (data) {
		  //console.log(data);
		return {
		  results: data
		};
	  },
		*/
		
		processResults: function (data) {
            return {
                results: $.map(data, function (obj) {
                    return { 
                        id: obj.id, 
                        text: obj.text, 
                        price: obj.price 
                    };
                })
            };
        },
		
	  cache: false
	}
});

both processResults work correct with:

    var data=$("#serv_id").select2('data')[0];
    console.log(data.price);

when i try code from documentation - https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2

var sSelect = $('.select2s');
$.ajax({
    type: 'GET',
	dataType: 'json',
    url: '_get_service.php?sid=<?=$row_p["serv_id"];?>'
}).then(function (data) {
	console.log(data);
    // create the option and append to Select2
    var option = new Option(data.text, data.id, true, true);
    $('.select2s').append(option).trigger('change');
	
    // manually trigger the `select2:select` event
    sSelect.trigger({
        type: 'select2:select',
        params: {
            data: data
        }
    });
});

console log shows correct values but select is not changed.

On http://offers.balkanecommerce.com/t.php you can check that ajax get initial val but select not changed.

Best wishes, T

When I try to visit the URL that it’s requesting for the preselected option (http://offers.balkanecommerce.com/_get_service.php?sid=4), I get a redirect back to the login page. Can you temporarily create a publicly accessible version of your API?

Also, FYI, you need to use triple backticks for code blocks (single backticks are only for inline code). See https://learn.userfrosting.com/troubleshooting/getting-help#use-markdown-to-format-blocks-of-code

hi, and thank for triple backticks ( never used)

http://offers.balkanecommerce.com/_get_service.php?sid=4
is public … it’s return - [{“id”:“4”,“text”:"\u0423\u0435\u0431 \u043d\u0435\u0449\u0430",“m_unit”:“1”,“price”:“900.00”}]

code is PHP:

$s = "SELECT
services.name_bg,
services.id,
services.m_unit,
services.mhm_price
FROM
services
where services.id=".GetSQLValueString($_REQUEST['sid'],"int"); 
//echo($s);
$ress = $db->query($s);

$json = [];

while($row = $ress->fetch_assoc()){

     $json[] = ['id'=>$row['id'], 'text'=>$row['name_bg'], 'm_unit'=>$row['m_unit'], 'price'=>$row['mhm_price']];

}


echo json_encode($json);

It’s not working for me - it just redirects me to your login page (http://offers.balkanecommerce.com/index.php).

Just a side note - any reason why you’re not using PDO to to bind your query parameters in PHP? That looks like it could open you up to SQL injection.

Also, another side note, if you’re building a platform with full user-login capabilities, you might consider using a framework like UserFrosting rather than building it from scratch. I designed it specifically for applications like these and you’ll learn a lot about how PHP is used in the modern era :stuck_out_tongue:

please, try again …
this is example … write it only for test … and i have my own framework with all user actions :slight_smile:
all 3 url’s a public
http://offers.balkanecommerce.com/t.php
http://offers.balkanecommerce.com/_get_services.php
http://offers.balkanecommerce.com/_get_service.php?sid=4

T.

this is out of topic :slight_smile:
i use same default AdminLTE for my dashboard :slight_smile:
i use hybridauth for login with socials, have blocking for invalid logins and some other thing
your UserFrosting looks great

1 Like

Ok, I can access your endpoint now - thanks!

Can you recreate your Select2 use case with our JS Bin template?

Yes, AdminLTE is awesome :smile:

hi,

http://jsbin.com/wajijinilu/edit?html,js,console,output

test it :slight_smile:

http://jsbin.com/wajijinilu/edit?html,js,console,output

with price console log on change

Looks like your API is once again no longer accessible to me :confused:

yes , use the JS Bin template :slight_smile:


ups … some one delete some info … 5 min … will add it again … sorry

JS Bin template is updated …
public are:

http://offers.balkanecommerce.com/t_get_services.php
http://offers.balkanecommerce.com/t_get_service.php?sid=20

Sorry text is Bulgarian …
T.

So the data being returned by your endpoint is actually an array of objects. You need to dereference the first element of that array to get the specific object you’re trying to initialize with.

Either that, or modify your API endpoint to return just an object, rather than an array of objects :stuck_out_tongue:

ok, good point … i fixed.
now initial value is correct but can’t access data attribute price … even i change select to this option again … price is missing…

please, check again JS Bin template link

Additional data attributes are a little trickier and we haven’t found a good solution yet. See:

…and many others.

this not helping me … i read and told you for - 5036
so, there is not clear solution
i made some stupid php & javascript mix that work in may case … but this not make me happy
will check and read time to time for news on this case

T.

I have used trigger to select the data with custom attributes dynamically without using Option.

var data = { id: 1, text: 'Some text', price: 123};

$("#select2ElementId").select2("trigger", "select", {data: data});

Above code works for me but when I tested with 50 select2 elements, above method takes like 7 seconds to complete the selection.