jQuery Multiple Autocomplete with c# - c#

I'm implementing multiple autocomplete using jQuery UI. Also I'm using webservice to pass values. I check jQuery UI demo for multiple autocomplete and using exact same code and it's working until the first autocomplete and adds a "," at the end.
But here I'm stuck, It's not searching for the next autocomplete. Well I didn't add a part of the code from the demo, which I don't know where it suppose to go. If someone could help me please.
Heare isthe My code
<script type="text/javascript">
$(function () {
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$(".tb")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
source: function (request, response) {
$.ajax({
url: "EmployeeList.asmx/FetchEmailList",
data: "{ 'mail': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
//term: extractLast(request.term),
response($.map(data.d, function (item) {
return {
value: item.Email
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
search: function () {
// custom minLength
var term = extractLast(this.value);
alert(term);
if (term.length < 2) {
return false;
}
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
alert(terms);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
} //,
//minLength: 2
});
});
</script>
Here is the code I'm missing from jQuery UI demo
.autocomplete({
source: function( request, response ) {
$.getJSON( "search.php", {
term: extractLast( request.term )
}, response );
},
I don't know where to add this code:
term: extractLast( request.term )
here is the link for entire code Demo Code link

replace
data: "{ 'mail': '" + request.term + "' }"
with
data: "{ 'mail': '" + extractLast(request.term) + "' }"
this should work but i didn't like much the way you encode JSON, may create problems with quotes etc.

Related

C# MVC5 Jquery auto complete, fail to return JSON Data

I am a beginner in programming, I have researched a few places to implement the jquery autocomplete. I managed to call postback to JSON GROUP method. But after success, I can't manage to get the JSON results or if I code it wrongly. Please help
Code
$(function () {
$("#txtGRP_CODE").autocomplete({
source: function (request, response) {
$.ajax({
url: '/AutoComplete/GRP_CODE',
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{ 'prefix': '" + request.term + "'}",
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#txtGRP_CODE").val(i.item.value);
},
minLength: 1
});
});
Server Side
[HttpPost]
public JsonResult GRP_CODE(string prefix)
{
List<AutoCompleteController> listGroup = new List<AutoCompleteController>();
string sSQL = " SELECT * FROM icgrp WHERE GRP_CODE like '" + prefix + "%'";
DataTable dt = conn2.GetData(sSQL);
using (MySqlDataReader dr = conn2.ExecuteReader(sSQL))
{
//foreach (DataRow dr in ds.Tables[0].Rows)
while (dr.Read())
{
listGroup.Add
(new search
{
Name = dr["GRP_CODE"].ToString(),
Sr_no = dr["GRP_PART"].ToString()
}
);
}
}
//**I manage to populate listGroup but when passing it to the client side I can't get the Json data.
return Json(listGroup, JsonRequestBehavior.AllowGet);
}
Server Side
https://ibb.co/sVbKSYG
Client side
https://ibb.co/09CFXdW
Network Client Response
https://ibb.co/BB61dRd
Response
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /AutoComplete/GRP_CODE
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3282.0

How to call codebehind method from Jquery after autocomplete selection

I have a autocomplete text box as and when the user types the city names are prompted. Once the user selects city name the selected value is retrieved using the following code:
$(document).ready(function() {
$('#txtName').on('change', function() {
$('#selectedItem').html('You selected: ' + this.value);
}).change();
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Now I need to pass the selected value and call method in aspx.cs (code-behind) to retrieve further details of selected city.
How can I call a method from JQuery can somebody guide me towards that
You must call ajax in autocompleteselect like this
$('#txtName').on('autocompleteselect', function (e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({url: "aspx.cs",data:{value:ui.item.value}, success: function(result){
//response from server
}});
});
Server Side changes
You need to mark that method with WebMethod attribute to call it from the client side or you need to create a web service.
[WebMethod]
public static yourObject GetCityDetails(string cityId)//name this method as per your needs.
{
//Do whatever you want.
return yourObject; //it can also be in JSON format.
}
Client Side changes
Make an ajax call to the method from the client side.
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({
url: "yourpage.aspx/GetCityDetails", //same method name here.
data: { cityId: this.value },
success: function(result) {
//do whatever you want with server side data here.
}
});
});
You Can use Web Method
function GetDetails(cityId) {
$.ajax({
type: "POST",
url: 'Default.aspx/GetDetails',
data: {"cityId":cityId},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log(msg);
},
error: function (e) {
console.log(e);
}
});
}
$(document).ready(function() {
$('#txtName').on('change', function() {
$('#selectedItem').html('You selected: ' + this.value);
}).change();
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
GetDetails(ui.item.value);
});
in your aspx page
[WebMethod] //Default.aspx.cs
public static void GetDetails(cityId)
{
//Your Logic
}
Use $.Ajax to send the selected value to the server (code-behind) and get the response:
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({
url: "your-page.aspx/GetCityDetails",
data: { Name: this.value },
success: function(result) {
//Process the result from the code-behind.
}
});
});
Your code-behind must have a webmethod named GetCityDetails that accepts the name parameter and returns a city object as JSON.
This is what solved my issue:
The following is the code in jquery part in .aspx
function SetCityName(cityName) {
$.ajax({
type: "POST",
url: 'Default.aspx/GetCityDetails',
data: JSON.stringify({ cityName: cityName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("CityName:" + cityName + "\n\nRequest: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result.d);
}
});
}
This is the code in .aspx.cs
[WebMethod]
public static string GetCityDetails(string cityName)
{
MessageBox.Show(cityName);
return "success";
}
The trick part is using the following piece in JQuery. I have tried above alternatives provided but none worked apart from the below piece of code:
data: JSON.stringify({ cityName: cityName }),

Autocomplete with Ajax returns No HTTP resource was found that matches the request URI

I am trying to implement an autocomplete on my textbox with data that comes from a web method. The webmethod works on the browser like:
http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers?SearchString=e
and these are the results:
[{"IssuerID":1,"Name":"test tester","ChequeAccountNumber":"12345678","CurrencyCode":"EUR"}]
Now, I am trying to add on the textbox the Name data from the response but I'm getting an error in the function below:
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers?{ 'SearchString': 'e'}'.","MessageDetail":"No action was found on the controller 'ModuleTask' that matches the request."}
Below, my AJAX call seems to fail for a reason, which I believe comes from passing wrongly the parameters. I do not have experience with ajax so far, so your input will be great.
<script type="text/javascript">
$(function () {
$("[id$=TextBox1]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers")%>',
data: "{ 'SearchString': '" + request.term + "'}",
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id$=hfIssuerID]").val(i.item.val);
},
minLength: 1
});
});
</script>
My web method:
public class ModuleTaskController : DnnApiController
{
[AllowAnonymous()]
[HttpGet()]
public HttpResponseMessage GetIssuers(string SearchString)
{
try {
List<Issuers> listIssuers = new List<Issuers>();
IssuersController ic = new IssuersController();
listIssuers = ic.GetIssuers(10, SearchString);
return Request.CreateResponse(HttpStatusCode.OK, listIssuers.ToJson);
} catch (Exception exc) {
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
}
}
}
Any ideas?
EDIT:
$(function () {
$("[id$=TextBox1]").autocomplete({
source: function (request, response) {
var qstring = '?' + jQuery.param({ 'SearchString': request.term });
$.ajax({
url: '<%=ResolveUrl("http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers")%>' + qstring,
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id$=hfIssuerID]").val(i.item.val);
},
minLength: 1
});
});
Your web method is a GET and accepts a querystring yet your Ajax call is trying to pass a JSON object, which is getting appended to the end of your url. You can see this by reading what the URL actually is, in the error message
There are a bunch of different things you can do. This is just one.
// turn your search object into querystring
var qstring = '?'+ jQuery.param({ 'SearchString': request.term});
// append this querystring to the end of your url
$.ajax({
url: '<%=ResolveUrl("http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers")%>' + qstring ,
// remove data and datatype
type: "GET",
//... etc
Also in this case, it doesn't look like you need the ResolveUrl.
Perhaps try your URL as:
url:'http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers' + qstring;

jquery POST data in aspx page

I post data to my aspx file qith the following code:
$.ajax({
type: 'POST',
url: "Ajax_Text.aspx?rand=" + myRand
+ "&id=" + $(".articleID").attr('title')
+ "&text=" + $("#text").val(),
cache: false,
beforeSend: function () {
},
success: function (data) {
alert(data);
}
});
Why i catch the text value by using the following code
string text = "";
if (!String.IsNullOrEmpty(Request.QueryString["text"]))
{
text = Request.QueryString["text"].ToString();
}
else
{
text = "";
}
and not this code:
string text = "";
if (!String.IsNullOrEmpty(Request.Form["text"]))
{
text = Request.Form["text"].ToString();
}
else
{
text = "";
}
Why is that? I expected Request.Form to work as i post data with jquery! Any ideas?
I suspect that the problem is that i have my input in the url parameter. Maybe i should put it to a data parameter but that means it will become a json request!
POST data are not send in query string but added to the request body. Try this code:
$.ajax({
type: 'POST',
url: "Ajax_Text.aspx",
data: {'rand': myRand, 'id': $(".articleID").attr('title'), 'text': $("#text").val()},
cache: false,
beforeSend: function () {
},
success: function (data) {
alert(data);
}
});
You are "posting" the data (text) as a query string (as part of URL) so you have to use Request.QueryString.

Get selected item using JQuery AutoComplete

I have the code below working. How do I read and set the item selected to a control on the page (i.e. hidden field). NomineeUserName is a property on the object being returned. Thanks for any help provided.
$(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Service/NomineeWebService.asmx/GetMatchingActiveDirectoryUsers",
data: "{ 'SearchCharacters': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
id: item.NomineeUserName,
value: item.NomineeLastNameFirstName,
data: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function (event, ui) {
selectedItemData = ui.item.data;
}
});
});
In your select handler, it should be pretty simple:
select: function (event, ui) {
$("hidden-input-selector").val(ui.item.id);
}

Categories

Resources