In this scenario I've got a textbox to which I have added autocomplete functionality. The kicker is that I want to dynamically change the source option of the AJAX call based on the value of a dropdown list. To do this I encapsulated the differences between the AJAX calls in an object of type Resolver
. The name
property of the Resolver object is the same as the text value coming from the dropdown list. I was looking for a way to make this a little cleaner. The code works, just looking for more extensible options as the project grows.
$(document).ready(function ()
{
//encapsulate the URL of the AJAX call
//the name property maps to a dropdown list value
//so if Drugs is chosen from the dropdown menu we look for the name property which = drugs
Resolver = function (name, url)
{
this.name = name;
this.url = url;
}
Resolver.prototype.resolve = function (request, response)
{
$.ajax(
{
type: "POST",
url: "Service.asmx/" + this.url,
data: JSON.stringify({ 'param': $('#auto').val() }),
dataType: "json",
contentType: "application/json",
success: function (data)
{
response(data.d);
},
error: function (xhr)
{
console.log(xhr.status);
}
});
}
//in the future I expect the Resolver object to have more properties
//this is the simplest example I could think of
var drugs = new Resolver('drugs', 'GetDrugNames');
var hospitals = new Resolver('hospitals', 'GetHospitalNames');
var resolverArray = [];
resolverArray.push(drugs);
resolverArray.push(hospitals);
//on the change even of the ddl we're looking for the index of the resolverArray
//which has the name name property as the value selected in the ddl.
$('#ddl').change(function ()
{
var target = $(this).val().toLowerCase();
var index = 0;
$.each(resolverArray, function (ix, val)
{
if (resolverArray[ix].name == target)
{
index = ix;
}
});
$('#auto').autocomplete(
{
source: function (request, response)
{
resolverArray[index].resolve(request, response);
}
});
});
});
JSON.stringify
when passing an object as thedata
property to jQ's$.ajax
, jQ will do that for you \$\endgroup\${ param: $('#auto').val() }
to the data property will sent the$('#auto').val()
value as$_POST['param']
... the request will look like this:param=<encodeURI($('#auto').val()>
, so no need to decode/parse the data \$\endgroup\${ param: $('#auto').val() }
to work. I'm using .NET 4.0 and get anInvalidJsonPrimitive
error. \$\endgroup\$x-www-form-urlencoded
mime \$\endgroup\$