How to dynamicly pass data to select list? - javascript

I need to dynamicly pass data to my select list with jquery. I see that data in console but my list is empty. Can you help me find the solution?
<script type="text/javascript">
var kunnr;
$(document).ready(function () {
$('#NAME1').autocomplete({
source: function (request, response) {
$.ajax({
url: "Form2",
method: 'POST',
data: {
term: $('#NAME1').val()
},
success: function (data) {
response(data);
}
});
},
select: function (event, ui) {
kunnr = ui.item.kunnr;
$.ajax({
url: "Form3",
method: 'POST',
data: {
kunnr: kunnr
},
success: function (data) {
console.log(data);
//there is my data ^ i need to pass to select list
}
});
}
});
});
</script>
My select list
#Html.DropDownListFor(model => model.Subaccount, new SelectList(" "), new { #class = "form-control" })

Change your javascript code to this
var kunnr;
$(document).ready(function () {
$('#NAME1').autocomplete({
source: function (request, response) {
$.ajax({
url: "Form2",
method: 'POST',
data: {
term: $('#NAME1').val()
},
success: function (data) {
response(data);
}
});
},
select: function (event, ui) {
kunnr = ui.item.kunnr;
$.ajax({
url: "Form3",
method: 'POST',
data: {
kunnr: kunnr
},
success: function (data) {
var selectData = JSON.parse(data);//use JSON.parse(), if the data is not already json formatted
$("#Subaccount").empty();
selectData.forEach(function (obj) {
//NOTE the Value and Text are what you assigned them when you fetched them
$('#Subaccount').append($('<option></option>').val(obj.Value).html(obj.Text));
});
}
});
}
});
});

Related

ReferenceError: response is not defined on autocomplete jquery ajax call in singleton design pattern

I am trying to implement jQuery autocomplete in my solution but I got an error ReferenceError: response is not defined
Here is my code
(function ($) {
$.SupportArticleObj = function (p) {
var SupportArticle = {
config: {
isPostBack: false,
async: false,
cache: false,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: { data: '' },
dataType: 'json',
baseURL: "Modules/SupportArticle/Services/SupportArticleWebService.asmx/",
url: "",
method: "",
ajaxCallMode: 0,
PortalID: PortalID,
UserModuleID: UserModuleID,
SecureToken: SecureToken,
UserName: UserName
},
init: function () {
$("#searchSupport").autocomplete({
source: function (request, response) {
searchTerm = request.term;
SupportArticle.getSearchData(searchTerm);
}
});
},
getSearchData: function (searchTearm) {
SupportArticle.config.method = "SearchSupportArticle";
SupportArticle.config.url = SupportArticle.config.baseURL + SupportArticle.config.method;
SupportArticle.config.data = JSON2.stringify({
searchTerm: searchTerm,
portalID: SupportArticle.config.PortalID,
userModuleID: SupportArticle.config.UserModuleID,
userName: SupportArticle.config.UserName,
secureToken: SupportArticle.config.SecureToken
});
SupportArticle.ajaxCall(SupportArticle.config);
},
ajaxSuccess: function (data) {
response(data);
},
ajaxFailure: function () {
jAlert('Somethings went wrong', 'Support Article');
},
ajaxCall: function (config) {
$.ajax({
type: SupportArticle.config.type,
contentType: SupportArticle.config.contentType,
cache: SupportArticle.config.cache,
url: SupportArticle.config.url,
data: SupportArticle.config.data,
dataType: SupportArticle.config.dataType,
success: SupportArticle.ajaxSuccess,
error: SupportArticle.ajaxFailure,
async: SupportArticle.config.async
});
}
};
SupportArticle.init();
};
$.fn.callSupportArticle = function (p) {
$.SupportArticleObj(p);
};
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
What I am trying to do here is, I am calling a webservice which will search the records on database and return as a list and I want to bind that list on textbox as a autocomplete. But the problem is while running the solution in browser I got an error ReferenceError: response is not defined.
I was trying http://www.c-sharpcorner.com/UploadFile/da55bf/Asp-Net-autocomplete-textbox-using-jquery-json-and-ajax/ as reference.
How can I solve the issue of ReferenceError: response is not defined
Write your script like below:
AutoDemoDataBase: function () {
$("#lytA_ctl29_txtSearchName").autocomplete({
source: function (request, response) {
var param = JSON.stringify({
userModuleID: UserModuleID,
portalID: autoComplete.config.portalId,
prefix: $("#lytA_ctl29_txtSearchName").val(),
userName: autoComplete.config.UserName,
secureToken: SageFrameSecureToken
});
$.ajax({
type: autoComplete.config.type,
contentType: autoComplete.config.contentType,
cache: autoComplete.config.cache,
url: autoComplete.config.baseURL + "GetNames",
data: param,
dataType: autoComplete.config.dataType,
async: autoComplete.config.async,
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.Name
}
}))
},
error: function (response) {
jAlert(response.responseText);
},
failure: function (response) {
jAlert(response.responseText);
}
});
},
select: function (e, i) {
$("#hfId").val(i.item.val);
$('#test').text(i.item.val);
},
minLength: 1
});
}
Your ajax success function is out of response scope.

