JavaScript: search user input in number of arrays - javascript

I am working with D3js library. On the web page, there is a search box which user can input their parameter. I receive arrays of data via Ajax post to my database. Following is the code:
..........
var aa;
var bb;
$(function(){
$.ajax({
type: "POST",
url: "http://localhost:7474/db/data/transaction/commit",
accepts: {json: "application/json"},
dataType: "json",
contentType: "application/json",
data: JSON.stringify(query), //query is somewhere above the code
//pass a callback to success to do something with the data
success: function (data) {
aa = data.results[0].data;
aa.forEach(function (entry) {
passVar(entry.row[0].name)
});}}
);
});
function passVar(smth){
bb =[smth];
console.log (bb);
//Should search the user input..........
}
//if the user input matches, filter function should run.........
function filterData() {
var value = d3.select("#constraint")[0][0].value;
inputValue = value;
............
}
As the result of console.log(bb)I receive the following on console:
["Direct Digital Control System"]
["Fire Protection"]
["HVAC Cooling- Waterside"]
["HVAC Heating- Waterside"]
["HVAC System"]
["HVAC-01"]
["HVAC-02"]
What I want to do:
If the user input match with one of the results in var bb, then program should run function filterdata() {....for querying. If not, don't do anything.
How should I write the code to make the search and run the other function? Thanks for the any help/suggestion.

You can loop through the array and find whether the user input is equals to the current index value of the array. if equals you can call your function and break the loop since no need to loop further more.
for(int i=0; i<bb.length; i++){
if(bb[i] == userInput){
filterdata();
break;
}
}

Related

Incorrect operation of the jquery-ui autocomplete

Immediately after reloading the page when you enter a single character in the input, nothing happens. when you enter the following characters begins to complement.
Get data
`function getData(data, callback) {
$.ajax({
url: "myUrl" + encodeURIComponent(data),
method: "GET",
dataType: "JSON",
success: callback
})
}`
Callback function
`function autocompleteInput () {
var dataInput = $("#myInput").val();
function success(data) {
var dataArr = [];
for (var i = 0; i < data.data.length; i++) {
dataArr.push(data.data[i].name);
}
$("#myInput").autocomplete({
source: brokersNameArr,
delay: 500,
minLength: 1
})
getData(dataInput, success);
}`
Use in html
$("#myInput").keyup($.throttle(200, autocompleteInput));
Would suggest the following:
var dataArr = [];
$("#myInput").autocomplete({
source: function(req, resp){
$.getJSON("myurl?" + req.term, function(results){
$.each(results.data, function(k, r){
dataArr.push(r.name);
});
resp(results);
});
},
delay: 500,
minLength: 1
});
You might also want to review: http://jqueryui.com/autocomplete/#multiple-remote
Using a Function for source will give you the ability to manage how the data is sent and received.
Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete, including JSONP. The callback gets two arguments:
A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
Hope this helps.

How to find the length of Success Data in Jquery Ajax?

I am retrieving list from ajax, when it become success, I wants to add those list values to DropDownList Items, So I want to iterate the data until last value and then add it to DropDownList
Here is my code What i tried
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "GPCreateCheque.aspx/getOpenRequestNo",
dataType: "json",
success: function (data) {
alert(data.length);
for (var i = 0; i<data.length; i++) {
$(".tbDDLReqNo").append(new Option(data.d[i], data.d[i]));
}
},
error: function (result) {
alert("Error");
}
})
In alert box it is showing undefined
UPDATE
I return the list<string> from [webmethod]
use data.d.length
alert(data.d.length);
for (var i = 0; i<data.d.length; i++) {
$(".tbDDLReqNo").append(new Option(data.d[i], data.d[i]));
}
You need to do data = JSON.parse(data); before treating your data like an array. It's just a string up to that point.
Update: if your data is not the array itself, but instead an object that contains an array named d, you need to work with that. It depends on your data structure.
Check the response from network tab in Chrome Developer Console or similar tool. May be response code is 200 but response data is missing.
On the other hand you want to itarete data in for loop but you try to append data.d[i]. If you want to append data.d[i] you have to itarete data.d in for loop.

Autocomplete search taking too long to retrieve data from server

