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)
Related
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 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 trying to get list of user data from a web service file which is called via AJAX. Here is my code :
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript">
var param;
var resultarr;
$(document).ready(function () {
param = document.getElementById('MainCT_dtvJobVac_PIC').value;
// Load countries then initialize plugin:
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: '{keyword:' + JSON.stringify(param) + '}',
dataType: 'json',
url: 'SvcADUser.asmx/GetADUserList',
success: function (result) {
//alert(result.d)
resultarr = result.d;
}
})
// Initialize autocomplete with local lookup:
$('#MainCT_dtvJobVac_PIC').autocomplete({
source: resultarr
});
});
</script>
resultarr will output an array with this values :
[ "Administrator", "Guest", "krbtgt", "phendy" , "Genin" , "Hendra" , "andri" ]
It throws this:
TypeError: this.source is not a function [Break On This Error]
this.source( { term: value }, this._response() );
What do I need to fix here? I am struggling on this for 2 days, some help would be appreciated.
Move the autocomplete initialization inside the ajax success callback:
success: function (result) {
//alert(result.d)
resultarr = result.d;
$('#MainCT_dtvJobVac_PIC').autocomplete({
source: resultarr
});
}
Ajax calls are asynchronous. Lets examine your code:
$.ajax({ .... } ); // (1)
$('#MainCT_dtvJobVac_PIC').autocomplete({ ... } ) // (2)
The autocomplete initialization (2) occurs after calling the service (1), but it is unclear if the AJAX request has succeeded and returned the response. There is a great chance that you are initializing the autocomplete with empty or undefined data - when the connection is slow, or it fails for some reason, the success callback might not get executed at the point of setting the autocomplete (2). The correct way to do this is to initialize the autocomplete in the AJAX callback, because then the response data is guaranteed to be present:
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: '{keyword:' + JSON.stringify(param) + '}',
dataType: 'json',
url: 'SvcADUser.asmx/GetADUserList',
success: function (result) {
resultarr = result.d;
$('#MainCT_dtvJobVac_PIC').autocomplete({
source: resultarr
});
}
})
I have the following code to retrieve departments names from db I have problem formatting CSS of data like background and font color
<script type="text/jscript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/AjaxLoad.asmx/GetBrands",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function(data) {
var datafromServer = data.d.split(":");
$("[id$='tbBrands']").autocomplete({
source: datafromServer
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
</script>
<div id="ajaxbrands">
<input id="tbBrands" runat="server" />
</div>
Any idea how to add text, like <p > or <div> to each list item?
I can think on 2 options:
1.Add it in your php code (like rdlowrey aadvised),
for instance:
$query = mysql_query("SELECT * FROM brands");
while($brand = mysql_fetch_array($query))
{
echo "<p>".$brand['name']."</p>";
}
2.Use jquery to do it.
"Split" converts your string to an array of sub-strings.
You should edit the autocomplete function so it will add each sub-string the desirable code. Add the function's code for more help.
Well, i assume you are using .NET, so, i wont mess around with server side code.
You can add this to your success callback function:
success: function(data) {
var datafromServer = data.d.split(":");
for(var item in datafromServer){
datafromServer[item] = '<p class="whatever">' + datafromServer[item] + '</p>';
}
$("[id$='tbBrands']").autocomplete({
source: datafromServer
});
},
The for loop added will surround every item in the array, with a p, or div, or whatever.
$(function () {
$("#tbNominalAccounts").autocomplete({
source: function (request, response){
$.ajax({
url: "TestPage3.aspx/GetUserNominalAccounts",
type:"POST",
datatype:"json",
data :{ searchText : request.term},
success: function(data)
{
response(
$.map(data, function(item)
{
return { label: item.NominalAccount, value:item.NominalAccount, id:item.NominalAccount}
}))
}
})
}
});
});
Added breakpoints and it hits the ajax call but when i put a breakpoint on the method GetUserNominalAccounts it doesent even reach it!! Any ideas of why its not posting?!
I have a textbox with an ID of #tbNominalAccounts just for background information
Reformat your data like so:
pString = '{"searchText":"' + request.term + '"}';
$.ajax({
data: pString,
...
and your server side code should have been properly "decorated" to allow page access.
Thought I would add some code from a working sample using asp.net: you might need this converter for generic handling of the asp.net data:
dataType: "jsond",
type: "POST",
contentType: "application/json",
converters: {
"json jsond": function(msg)
{
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
EDIT: And for the use of the return value:
focus: function(event, ui)
{
return false; // return "true" will put the value (label) from the selection in the field used to type
},
try putting a contentType in the ajaxRequest:
contentType: "application/json; charset=utf-8",
I've noticed that when using jQuery Ajax the default content Type application/x-www-form-urlencoded doesn't work well enough.