jQuery Autocomplete to populate multiple textboxes [duplicate]

I have an autocomplete text field, that uses JSON like so:
$(function () {
var src = '#Url.Action("GetParts", "Parts")'
$("#autoCompleteBox").autocomplete({
source: function (request, response) {
$.ajax({
url: src,
async: true,
dataType: "json",
data: {
partNumber: $("#autoCompleteBox").val()
},
success: function (data) {
response(data[0]);
}
});
}
});
});
What I want to do is when the user selects the item from the suggested list is make another ajax call to get specific information about that item and populate other textboxes on the page.
What is the best approach for this?
You can do that in the select event of the autocomplete.
$(function () {
var src = '#Url.Action("GetParts", "Parts")'
$("#autoCompleteBox").autocomplete({
source: function (request, response) {
$.ajax({
url: src,
async: true,
dataType: "json",
data: {
partNumber: $("#autoCompleteBox").val()
},
success: function (data) {
response(data[0]);
}
});
},
select: function (event, ui) {
var item= ui.item.label;
//Now make the ajax call here
$.post("SomeValidUrl", new { id : item } ,function(res){
// do something with res
});
}
});
});

How to work with jQuery UI auto-complete extender for text searching

I'm working with jQuery UI Auto Complete extenders for populating list.
Here i include this article for more reference of my code detail.
Here I modify method for auto complete. In article this calls from css class and I want from the ID of the control.
This is my jQuery script :
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#<%=txt_reason.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Raise_Ticket.aspx/SearchReasons",
data: "{'prefixText':'" + $("#<%=txt_reason.ClientID %>").val() + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
And this is my method:
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
[System.Web.Services.WebMethod]
public static List<string> SearchReasons(string prefixText)
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
var query = db.Reasons.Where(r => r.ReasonText.Contains(prefixText)).Select(r => r).ToList();
List<string> reasons = new List<string>();
foreach (var item in query)
{
reasons.Add(item.ReasonText.ToString());
}
return reasons;
}
}
The problem is not detecting this textbox not displaying result.
Use this
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#txt_reason").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Raise_Ticket.aspx/SearchReasons",
data: "{'prefixText':'" + $("#txt_reason").val() + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
Using this you can also try
$(document).ready(function () {
$("#textbox").autocomplete({
source: function (request, response) {
$.ajax({
url: "URL",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (retrieveddata) {
if (retrieveddata.length > 0) {
}
},
error: function (request, status, error) {
console.log("Error! " + request.responseText);
}
})
},
});
})
Take Tern Variable in Code

Jquery Autocomplete doesn't work

i'm trying to add an autocomplete to an input box (i'm in asp.net/vb.net project) with the autocomplete source from a database.
So i've created a webservice and i did an ajax call:
<script type="text/javascript">
$(document).ready(function () {
$('#modelloInput').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebServices/AutocompleteWS.asmx/getTuttiIModelli",
data: "{'prefix':'" + request.term + "'}",
dataType: "json",
async: true,
success: function (data) {
response(data.d);
},
error: function (result) {
//alert("Error");
}
});
}
});
});
</script>
<input type=text id="modelloInput" />
Now when i run the application and i write something in the inputbox i got the entire list in the autocomplete box.
I can write everything but i get always the entire list of elements.
Why?
I think there must be some issue in your web-service code,
you can use this basic code for autoComplete,
$( "input.suggest-user" ).autocomplete({
source: function( request, response ) {
$.ajax({
dataType: "json",
type : 'Get',
url: 'yourURL',
success: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading'); // hide loading image
response( $.map( data, function(item) {
// your operation on data
}));
},
error: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3,
open: function() {
},
close: function() {
},
focus:function(event,ui) {
},
select: function( event, ui ) {
}
});
OR
$("#id").autocomplete(
{
search: function () {},
source: function (request, response)
{
$.ajax(
{
url: ,
dataType: "json",
data:
{
term: request.term,
},
success: function (data)
{
response(data);
}
});
},
minLength: 2,
select: function (event, ui)
{
var test = ui.item ? ui.item.id : 0;
if (test > 0)
{}
}
});

How to turn autocomplete into a function

I am calling jquery autocomplete several times on my form. How can I refactor and the following javascript into a function?
$(document).ready(function () {
$("#Style").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Beer/AutoStyle",
type: "GET",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Style,
value: item.Style
}
}));
}
});
}
});
});
I cannot figure out how to paramterize the this
return {
label: item.Style,
value: item.Style
}
So my function would be something like this
function AutoCompleteTemplate(tagID){
$(document).ready(function () {
$("#"+tagID).autocomplete({
source: function (request, response) {
$.ajax({
url: "/Auto"+tagID,
type: "GET",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.tagID,
value: item.tagID
}
}));
}
});
}
});
});
}
You need to use bracket notation as the member operator, since tagID is a variable holding the actual property key
function AutoCompleteTemplate(tagID) {
$("#" + tagID).autocomplete({
source: function (request, response) {
$.ajax({
url: "/Auto" + tagID,
type: "GET",
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item[tagID],
value: item[tagID]
}
}));
}
});
}
});
}

Categories