I have an AJAX autocomplete search in user control page, which gets called on document.ready. In that we makes an AJAX call to web service which takes the data (which is approx. 90,000) from the database, insert data into cache, returns the data to JavaScript and added to the array.
At first it takes the data from the database and after inserting the data into cache, every time it takes the data from cache. When we type something on textbox it matches the text of textbox with array and displays the list. To get 90,000 items from a stored procedure, it takes 2 sec in local server.
But on live server it takes approx 40 secs to take data from a stored procedure. Also for taking data from cache it takes the same time. How can I reduce the time and increase the performance?
AJAX call:
var locationSearchListData = [];
var termTemplate = "<span class='ui-autocomplete-term'>%s</span>";
var postData = '{cultureId : "DE"}';
// Ajax call to run webservice's methods.
$.ajax({
url: "/asmx/SearchLocations.asmx/GetAutoCompleteSearchLocations",
type: "POST",
data: postData,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (responseData) {
if (responseData != undefined && responseData != null && responseData.d.length > 0) {
for (i = 0; i < responseData.d.length; i++) {
// Add resopnse data in location search lis, this list is used as a source for autocomplete textbox.
locationSearchListData.push({
label: responseData.d[i].locationData,
latitude: responseData.d[i].latitude,
longitude: responseData.d[i].longitude
});
}
}
Web-service:
[ScriptMethod]
[WebMethod(Description = "Provides instant search suggestions")]
public List<GeoLocationObject> GetAutoCompleteSearchLocations(string cultureId)
{
SqlDatabase database = new SqlDatabase(WebConfigurationManager.ConnectionStrings["MasterDB"].ConnectionString);
string databaseName = WebConfigurationManager.AppSettings["databaseName"];
// Key to identify location search data in cache
string cacheKey = "auto_complete_result";
// List to store locations
List<GeoLocationObject> lstGeolocationObject = new List<GeoLocationObject>();
// If location data is present in cache then return data from cache.
if (Context.Cache[cacheKey] is List<GeoLocationObject>)
{
return Context.Cache[cacheKey] as List<GeoLocationObject>;
}
else // If data is not present in cache, get data from db and add into cache.
{
// Call method GetAutoCompleteSearchLocations of LocationManager to get list of geo location object.
lstGeolocationObject = LocationManager.GetAutoCompleteSearchLocations(database, cultureId);
// Checking if lstGeolocationObject is not null
// If its not null then adding the lstGeolocationObject in the cache
if (lstGeolocationObject.Count > 0)
{
// Add locationdata in cache.
// Removed sqlcache dependency.
Context.Cache.Insert(cacheKey,
lstGeolocationObject,
null,
Cache.NoAbsoluteExpiration,
Cache.NoSlidingExpiration,
CacheItemPriority.NotRemovable,
null);
}
// Return geolocation data list
return lstGeolocationObject;
}
} // GetAutoCompleteSearchLocations
The main intention of autocomplete facility is to narrow down the search and bring to front only the nearly matching records to ease the user to select the exact record he wants. Try adding a debounceTime() if possible.
Other options are to fine tune the sql query, implementing the server side paging and checking the page render time in browser.
Sorry for my late reply.
Thanks all for helping me to find out the solution.
We have solved the issue by doing some changes in ajax call. We send the search text as:
// set auto complete textbox
$("#<%= txtOrtOderPlz.ClientID%>").autocomplete({
// Set required minimum length to display autocomplete list.
minLength: 3,
// Set source for textbox, this source is used in autocomplete search.
source: function (request, response) {
// Ajax call to run webservice's methods.
$.ajax({
url: "/asmx/SearchLocations.asmx/GetAutoCompleteSearchLocations",
type: "POST",
data: '{ searchText :\'' + request.term + '\' }',
dataType: "json",
contentType: "application/json; charset=utf-8",
Success: function (responseData) {
response(responseData.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
},
Every time we search anything, it takes the search text and call web services, send the search text to SP, get the data from SP and show in autocomplete search.

javascript, array of string as JSON

I'm having problems with passing two arrays of strings as arguments in JSON format to invoke ASMX Web Service method via jQuery's "POST".
My Web Method is:
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<string> CreateCollection(string[] names, string[] lastnames)
{
this.collection = new List<string>();
for (int i = 0; i < names.Length; i++)
{
this.collection.Add(names[i] + " " + lastnames[i]);
}
return this.collection;
}
Now, the js:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: dataS,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
GetJSONData() is my helper method creating two arrays from column in a table. Here's the code:
function GetJSONData() {
//take names
var firstnames = $('#data_table td:nth-child(1)').map(function () {
return $(this).text();
}).get(); //["One","Two","Three"]
//take surnames
var surnames = $('#data_table td:nth-child(2)').map(function () {
return $(this).text();
}).get(); //["Surname1","Surname2","Surname3"]
//create JSON data
var dataToSend = {
names: JSON.stringify(firstnames),
lastnames: JSON.stringify(surnames)
};
return dataToSend;
}
Now, when I try to execude the code by clicking button that invokes CreateArray() I get the error:
ExceptionType: "System.ArgumentException" Message: "Incorrect first
JSON element: names."
I don't know, why is it incorrect? I've ready many posts about it and I don't know why it doesn't work, what's wrong with that dataS?
EDIT:
Here's dataToSend from debugger for
var dataToSend = {
names: firstnames,
lastnames: surnames,
};
as it's been suggested for me to do.
EDIT2:
There's something with those "" and '' as #Vijay Dev mentioned, because when I've tried to pass data as data: "{names:['Jan','Arek'],lastnames:['Karol','Basia']}", it worked.
So, stringify() is not the best choice here, is there any other method that could help me to do it fast?
Try sending like this:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: {names: dataS.firstnames,lastnames: dataS.surnames} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
This should work..
I think since you are already JSON.stringifying values for dataToSend property, jQuery might be trying to sending it as serialize data. Trying removing JSON.stringify from here:
//create JSON data
var dataToSend = {
names : firstnames,
lastnames : surnames
};
jQuery will stringify the data when this is set dataType: "json".
Good luck, have fun!
Altough, none of the answer was correct, it led me to find the correct way to do this. To make it work, I've made the following change:
//create JSON data
var dataToSend = JSON.stringify({ "names": firstnames, "lastnames": surnames });
So this is the idea proposed by #Oluwafemi, yet he suggested making Users class. Unfortunately, after that, the app wouldn't work in a way it was presented. So I guess if I wanted to pass a custom object I would need to pass it in a different way.
EDIT:
I haven't tried it yet, but I think that if I wanted to pass a custom object like this suggested by #Oluwafemi, I would need to write in a script:
var user1 = {
name: "One",
lastname:"OneOne"
}
and later pass the data as:
data = JSON.stringify({ user: user1 });
and for an array of custom object, by analogy:
data = JSON.stringify({ user: [user1, user2] });
I'll check that one later when I will have an opportunity to.

using json in mvc 5 controller method

var checkboxes = $("input[type='checkbox']");
$(function ()
{
function getValueUsingClass() {
/* declare an checkbox array */
var chkArray = [];
/* look for all checkboes that have a class 'chk' attached to it and check if it was checked */
$(".chk:checked").each(function () {
chkArray.push($(this).val());
});
/* we join the array separated by the comma */
var selected = chkArray.join(",") + ",";
/* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */
if (selected.length > 1)
{
$.ajax({
url: "/StateController/MyResult",
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
type: "POST",
data: {"randstuff": chkArray},
success: function () {
// do things upon success
},
error: function () {
alert("Error!");
}
});
}
else
{
alert("Please check at least one of the checkbox");
}
}
$("#Charter").click(function () {
getValueUsingClass();
});
});
My Javascript code.
This gets me the Id of the checked boxes, i want to send this data to my controller, so that i can use it to select those particular values from my database. This is my first time using Jquery and Ajax, i have managed to get this far but i'm still quite lost.
public JsonResult MyResult(int[] randstuff)
{
return Json();
}
I know i'm meant to have a method like this to receive the data from the script file, but i'm not really sure how to go about that. I want to create an array from the received Json data, which i can then use to loop through my database and select only values who have matching Ids that are in the array.
I think there's a bit of extra fluff in your code, and that it can be cleaned up. Let's take a look at getValueUsingClass (see my comments in the code itself):
function getValueUsingClass() {
// no need for looping and building the array manually, we've got .map() for that
var chkArray = $('.chk:checked').map(function() {
return this.value;
}).get(); // turn into basic array
// check if the chkArray has any elements, don't build a string
if (chkArray.length > 1) {
$.ajax({
url: '#Url.Action("MyResult", "StateController")', // let MVC build URL for you
contentType: "application/json; charset=utf-8", // type sending
dataType: "json", // type receiving
// traditional: true, // not necessary
type: "POST",
data: JSON.stringify({ 'randstuff': chkArray }), // serialization
}).done(function () { // use jQuery promises
// do things upon success
}).fail(function () { // use jQuery promises
alert("Error!");
});
} else {
alert("Please check at least one of the checkbox");
}
}
Now, MVC should be able to deserialize your JSON request into the int[] array in your controller method, as long as it allows POSTing via the presence of an HttpPostAttribute:
[HttpPost]
public JsonResult MyResult(int[] randstuff)
{
return Json();
}

Categories

Resources