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]
}
}));
}
});
}
});
}
Related
After searching for an event successfully, I would like to open the update / delete dialog with all information filled in. But nothing happens.
I have this code in Default.aspx:
<script type="text/javascript">
$(function () {
$("[id$=txtSearch]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Default.aspx/GetEvent") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
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$=hfCustomerId]").val(i.item.val);
date = moment(i.item.label, "DD/MM/YYYY HH:mm");
$("#calendar").fullCalendar('gotoDate', date);
let eventProva = $("#calendar").fullCalendar("getEventById", i.item.label);
$("#calendar").fullCalendar('updateEvent', eventProva);
},
minLength: 1
});
});
</script>
where 'i.item.label' is the event id.But nothing happens with the line $("#calendar").fullCalendar('updateEvent', eventProva);
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));
});
}
});
}
});
});
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.
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
I am using jQuery Autocomplete.
It's making an AJAX request on every keypress which I don't want. If data from a previous AJAX request matches a search it should not make any more AJAX requests.
<script>
$('#tags').autocomplete({
source: function (request, response) {
$.ajax({
url: '/TestDDl/Index',
// data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.user, function (item) {
return {
label: data.name,
val: data.val
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
autoFocus: true,
keypress: function (event, ui) {
alert('Not Selected');
if (!ui.item) {
alert('Not Selected');
}
}
});
});
Here if I am typing the name of a user which is already in previous AJAX request data, it should not make an AJAX request on next the keypress.
You can declare a variable, assing user input to it, then update it in your success function. And just before making next call, check if your variable matches the next data.
Something like this:
<script>
var recent = '';
$('#tags').autocomplete({
source: function (request, response) {
if (recent == request.term) {
return;
}
recent = request.term;
$.ajax({
url: '/TestDDl/Index',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.user, function (item) {
return {
label: data.name,
val: data.val
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
autoFocus: true,
keypress: function (event, ui) {
alert('Not Selected');
if (!ui.item) {
alert('Not Selected');
}
}
});
</script>
<script>
window.xyz = []; //For saving history
$('#tags').autocomplete({
source: function (request, response) {
if(xyz[request]){
response(xyz[request]); // Return previously saved data
}else(
$.ajax({
url: '/TestDDl/Index',
// data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
var res = $.map(data.user, function (item) {
return {
label: data.name,
val: data.val
}
});
xyz[request]=res; //set data to reuse later
response(res)
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
}
},
autoFocus: true,
keypress: function (event, ui) {
alert('Not Selected');
if (!ui.item) {
alert('Not Selected');
}
}
});
</script>
Your next ajax reques should be in the Success function of the first ajax request.Buid the logic there.If you find the match don't call the second ajax request else call the second ajax request and all should be in the success function of the first ajax request.