Getting select2 to refresh data using ajax on dropdown - asp.net-mvc-5

I have the following JavaScript to populate dropdown list using select2 https://select2.github.io/
It works fine, and populates the list on the first load of the page.
From then on it does not refresh the list even when data is added because it only does the AJAX call once. Even if I reload the page, the dropdown list is not refreshed and the AJAX call is not triggered (unless I close and reopen the browser, then the AJAX call is fired)
Is there a way to undertake the ajax call each time the dropdown is opened. I tried the .on("select2-open") option but didn't have any luck.
Sorry JavaScript is not something I know much about.
$("#Location").select2({
placeholder: "Select a known location", // Placeholder text
allowClear: true, //Allows deselection of chosen address
ajax: {
url: '/AlertInterface/NewAlertLocations', // Where we want the ajax to call
dataType: 'json', // The datatype we are expecting to be returned
type: "GET", //Just a get method
//Data: allows us to pass a parameter to the controller
data: function (query) {
console.log(query)
return { search: query.term }
},
//processes the results from the JSON method and gives us the select list
processResults: function (data) {
console.log(data)
return {
results: JSON.parse(data)
};
}
}
});
EDIT:
I did try to use
$("#Location").on("select2:open", function () { $("#Location").select2(); })
but that didn't help. :-(

You have a syntax error in your code.
Please check the below code,
$("#Location").select2({
placeholder: "Select a known location", // Placeholder text
allowClear: true, //Allows deselection of chosen address
ajax: {
url: '/AlertInterface/NewAlertLocations', // Where we want the ajax to call
dataType: 'json', // The datatype we are expecting to be returned
type: "GET", //Just a get method
//Data: allows us to pass a parameter to the controller
data: function (query) {
console.log(query)
return { search: query.term }
},
//processes the results from the JSON method and gives us the select list
processResults: function (data) {
console.log(data)
return {
results: JSON.parse(data)
};
}
}
});

Related

How to get Tabulator to populate a headerFilter ONLY when it is clicked

I'm using Tabulator with ajax to pull paginated data to the table. I'd like to use headerFilters with valuesURL but the AJAX request is a POST not a GET and valuesURL only works with GET. He alternative is to use values, but that seems to want to pull the values each time the data is refreshed. I need the headerFilter options to be refreshed ONLY when it the input box is clicked. Psuedo-process below...
Load all data
user clicks one headerFilter "City"
ajax called via POST to get list of relevant values for "City"
headerFilter is populated with list, which is then presented to the user via the drop down
Is this possible?
I've tried using a function in headerFilterParams to get the values but each headerFilter is refreshed when the data is refreshed as opposed to just the one that was clicked.
You can use the headerFilter in combination with a custom header filter component that makes the AJAX call to get the values when the header filter is clicked.
Example:
var cityFilter = function(headerValue, rowValue, rowData, filterParams){
// code to filter data based on selected city
};
// Custom header filter component
var customCityFilter = function(header) {
var self = this;
self.element = document.createElement("input");
self.element.setAttribute("type", "text");
self.element.setAttribute("placeholder", "Type to filter");
// Add click event to make the AJAX call when the input box is clicked
self.element.addEventListener("click", function() {
// Make the AJAX call to get the list of relevant values for "City"
// Replace with your own AJAX code
// Example using jQuery
$.ajax({
type: "POST",
url: "your_url",
data: {},
success: function(data) {
// Populate the headerFilter with the list of values
header.setFilterValues(data);
}
});
});
// Return the custom filter component
return self.element;
};
// Initialize the table with the custom header filter
var table = new Tabulator("#example-table", {
columns:[
{title:"City", field:"city", headerFilter:"custom", headerFilterParams:{component:customCityFilter}, headerFilterFunc:cityFilter},
// other columns
],
});

Why steam web api returns undefined json value node js

Hello these code does request to Steam Web API
const request = require("request");
request({
url: "https://api.steampowered.com/IEconService/GetTradeOffers/v1/?key=MYAPIKEY&get_sent_offers=1&active_only=1&format=json",
json: true
}, (err, responser, body) => {
console.log(body.response['trade_offers_sent']);
});
And this is what it returns:
{
trade_offers_sent: [
{
tradeofferid: '3974708687',
accountid_other: 82613664,
message: 'test message',
expiration_time: 1587017229,
trade_offer_state: 9,
items_to_give: [Array],
is_our_offer: true,
time_created: 1585807629,
time_updated: 1585807629,
from_real_time_trade: false,
escrow_end_date: 0,
confirmation_method: 2
}
]
}
But when i'm trying to get value of accountid_other this way:
console.log(body.response['trade_offers_sent'].accountid_other);
it returns undefined
The square brackets [ ... ] within trade_offers_sent indicate that it holds an array and not just a single item (it just happens to be a single item in the array). Thus to obtain you value you are interested in you need to specify the index of the item you want or use a loop to go through it. In this case you want the first item and you can use ['trade_offers_sent'][0] to obtain it.

Extjs Grid - Click next page button with search condition

