How do I fire a new ajax on select2 new /remove tag event?
Asked Answered
M

2

7

I use the following snippet to add a new select2 tag remotely with ajax and I want to register or remove some records of my many to many table on new tag / remove tag event

The Table looks like

---------------------------------
+--voucher_id--+|+--product_id--+
---------------------------------
+     123       |   566         +
---------------------------------
+     156       |   566         +
---------------------------------
+     123       |   426         +
---------------------------------
+     156       |   516         +
---------------------------------

My Javascript

$(".e6").select2({
    tags: true,
    placeholder: 'placeholder',
    minimumInputLength: 1,

    ajax: {
        url: 'searchProducts',
        dataType: 'json',
        data: function(term) {
            return {q: term};
        },
        results: function(data) {
            return {results: data};
        }
    },
    createSearchChoice: function(term, data) {
        if ($(data).filter(function() {
            return this.computername.localeCompare(term) === 0;
        }).length === 0) {
            return {id: term, name: term};
        }
    },
    formatResult: function(item, page) {
        return item.computername;
    },
    formatSelection: function(item, page) {
        return item.computername;
    }
});

In the returned json I have a product ID as well and I'm searching a way to fire a new ajax on select2 event but I can't figure out where should be done to save or remove data from my table.

Making some researches I've been able to build a function which would update records on the table above and which is working good sofar

$('.e6').on("change", function(e){                           
    console.log(ids);
    console.log(gs);
    $.ajax({
        type: "POST",
        url: '/admin/?controller=vouchers&action=updateRelatedProducts',
        data: {ids: ids, gs:gs},
        error: function () {
            alert("error");
        }
    });                   
});

But I have problems to populate my input field with initial existing tags

Melina answered 25/4, 2014 at 13:54 Comment(4)
Abstract out the ajax function into it own function, then apply this to any select2 functions you have to do.Anthracosis
what is not clear to me how to catch remove or add event in case of select2Melina
I just looked at Select2 it is freaking awesome. Going to have to start using it!Anthracosis
@No1_Melman It's actually very similar to julesjanssen.github.io/chosenNovitiate
P
5

Not tested but should work :

$('.e6').on("change", function(e){
    if (e.removed) {
        $.ajax({
            type: "POST",
            url: '/admin/?controller=vouchers&action=updateRelatedProducts',
            data: {id: e.removed.id, action: remove},    //Or you can e.removed.text
            error: function () {
                alert("error");
            }
        });
    }
    if (e.added) {
        $.ajax({
            type: "POST",
            url: '/admin/?controller=vouchers&action=updateRelatedProducts',
            data: {id: e.added.id, action: add},    //Or you can e.added.text
            error: function () {
                alert("error");
            }
        });
    }

    //OR you can play with val data instead
    if (e.val) {
        $.ajax({
            type: "POST",
            url: '/admin/?controller=vouchers&action=updateRelatedProducts',
            data: {val: JSON.stringify(e.val)},    //Will send all the selected values
            error: function () {
                alert("error");
            }
        });
    }
}
Premonish answered 3/5, 2014 at 16:43 Comment(1)
i have raised a question could you please have a look. #35216802Weingarten
L
1

Is there a fiddle where you can post a version of this problem.

Based on what I understood, would the following pattern suffice?

  function dynamicSelect2(id) {
      $.ajax({
          url: 'data-url',
          data: 'parameters',
          dataType: 'json'
      }).done(function () {
          //Create the Select2 with necessary data on the element "id" passed.
      }).always(function () {
          //Attach other events..
      });
  }

It is possible to create the entire select2 box dynamically and attach events on it this way. If you do that within a closure, you'll have access to variables that you defined prior to your ajax calls.

Linson answered 29/4, 2014 at 4:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.