I am using jQuery UI Autocomplete on my Create View in my web application
When I click in the textbox that I want the autocomplete to service, and type 1 letter, I receive a runtime error:
Here is the line of the built in script debugger where the error is occurring
Here is my Script:
<script type="text/javascript">
$(document).ready(function () {
$('#Categories').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Activities/AutoCompleteCategory",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.subcategory, value: item.subcategory };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
Here is my Controller:
public JsonResult AutoCompleteCategory(string term)
{
var result = (from r in db.Activities
where r.subcategory.ToUpper().Contains(term.ToUpper())
select new { r.subcategory }).Distinct();
return Json(result, JsonRequestBehavior.AllowGet);
}
If I click Do not show this message again, it works perfectly.
Any help to figure out why this run-time error is happening is greatly appreciated.
The code that's failing is trying to execute the results method under messages.
this.messages.results(e.length)
You have defined the results method as "" here:
messages: {
noResults: "", results: ""
}
The browser is probably handling this error silently after you cancel the dialog box, but underneath it is still dealing with the error. You should remove the messages section if you have nothing to add there, or create your messages as empty functions.
Related
i had build a web form with autocomplete method, the program is working fine in IDE. But after i publish the application to IIS, the method is not working. the console show this error `failed to load resouces: server response with a status 500(internal server error) Index2) . Im suspected the jquery code didn't recognize the controller name.
CSHTML
<script type="text/javascript">
$(document).ready(function () {
$("#CardName").autocomplete({
source: function (request, response) {
$.ajax({
url: "Index2",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.CardName, value: item.CardId };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
Controller
[HttpPost]
public JsonResult Index2(string Prefix)
{
List<CardHolderDetails> getCardList = new List<CardHolderDetails>();
getCardList = _service.getCardList();
List<CardHolderDetails> ObjList = new List<CardHolderDetails>();
foreach (var value in getCardList)
{
ObjList.Add(new CardHolderDetails { CardId = value.CardId, CardName = value.CardName });
}
//Searching records from list using LINQ query
var CardName= (from N in ObjList
where N.CardName.StartsWith(Prefix)
select new { N.CardName, N.CardId });
return Json(CardName, JsonRequestBehavior.AllowGet);
}
The following code it is working fine during the development, but once publish to IIS it seem the jquery url cannot be read. any replacement for URL to controller function name?
If your _service.getCardList() returns null then the foreach will throw an exception which you have not handled.
Maybe that is the reason you are getting (500) internal server error and not the jquery url, as 500 error code suggests that something went wrong in the server code.
As a suggestion, You should use implement try - catch and log the exceptions somewhere to be able to resolve such issues.
I am realy struggling with this and would apprecate any advice.
I have this field
<input id="scanInput" type="text" placeholder="SCAN" class="form-control" />
For which I would like to make an ajax call when the field changes, so I tried
<script>
$("#scanInput").change(function () {
console.log('ye');
$.getJSON("?handler=GetPartDetails", function (data) {
//Do something with the data.
console.log('yay?');
}).fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
});
});
</script>
Where my PageModel has this method
[HttpPost]
public IActionResult GetPartDetails()
{
return new JsonResult("hello");
}
and the url for the page in question is /packing/package/{id}
Now when I change the input value, I see ye on the console, and I can see that the network called http://localhost:7601/Packing/Package/40?handler=GetPartDetails (the correct URL I think?) with status code 200
But My breakpoint in GetPartDetails never hits, and I don't see yay? in the console.
I also see this message from the fail handler:
Request Failed: parsererror, SyntaxError: JSON.parse: unexpected character at line 3 column 1 of the JSON data
But I'm not even passing any JSON data... why must it do this
I also tried this way :
$.ajax({
type: "POST",
url: "?handler=GetPartDetails",
contentType : "application/json",
dataType: "json"
})
but I get
XML Parsing Error: no element found
Location: http://localhost:7601/Packing/Package/40?handler=GetPartDetails
Line Number 1, Column 1:
I also tried
$.ajax({
url: '/?handler=Filter',
data: {
data: "input"
},
error: function (ts) { alert(ts.responseText) }
})
.done(function (result) {
console.log('done')
}).fail(function (data) {
console.log('fail')
});
with Action
public JsonResult OnGetFilter(string data)
{
return new JsonResult("result");
}
but here I see the result text in the console but my breakpoint never hits the action and there are no network errors..............
What am I doing wrong?
Excuse me for posting this answer, I'd rather do this in the comment section, but I don't have the privilege yet.
Shouldn't your PageModel look like this ?
[HttpPost]
public IActionResult GetPartDetails() {
return new JsonResult {
Text = "text", Value = "value"
};
}
Somehow I found a setup that works but I have no idea why..
PageModel
[HttpGet]
public IActionResult OnGetPart(string input)
{
var bellNumber = input.Split('_')[1];
var partDetail = _context.Parts.FirstOrDefault(p => p.BellNumber == bellNumber);
return new JsonResult(partDetail);
}
Razor Page
$.ajax({
type: 'GET',
url: "/Packing/Package/" + #Model.Package.Id,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
input: barcode,
handler: 'Part'
},
success: function (datas) {
console.log('success');
$('#partDescription').html(datas.description);
}
});
For this issue, it is related with the Razor page handler. For default handler routing.
Handler methods for HTTP verbs ("unnamed" handler methods) follow a
convention: On[Async] (appending Async is optional but
recommended for async methods).
For your original post, to make it work with steps below:
Change GetPartDetails to OnGetPartDetails which handler is PartDetails and http verb is Get.
Remove [HttpPost] which already define the Get verb by OnGet.
Client Request
#section Scripts{
<script type="text/javascript">
$(document).ready(function(){
$("#scanInput").change(function () {
console.log('ye');
$.getJSON("?handler=PartDetails", function (data) {
//Do something with the data.
console.log('yay?');
}).fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
});
});
});
</script>
}
You also could custom above rule by follow the above link to replace the default page app model provider
I'm working on an autocomplete that calls a method on my home controller, the javascript calls the method and returns the array. However the values do not display on the text box drop down, nothing does.
If I use a straight array as the source and don't call the home controller then it works just fine.
I don't see what I'm missing here, so I narrowed down the home controller method just to return an array using no logic until I figure this problem out.
Home Controller Method:
public string[] GetPatientName()
{
var names = new List<string> { "Bent","Boon","Book", "Al", "Cat", "Doe", "Ed", "Fox", "George" };
return names.ToArray();
}
Javascript:
<script language="javascript" type="text/javascript">
$(function() {
$('#tags').autocomplete({
source: function(request, response) {
$.ajax({
url: "/Home/GetPatientName",
data: "{ 'pre':'" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
response($.map(data.d,
function (item) {
alert(item);
return { value: item }
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
delay: 0
});
});
</script>
HTML
<form>
<input id="tags" type="text" />
</form>
2 things:
1. From the top of my mind, if it wirked with a regular array and didnt work with the result of jQuery map function you probably need to ad .get() in order to get a clean array. To be precise
$.map(data.d,function (item) {
alert(item);
return { value: item }
}).get();
2. If that doesnt work, you would really have to share more data like what is the "response" function and exactly what response you are getting from the server (you could get that from the web browser's dev tools)
I have a web service that returns a list of strings.
I am trying to feed that as a datasource for my auto suggesttextbox.
here is what my webservice returns
<ArrayOfString>
<string>Air Pollutants</string>
<string>Air Facilities</string>
<string>Air Emissions</string>
<string>Air Pollution</string>
<string>Air Quality Monitoring</string>
<string>Air Piracy</string>
</ArrayOfString>
this is my jquery with ajax.
$(document).ready(function () {
$('#<%=txt_search_extantdata.ClientID%>').autocomplete({
source: function (request, response) {
$.ajax({ type: 'POST',
url: "/_layouts/Extantlibrarywebservice/getdata.asmx/GetSearchData",
data: { 'src': $("#<%=txt_search_extantdata.ClientID%>").val() },
dataType: "xml",
success: function (xmlResponse) {
response($(xmlResponse).map(function () {
return { value: $(this).text() };
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
what i am gettting output currently is like this
one single item with all strings attached
Air PollutantsAir FacilitiesAir EmissionsAir Pollution Air Quality MonitoringAir Piracy
what i want to display in out put is one string in one line
Air Pollutants
AirFacilities
Air Emissions
Air Pollution
Air Quality Monitoring
Air Piracy
I am not able to figure out what i am doing wrong any help please...
ok figured it out , your success callback should be like this :
success: function (xmlResponse) {
response($("string", xmlResponse).map(function () {
return {
value: $(this).text()
};
}));
},
because here you are getting response which contains xml node of string inside ArrayofStrings
your selector to map inside response should be like this
$("string", xmlResponse)
hope that helps !!
I am using a jQuery jTable and it gives the message first "No Data Available" before it loads the data and displays a long list of it. So is it possible to display an Ajax loader (loading.gif) first while it's loading the data in the background?
Edit #Rex: i Tried this but don't know how to implement it with the jQuery jTable success function.
This is the code I tried:
$(document).on('click', '#PlayStatisticone', function (e) {
function loadingAjax(div_id) {
var divIdHtml = $("#"+div_id).html();
$.ajax({
url: '#Url.Action("_TopPlayedTracksPermissionCheck", "ReportStatistic")',
type: 'POST',
beforeSend: function() {
$("#loading-image").show();
},
success: function (data) {
$("#"+div_id).html(divIdHtml + msg);
$("#loading-image").hide();
$(function () {
$("#PartialViewTopPlayedTracks").load('#Url.Action("_PartialViewTopPlayedTracks", "ReportStatistic")');
});
},
error: function (xhr, textStatus, exceptionThrown) {
var json = $.parseJSON(xhr.responseText);
if (json.Authenticated) {
window.location.href = '/UnAuthorizedUser/UnAuthorizedUser';
}
else {
window.location.href = '/UnAuthenticatedUser/UnAuthenticatedUser';
}
}
});
Any suggestion would be really helpful
Thanks in advance.
It worked just as I wanted... I found it from an another forum
I don't know if it's ok to post worked answers from another forum or not in here:
here's the code that worked:
$(document).ready(function () {
// DOM is ready now
$.post("<%= Url.Action("ActionThatGetsTableOnly") %>",
"",
function(data) { $("#elementToReplaceId").html(); },
"html"
);
});