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);
}
Related
My c# action looks like:
[HttpPost]
public JsonResult GetItems(int id)
{
var productsQryList = some-query-to-getitems.ToList();
if(productsQryList != null)
{
return Json(productsQryList);
} else
{
return Json(new());
}
}
In my view, the autocomplete configuration looks like:
$("#productInfo").autocomplete({
minLength: 1,
source: function( request, response ) {
$.ajax({
type: "GET",
url: "/api/purchase/SearchProductsSimple",
data: {
term: request.term
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function( data ) {
response( data );
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
select: function (event, ui) {
if (ui.item) {
$("#order-items-table tbody tr").remove();
$.ajax({
cache: false,
type: "POST",
url: "/api/purchase/GetItems",
data: { "id": ui.item.value },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response($.map(data.d, function (itemList) {
for(const item of itemList) {
appendOneRow(item);
counter++;
}
countTrSetIndex();
return false;
}))
},
failure: function (response) {
alert(response.d);
}
});
}
}
});
In firefox plugin RESTED,
The GetItems method runs good if I change its attribute to HttpGet.
But, if The attribute is HttpPost, I got 400 error.
By the way, The select event must be POST call.
wait for resolution.
Thank you guys.
You might have [AutoValidateAntiforgeryToken] attribute on your controller, so you must send forgery token value at ajax call.
data: { "id": ui.item.value,
"__RequestVerificationToken":$( "input[name='__RequestVerificationToken']" ).val() },
I want know how to use autocomplete with database using ajax and the data get faster on local server and Main server also
And i try this script
$("#SI").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetSearchValue","Main")',
dataType: "json",
data: { search: $("#SI").val() },
success: function (data) {
response($.map(data, function (item) {
return { label: items.Name, value: items.Name };
}));
},
error: function (xhr, status, error) {
alert("Error");
}
});
}
});
I am writing CRUD application using ASP.NET MVC, KnockoutJS and database. When I write separate viewmodel for Create, Read, Update and Delete. and calling each view model in separate view (Create, Read, Update and Delete) then It's working fine. But when I include all view model in one single view model, then calling that view model in every View. Then I am neither able to create nor able to edit.
Please help me with this. I tried so many ways but could not get a proper solution.
I have written this function using Knockout:
$(function() {
ko.applyBindings(modelView);
});
Var parsedSelectedCourse = $.parseJSON(selectedCourse);
var modelView = {
Read: {
Courses: ko.observableArray([]),
viewCourses: function() {
var thisObj = this;
try {
$.ajax({
url: '/Home/ListCourses',
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function(data) {
thisObj.Courses(data); //Here we are assigning values to KO Observable array
},
error: function(err) {
alert(err.status + " : " + err.statusText);
}
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
},
Create: {
CourseName: ko.observable(),
CourseDescription: ko.observable(),
createCourse: function() {
try {
$.ajax({
url: '/Home/Create',
type: 'post',
dataType: 'json',
data: ko.toJSON(this), //Here the data wil be converted to JSON
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
},
Update: {
CourseID: ko.observable(parsedSelectedCourse.CourseID),
CourseName: ko.observable(parsedSelectedCourse.CourseName),
CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),
updateCourse: function() {
try {
$.ajax({
url: '/Home/Update',
type: 'POST',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
},
Delete: {
CourseID: ko.observable(parsedSelectedCourse.CourseID),
CourseName: ko.observable(parsedSelectedCourse.CourseName),
CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),
deleteCourse: function() {
try {
$.ajax({
url: '/Home/Delete',
type: 'POST',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
}
};
function successCallback(data) {
window.location.href = '/Home/Read/';
}
function errorCallback(err) {
window.location.href = '/Home/Read/';
}
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;
Please consider below code. I am loading my products view using below ajax call.
$.ajax({
cache: true,
type: "GET",
url: url,
data: json.stringify(data),
success: function (data) {
var mainview = $(data).find(".maindiv");
$('.maindiv').replaceWith(mainview);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error Occured...... No Products Found');
},
complete: function () { subscribeProgress.hide(); }
});
Now when I load this view there is add to cart button for each product on which another ajax call is executed to check if customer is registerd or guest and accordingly popup for register is shown. Now for registering customer, another ajax method is called which works properly but json data is not returned to the success and is directly shown on the page.
Below id code for registering customer through popup
$('#formpopupReg').unbind('submit');
$('#formpopupReg').bind('submit', function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
// you can post your model with this line
data: $(this).serialize(),
success: function (data) {//Json should get back to this call but doesnt
if (data.status == "Wrong email") {
$('#modelerrors').text("Wrong email");
}
if (data.status == "emailexists") {
//Code on Error
}
if (data.status == "registersuccess") {
location.reload();
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Internal Error.');
},
complete: function () { }
});
}
return false;
});
Any solutions.I want json data to return back to success call.
Add dataType:"json" to your ajax call.
Try this, problem is your } is extra in your code, and missing dataType: 'json', if you use json.
$.ajax({
cache: true,
url: url,
dataType: 'json',
data: json.stringify(data),
success: function (data) {
var mainview = $(data).find(".maindiv");
$('.maindiv').replaceWith(mainview);
}
error: function (xhr, ajaxOptions, thrownError) {
alert('Error Occured...... No Products Found');
},
complete: function () { subscribeProgress.hide(); }
});