I am trying to get a list of name and Id at autocomplete. I have keypress event at textbox and called a funstion of ajax post and I am able to get list for selection. I am trying to get Id and Name. If I have binded name in the textbox then where should I have to keep ID so that it could not be visible to user but I can use it when I have to save data. I can use hidden field but how to assign that Id to hidden field id if Select event of Autocomplete is not working. Also, I need to change the hidden field value when another element is get selected from list.
Please Help me regarding this. Thank You.
function SearchClients() {
}
$(document).ready(function () {
$("#txt_Autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../PsychiatricEvaluation/SearchClients",
data: "{'searchtext':'" + document.getElementById('txt_Autocomplete').value + "'}",
dataType: "json",
success: function (data) {
response($.map(data.Data, function (item) {
return {
label: item.Name,
value: item.id
}
}));
},
select: function (event, ui) {
alert("hi");
//$("#txt_Autocomplete").val(ui.item.value);
$("#hdnPkClientId").val(ui.item.id);
},
change: function (e, ui) {
alert("changed!");
},
error: function (result) {
alert('Error');
}
});
}
});
});
Put your jQuery hookups inside of the $(document).ready event:
$(document).ready(function () {
$("#txt_Autocomplete").autocomplete({ ...
});
Related
I populated asp.net dropdownlists with jquery to show countries and cities. The dropdownlists show the correct value. I need to get the text of a ddlState at the backend of asp.net. However, I cannot get the selected text from the dropdownlist. It said it is null.
Below is my script.
<script type="text/javascript">
$(document).ready(function () {
GetCountries();
GetStates();
});
function GetCountries() {
$.ajax({
type: "GET",
url: "http://api.geonames.org/countryInfoJSON?formatted=true&lang=en&style=full&username=xxx",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (data) {
$(".ddlCountry").append($('<option />', { value: -1, text: 'Select Country' }));
$(data.geonames).each(function (index, item) {
$(".ddlCountry").append($('<option />', { value: item.geonameId, text: item.countryName}));
});
},
error: function (data) {
alert("Failed to get countries.");
}
});
}
function GetStates() {
$(".ddlCountry").change(function () {
GetChildren($(this).val(), "States", $(".ddlState"));
});
}
function GetChildren(geoNameId, childType, ddlSelector) {
$.ajax({
type: "GET",
url: "http://api.geonames.org/childrenJSON?geonameId=" + geoNameId + "&username=xxx",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (data) {
$(ddlSelector).empty();
$(ddlSelector).append($('<option />', { value: -1, text: 'Select ' + childType }));
$(data.geonames).each(function (index, item) {
$(ddlSelector).append($('<option />', { value: item.geonameId, text: item.name + "," + item.countryCode }));
});
},
error: function (data) {
alert("failed to get data");
}
});
}
</script>
Below is the two dropdownlists that i have.
<asp:DropDownList
runat="server"
ID="ddlCountry"
CssClass="ddlCountry">
</asp:DropDownList>
<br />
<asp:DropDownList
runat="server"
ID="ddlState"
onChange="ddlState_OnChange"
CssClass="ddlState">
</asp:DropDownList>
Can anybody help? Thank you.
your "change" function should not be inside the GetStates() function. You should collect the value every time the user change the select. and after that trigger the GetStates with the actual value.
$(".ddlCountry").change(function () {
valueOfddlCountry = $(this).val();
});
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 }),
I was facing some problem with AJAX code. I was using MVC3 for our project. My requirement is bind the dropdown value using AJAX when page load. What happens when loading the page, the AJAX request send to the controller properly and return back to the AJAX function and binds the exact values in dropdown. But sometimes (When page refreshed or first time load) its not binding retrieved value. Rather its showing default value. Pls see my code and suggest me where i am doing wrong.
Edit: Even i tried to use async property to false. Its not at all send to the controller action method for getting the data.
Code
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetUser", "Invoices")',
data: "{'id':" + JSON.stringify(currval) + "}",
dataType: "json",
async: true,
success: function (data) {
$("#User-" + curr).select2("data", { id: data.Value, Name: data.Text });
$(this).val(data.Value);
}
});
Thanks,
Let's say your Action method is below
public JsonResult hello(int id)
{
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
and JQuery should be like below
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var currval = 2;
$.ajax({
url: 'URl',
async: true,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: currval }),
success: function (data) {
}
});
});
</script>
You are declaring your data property incorrectly. Try this:
data: { id: currval },
I had populated an ASP.net dropdown list with AJAX now I need to get the Id to store in into the database in a C# method, (I'm using LINQ)
This is my webmethod
[WebMethod]
public static ArrayList GetLanguageList()
{
ArrayList lstArrLanguage = new ArrayList();
IQueryable<Common.Town> myList = new SupplierBL().GetTowns();
foreach(Common.Town t in myList)
{
string name = t.Name;
string id = t.TownId.ToString();
lstArrLanguage.Add(new ListItem(name, id));
}
return lstArrLanguage;
}
My test.aspx code
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "test.aspx/GetLanguageList",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#ddlLanguage").empty().append($("<option></option>").val("[-]").html("Please select"));
$.each(msg.d, function () {
$('#<%=ddlLanguage.ClientID%>').append($("<option></option>").val(this['Value']).html(this['Text']));
});
},
error: function () {
alert("An error has occurred during processing your request.");
}
});
});
</script>
You can't get selected value from DropDownList if you adding options in javaScript. You can try the following
string selectedValue = Request.Form[ddlLanguage.UniqueID];
This question may be useful also.
If you populate the value of dropdown via ajax than it can't be available on Server Side because the page doesn't postback during ajax request.
In order to get the value of dropdown in C# use below snippets :
String _value = Convert.ToString(Request[ddlLanguage.ClientID]);
Hope this will help !!
$(function () {
$("#tbNominalAccounts").autocomplete({
source: function (request, response){
$.ajax({
url: "TestPage3.aspx/GetUserNominalAccounts",
type:"POST",
datatype:"json",
data :{ searchText : request.term},
success: function(data)
{
response(
$.map(data, function(item)
{
return { label: item.NominalAccount, value:item.NominalAccount, id:item.NominalAccount}
}))
}
})
}
});
});
Added breakpoints and it hits the ajax call but when i put a breakpoint on the method GetUserNominalAccounts it doesent even reach it!! Any ideas of why its not posting?!
I have a textbox with an ID of #tbNominalAccounts just for background information
Reformat your data like so:
pString = '{"searchText":"' + request.term + '"}';
$.ajax({
data: pString,
...
and your server side code should have been properly "decorated" to allow page access.
Thought I would add some code from a working sample using asp.net: you might need this converter for generic handling of the asp.net data:
dataType: "jsond",
type: "POST",
contentType: "application/json",
converters: {
"json jsond": function(msg)
{
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
EDIT: And for the use of the return value:
focus: function(event, ui)
{
return false; // return "true" will put the value (label) from the selection in the field used to type
},
try putting a contentType in the ajaxRequest:
contentType: "application/json; charset=utf-8",
I've noticed that when using jQuery Ajax the default content Type application/x-www-form-urlencoded doesn't work well enough.