I have a gridpanel and i create store in initComponet function like
,initComponent: function() {
var store = Ext.create('Ext.data.Store', {
model: 'MyObject',
autoLoad: false,
pageSize:22,
remoteSort:true,
proxy: {
type: 'ajax',
url: 'example.php',
reader: {
type: 'json',
totalProperty: 'total',
root: 'results'
}
}
});
this.store = store;
this.dockedItems = [{
xtype: 'pagingtoolbar',
store: this.store,
displayMsg: '{0} - {1} / {2}',
emptyMsg: 'empty',
dock: 'bottom',
displayInfo: true,
pageSize: 22
}];
this.callParent(arguments);
this.store.load({params:{start:0, limit:22}});
}
I make a form search with some value and when i press search button i will do below code
grid.store.load({
params:{
start:0,
limit:22,
signalSearch: 1,
search1: myValue1,
search2: myValue2,
}
});
In my php file will catch that to know that's search
if ( have $_REQUEST["signalSearch"]) {
// print json with condition search
}else {
// print json with all data
}
And results return with 2 page (it well). But when i press Next page button to see some results on page 2 But my store load fail (i think they call store.load({params:{start:0, limit:22}}); when i press next page button and in my php file that will run with else case).
That's not call
grid.store.load({
params:{
start:0,
limit:22,
search1: myValue1,
search2: myValue2,
}
});
My idea to make search is not good? How can i fix that thank
If you use params in the "load" function of the store, those are referred to the single request only so if you click next page of the toolbar you won't post the signalSearch param.
You should register a custom listener on the before load event and add your params:
initComponent: function(){
....
this.callParent(arguments);
this.store.addListener('beforeload', function(store, operation){
Ext.apply(operation.params, {
signalSearch: 1 // Or you could make conditions if apply this search param
});
return true;
}, this);
}

jQuery Autocomplete - Show Data Based on Selection

I have a standard jQuery autocomplete setup similar to the below:
$("input#autocomplete").autocomplete({
source: source,
minLength: 5 ,
select: function( event, ui ) {
alert(ui.item.value);
}
});
What I would like is, when the value is chosen, a data-table within the page appears and get populated with data from a database using the value as a search parameter.
So for instance if I select "RED", the table would then show and display data from a query such as SELECT * FROM TABLE WHERE COLUMN='RED'
The query is simplified but can anyone please point me in the right direction?
For this purpose you should request a kind of search page which will act as JSON endpoint for e.g.
$("input#autocomplete").autocomplete({
source: source,
minLength: 5 ,
select: function( event, ui ) {
var _value = ui.item.value;
$.post('services/populate_table.php', // endpoint URL
{ someParameterToTransmit: _value }, // some data to transmit
function(data) { // on complete handler
$('.result').html(data); // populate retrieved data in any form you need
} // on complete function
); // post
} // on select (autocomplete)
}); // autocomplete
Data from endpoint also can be retrieved as JSON.
You can read documentation for more information about request method.
If I understand you correctly, you're looking for $.post.
For example, your jQuery would be:
$("input#autocomplete").autocomplete({
source: source,
minLength: 5 ,
select: function( event, ui ) {
$.post("autocomplete.php", { option: ui.item.value }, function(data){
$("table").html( data[0] );
// sets the content of a table element to the first matched row
});
}
});
And in autocomplete.php, you would have something like this:
// DB connect
// use $_POST['option'] here for the selected option
$sth = mysql_query("SELECT ...");
$r = mysql_fetch_assoc($sth);
print $r;
What we do here is request the page autocomplete.php and POST the data, which in this case is the selected value. autocomplete.php grabs that POSTed value and searches the database (you can customize that query to fit your needs). The page then prints an array of the matched rows, which is the data received by the jQuery, and can be traversed as a Javascript array.

JqueryUI Autocomplete : only one character is displayed per list item

I'm using jquery-1.4.2.min and jquery-ui-1.8.6.custom to get the autocomplete data on a jsp page, here is the code snippet:
$(document).ready(function() { $("input#airportfrom").autocomplete({minLength: 3,
source: function(request, response) { $.ajax({
url: "MLocationLookupSearchPopUpAuto.action?LANGUAGE=${param.LANGUAGE}&SITE=${param.SITE}&RESULT_FILTER=3",
dataType:"text/html",
data: { MATCH : $("#airportfrom").val() },
success: function(data) { response(data); } }); } }); });
The result returned is correct as I have used an alert(data); inside the success function and it gave correct result, but in the list, it is showing one character or one alphabet per line, hence if I want to get LONDON, it is displayed as:
l
o
n
d
o
n
Any idea why this happening ? Whether we have to give data as json only because here I'm getting the data from a jsp.
Try to split the response data into lines using "\n"
$("#tags").autocomplete({
source: function(request,response) {
$.ajax({
dataType: "text",
url: 'yourscript.php?extraParam=foo',
data: { term: request.term },
success: function(data) {
var lines = data.split("\n");
response(lines);
}
})}
});
I had the same problem and it was down to serializing the object twice (by mistake) on the server side. The JSON data returned to the client was being de-serialized to a string rather than an array.

Resources