I am using the select2 multiple for search box. I am passing these data with JSON and saving it using ajax(JSON stringify).
I just need 2 variables passed, which is the ID(primary key, customized) and the Selection itself.
I managed to save it to the database when only 1 value is selected.
When selecting multiple values, in my console.log, I see something like this
{21,23,25,26}
which is the selection itself.
How do I get it show like this,
Object0->{id:1, selection:21}
Object1->{id:2, selection:23}
Object2->{id:3, selection:25}
Object3->{id:4, selection:26}
Below is the code I am using,
var nature = {
ubtBusinessInfo: businessId, // the primary key
ubtBusinessListing: nature.val() // here is selection
};
Here is the initialization of the select2,
nature
.select2({
allowClear: true,
placeholder: "Filter as you type",
minimumInputLength: 3,
multiple: true,
ajax: {
url: 'home/umkei/info/nature',
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return { q: term };
},
results: function (data, page) {
return { results: data };
},
cache: true
}
})
nature is defined from(I tried both as below)
var nature = $('[name=nature_business]') OR var nature = $(#nature_business);
I know it must have something to do with the nature.val() usage. Must have been something like array but I dont know how to differentiate/split those data to be key->value pairs.
Thank you.
I got this about last week and thought I'd share my solution.
var nature=[];
var splitnature = nature_business.val().trim().split(',');
var n;
for(n=0; n<=splitnature.length-1;n++){
nature.push({
ubtBusinessListing: splitnature[n],
ubtBusinessInfo: businessId
});
}
Related
I have an endpoint which I call with Axios and the response looks like (for example):
items: [
{
url: "https://api.example1...",
expirationDate: "2019-11-15T00:00:00+01:00"
},
{
url: "https://api.example2...",
expirationDate: "2019-12-20T00:00:00+01:00"
},
{
url: "https://api.example3...",
expirationDate: "2020-01-17T00:00:00+01:00"
},
...and so on.
If I go to one of the url:s in the browser the structure of the JSON is:
fooBar: {
url: "https://api.foo...",
id: "123",
type: "INDEX",
source: "Foobar",
quotes: {
url: "https://api.bar..."
}
},
I need to get the quotes of the two first url:s in items:[] dynamically because they will disappear when the 'expirationDate' is older than today's date.
How can this be achieved? Thanks in advance!
If I understand the requirements correctly you need to:
get the list of items
get item details for first two items (to extract links to quotes)
get quotes for first two items
You can use promise chaining to execute these operations maintaining the order:
const getQuotes = (item) => axios.get(item.url)
.then(resp => axios.get(resp.data.fooBar.quotes.url));
axios.get('/items') // here should be the url that you use to get items array
.then(resp => resp.data.slice(0, 2).map(getQuotes))
.then(quotes => Promise.all(quotes))
.then(quotes => {
console.log(quotes);
});
Please find my proposal below. I gave two examples. You can get the whole quotes object, or just the URL inside the quotes object.
This is just a console log, but you can easily ie. append this data to a div in the html or pass this URL to some other function.
$(function() {
const address = 'https://api.example1...';
function loadQuotes() {
$.ajax({
url: address,
dataType: 'json',
}).done(function(response) {
response.forEach(el => {
console.log(`el.quotes`);
// or if you want to be more specific console.log(`el.quotes.url`);
});
});
}
loadQuotes();
});
If these are nested objects, just append fooBar.
For example change the .done part to:
.done(function(response) {
let qqq = response.quotes
quotes.forEach(el => {
console.log(`el.quotes`);
// or if you want to be more specific console.log(`el.quotes.url`);
});
I know this is a popular topic and I've tried all of the solutions I could find already out there to no avail. I've used all the solutions included for this questions: Pass a List from javascript to controller. I've simplified my test to ridiculously simple. I get into the controller but my controller input param is {int[0]}. I confirmed my array data looks good in the JavaScript and ajax call.
Can anyone please tell me what I am missing?
JavaScript Code
var selectedIds = [];
selectedIds.push(565);
selectedIds.push(573);
selectedIds.push(571);
// selectedIds = [565, 573, 571]
$.ajax({
type: "POST",
traditional: true,
dataType: "json",
data: { "ids": JSON.stringify(selectedIds) },
//data: { "ids": selectedIds},
//data: { ids: selectedIds},
url: "api/services/getbuildingsbyid",
success: function (result) {
return result;
}
});
Controller Code
[HttpPost]
public bool GetBuildingsById(int[] ids)
{
var lookAtIds = ids; // {int[0]}
return true;
}
By using JSON.stringify(selectedIds) you are turning an array of int into a string representation of said array.
The AJAX POST ends up like so:
{ "ids": "[565, 573, 571]" }
instead of
{ "ids": [565, 573, 571] }
If instead you just use the variable for the data, that should resolve the issue:
data: { "ids": selectedIds },
Edit-
Working backwards, by setting a variable to the data we can see the following:
var data = {"ids": JSON.stringify(selectedIds)}
typeof(data["ids"]) // string
data["ids"][0] // '['
data = {"ids": selectedIds}
typeof(data["ids"]) // object
data["ids"][0] // 565
I use:
public ActionResult GetBuildingsById(String selectedIds)
{
// this line convert the json to a list of your type, exactly what you want.
IList<int> Ids = new JavaScriptSerializer().Deserialize<IList<int>>(selectedIds);
return Content(ids[0].ToString());
}
This will take you selectedIds = [565, 573, 571]
and create the list of your type List
I am in desperate need of some help from JavaScript experts. I have spent the last 7 hours trying hundreds of combinations of code to get a basic Tag selection input field to work with the library x-editable and select2.
I am building a Project Management app which is going to have Project Task data shown in a popup Modal Div. In the Task Modal, all Task fields will be editable with in-line edit-in-place capability using AJAX.
I am using:
the jQuery edit in place library called X-Editable - http://vitalets.github.io/x-editable/
The drop down selection jQuery library Select2 - https://select2.github.io/
The jQuery MockAjax library to allow simulating AJAX request responses. https://github.com/jakerella/jquery-mockjax
I have setup a basic JSFiddle demo to experiment with just for this StackOverflow question. I don't have the thousands of lines of code from my actual application , however I do have majority of the 3rd part libraries that are being used included into the page. THe reason is to make sure that none of them are interfering with the results.
JSFiddle Demo: http://jsfiddle.net/jasondavis/Lusbqfhs/
The Goal:
Setup X-editable and Select2 on a Field to allow users to select and enter in Tags for a Project Task.
Fetch available Tag records from a backend server which will return a JSON response with Tag ID number and Tag Name and use this data to populate the Selection2 input field to allow a user to select multiple Tags.
Allow user to also type in a NEW tag and it will post and save the new Tags to the backend as well!
When tags are selected and the save button is clicked, it will save the list of selected Tags bu ID number back to a database.
Problems:
Now I have tried hundreds of variations of options and code combinations from my research in the past 7 hours. I cannot seem to get this basic functionality to work and majority of the examples I have found do not seem to work correctly anymore!
On this demo page for the library x-editable http://vitalets.github.io/x-editable/demo-plain.html?c=inline near the bottom of the examples in the table where it says Select2 (tags mode) that functionality is what I need! I just need it to load the available tags from an AJAX request and all the docs claim it can do this with no problem at all!
This is the Documentation section from X-Editable for Select2 fields - http://vitalets.github.io/x-editable/docs.html#select2
It also links to the Select2 documentation and claims that all the Options in Select2 can be set and used as well located here - https://select2.github.io/options.html
I use MockAjax library to simulate an AJAX response in pages like JSFiddle for testing. In my JSFiddle demo here http://jsfiddle.net/jasondavis/Lusbqfhs/ I have 2 MockAjax responses set up....
$.mockjax({
url: '/getTaskTags',
responseTime: 400,
response: function(settings) {
this.responseText = [
{id: 1, text: 'user1'},
{id: 2, text: 'user2'},
{id: 3, text: 'user3'},
{id: 4, text: 'user4'},
{id: 5, text: 'user5'},
{id: 6, text: 'user6'}
];
}
});
$.mockjax({
url: '/getTaskTagById',
responseTime: 400,
response: function(settings) {
this.responseText = [
{id: 1, text: 'user1'},
{id: 2, text: 'user2'},
{id: 3, text: 'user3'},
{id: 4, text: 'user4'},
{id: 5, text: 'user5'},
{id: 6, text: 'user6'}
];
}
});
They both are supposed to return a Mock JSON string for my Selection list to be populated with.
Here is my code for the demo...
$(function(){
//remote source (advanced)
$('#task-tags').editable({
mode: 'inline',
select2: {
width: '192px',
placeholder: 'Select Country',
allowClear: true,
//minimumInputLength: 1,
id: function (item) {
return item.CountryId;
},
// Get list of Tags from AJAX request
ajax: {
url: '/getTaskTags',
type: 'post',
dataType: 'json',
data: function (term, page) {
return { query: term };
},
results: function (data, page) {
return { results: data };
}
},
formatResult: function (item) {
return item.TagName;
},
formatSelection: function (item) {
return item.TagName;
},
initSelection: function (element, callback) {
return $.get('/getTaskTagById', {
query: element.val()
}, function (data) {
callback(data);
});
}
}
});
});
Now in the demo when you click the field to select Tags, it just keeps "loading" and never gets a result. Looking at the Console, it seems my MockAjax request is not working, however the 2nd one is working so I am not sure what is wrong with my AJAX request?
I could really use some help if someone can help to get this to work I would be very greatful, I have spent my whole night without sleep and am not even any closer to a working solution! Please help me!
Thank you
X-Editable uses Select2 3.5.2 which doesn't use jQuery.ajax() directly. It has its own ajax function and calls jQuery.ajax() like that:
transport = options.transport || $.fn.select2.ajaxDefaults.transport
...
handler = transport.call(self, params);
That's why $.mockjax({url: '/getTaskTags'... does not work.
To get it work you need to create your own transport function, something like that:
var transport = function (queryParams) {
return $.ajax(queryParams);
};
and set the transport option:
ajax: {
url: '/getTaskTags',
=> transport: transport,
type: 'post',
dataType: 'json',
data: function (term, page) {
return { query: term };
},
results: function (data, page) {
return { results: data };
}
},
I am using Select2.js(latest version) to implement tokenized tagging in my application. It is working fine except, I am not able to select any item from the suggestions.
I saw few answers in which it was mentioned that we need to include "id" in our configuration. it doesn't seems to be working for me.
My code is :
$("#interest").select2({ ajax: {
url: "get-interests",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
placeholder:{
id: "-1",
text: "Add your interest.."
} ,
tags: true,
tokenSeparators: [',', ' '],
id: function(data) {
alert(JSON.stringify(data));
return data.interestId;
},
templateResult: function(post) {
// return html markup for individual result item
var markup ="";
if(String(post.description) !== 'undefined') {
markup = '<p><b>' + post.text + '</b> : ' + post.description + '</p>';
} else {
markup = '<p><b>' + post.text + '</b></p>';
}
return markup;
},
formatSelection: function(post) {
// This shows up in the select box
return post.text;
}
What I am doing wrong in above configuration?
Contrary to the comment you placed in your code, with Select2 4.0 you do need to add code to the processResults function to convert the returned JSON data to objects with an id property. Normally, the objects should also have a text property, but they don't have to if you supply the templateResult and templateSelection functions.
I saw few answers in which it was mentioned that we need to include
"id" in our configuration. it doesn't seems to be working for me.
Those answers were correct for previous versions of Select2, but with with Select2 v4.0, the id function is no longer supported. See the "The id and text properties are strictly enforced" section on the the "4.0 Anouncement" page:
You can also remove the formatSelection function. With Select2 4.0 it should now be named templateSelection. That means it is not getting called for you, but you probably didn't notice that because your formatSelection function is just doing what is done by default anyway.
The processResults function should return an object with a results property, which is set to an array of objects. Those objects all need to have an id property (but they can have other properties too).
You don't show what your returned data looks like, but judging from your id and templateResult functions, it appears to be an array of objects with the following properties: interestId, text and description. In that case your processResults function could look something like this:
// This builds a new array of new objects.
processResults: function(data, page) {
return {
results: $.map(data, function(post) {
return {
id: post.interestId,
text: post.text,
description: post.description
};
})
};
},
Or this:
// This just adds an `id` property to the objects in the existing array.
processResults: function(data, page) {
$.each(data, function(i, post) {
post.id = post.interestId;
});
return { results: data };
},
I am working on an ASP.NET MVC 4 app. This app has a controller with an action that looks like the following:
public class MyController : System.Web.Http.ApiController
{
[ResponseType(typeof(IEnumerable<MyItem>))]
public IHttpActionResult Get(string id, string filter)
{
IEnumerable<MyItem> results = MyItem.GetAll();
List<MyItem> temp = results.ToList<MyItem>();
var filtered = temp.Where(r => r.Name.Contains(filter);
return Ok(filtered);
}
}
I am calling this action using the following JavaScript, which relies on the Select2 library:
$('#mySelect').select2({
placeholder: 'Search here',
minimumInputLength: 2,
ajax: {
url: '/api/my',
dataType: 'json',
quietMillis: 150,
data: function (term, page) {
return {
id: '123',
filter: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
This code successfully reaches the controller action. However, when I look at id and filter in the watch window, I see the following errors:
The name 'id' does not exist in the current context
The name 'filter' does not exist in the current context
What am I doing wrong? How do I call the MVC action from my JavaScript?
Thanks!
You're not passing actual data as the parameters, you're passing a function:
data: function (term, page) {
return {
id: '123',
filter: term
};
}
Unless something invokes that function, the result will never be evaluated. Generally one would just pass data by itself:
data: {
id: '123',
filter: term
}
If, however, in your code there's a particular reason (not shown in the example) to use a function, you'll want to evaluate that function in order for the resulting value to be set as the data:
data: (function (term, page) {
return {
id: '123',
filter: term
};
})()
However, these errors also imply a second problem, probably related to however you're trying to debug this:
The name 'id' does not exist in the current context
The name 'filter' does not exist in the current context
Even if no values were being passed, id and filter still exist in the scope of the action method. They may be null or empty strings, but the variables exist. It's not clear where you're seeing that error, but it's definitely not in the scope of the action method.