Remove Select2 parameters

Asked

Viewed 538 times

3

I have a problem using the Select2 plugin, I need to make an AJAX request, but I need the final URL to be the following:

api/user/findbyname/name

And the way it’s coming is this:

api/user/findbyname/?q=name&_=1395243972884

My code is like this

ajax: {
    url: "/api/user/findbyname/",
    params: {
        contentType: 'application/json; charset=utf-8'
    },
    dataType: 'json',
    data: function (term) {
        return {
            q: term                    
        };
    },
    results: function (data) {
        console.log(data);
    }
}
  • You’re doing it with a form?

  • It’s not an input text on the screen itself, and it’s not inside a form.

2 answers

2


The Select2 uses the ajax jQuery under the covers. When you use data it puts the result in query string [in a GET; in the POST he would go to the requisition body], such as the original method. If you want this result in the URL itself (i.e. no path), the "natural" solution would put you in the field url:

ajax: {
    url: "/api/user/findbyname/" + term,

And leave the data empty. However, I believe that for this you will not be able to use the ajax this way, and yes to make the request explicitly, using query. I had a quick read in the documentation and in this example, but I didn’t understand 100% how it works, but anyway I suggest starting there. My (untested) solution attempt would be:

query: function(query) {
    $.ajax({
        url: "/api/user/findbyname/" + query.term,
        contentType: 'application/json; charset=utf-8'
        dataType: 'json'
    }).done(function(data) {
        console.log(data);
    });
}
  • 1

    Using this property queryworked, then I had to do in Success the options.callback to be able to work with the results in the other plugin properties.

  • @fbadaro You’re right, this detail went unnoticed. The linked example uses query.callback - I don’t know if it’s the same...

  • Yes, it is that in my case I have assembled an options object, with the properties of my query. Tks

-1

This plugin comes by default with get method which causes this in the Url, switching to post method I imagine the problem is solved, but it’s just a guess.

 ajax: {
 type: 'POST',
 url: "/api/user/findbyname/",
 params: {
     contentType: 'application/json; charset=utf-8'
 },
 dataType: 'json',
 data: function (term) {
    return {
        q: term                    
    };
 },
 results: function (data) {
     console.log(data);
 }
 }
  • 1

    Change the method of GET for POST will in fact cause the parameters to exit the query string and go into the body of the request. But that’s not what OP wants: it needs the search term to be on path of the URL.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.