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 !!
Related
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)
My full Calendar show data correctly using ajax . so i want to change the data on previous button click. But the button click function not working and how can i pass the data as parameter on previous and next button click
<script src="../assets/global/plugins/fullcalendar/lib/moment.min.js"></script>
<script src="../assets/global/plugins/fullcalendar/lib/jquery.min.js"></script>
<script src="../assets/global/plugins/fullcalendar/fullcalendar.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json",
data: "{}",
url: "attendance-full.aspx/GetEvents",
dataType: "json",
success: function (data) {
$('div[id*=calendar1]').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: $.map(data.d, function (item, i) {
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.title = item.EventName;
return event;
}), eventRender: function (event, eventElement) {
if (event.ImageType) {
if (eventElement.find('span.fc-event-time').length) {
eventElement.find('span.fc-event-time').before($(GetImage(event.ImageType)));
} else {
eventElement.find('span.fc-event-title').before($(GetImage(event.ImageType)));
}
}
},
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
$('div[id*=calendar1]').show();
//below code not working
$(".fc-prev-button span").click(function () {
alert("Hai");
})
});
My console is error free .
$(".fc-prev-button span").click(function () { runs before your calendar is created (because you wait to create the calendar until ajax has run, and ajax is asynchronous). Therefore there is no button for your code to bind the event to.
Simply move
$(".fc-prev-button span").click(function () {
alert("Hai");
});
to the end of your ajax "success" function.
N.B. I would also suggest that you re-consider how you're getting your events. Currently you fetch all events into the calendar, and the calendar cannot be displayed until the events are fetched. If your application is live for a long time, and builds up a lot of historical events, consider what will happen after a few years when there is a long list of events - it will take a long time to load them all, with no calendar on screen, and unless your situation is unusual, then probably no-one will look at anything from a long time ago, so it's a waste of time to load them.
FullCalendar is actually designed to work in a way that fetches only the events that are needed for the view and date range currently being displayed. So you fetch the minimum required events. If the user changes the view or date to something else, fullCalendar requests more events from the server, and sends it the date range required. This is usually much more efficient.
In your case you could re-write it something like this snippet below. Bear in mind you'd also have to change your GetEvents server method so that it filters the list of events by the dates supplied. I can't see that code so I can't advise exactly what you would need to do, but hopefully it will be fairly simple to add a couple of extra parameters and add a clause to your database query to compare the dates.
$(document).ready(function() {
$('div[id*=calendar1]').show();
$('div[id*=calendar1]').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: function(start, end, timezone, callback) {
$.ajax({
type: "POST",
contentType: "application/json",
data: '{ "start": "' + start.format("YYYY-MM-DD") + ', "end": ' + end.format("YYYY-MM-DD") + '}',
url: "attendance-full.aspx/GetEvents",
dataType: "json",
success: function(data) {
var events = $.map(data.d, function(item, i) {
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.title = item.EventName;
return event;
});
callback(events);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
},
eventRender: function(event, eventElement) {
if (event.ImageType) {
if (eventElement.find('span.fc-event-time').length) {
eventElement.find('span.fc-event-time').before($(GetImage(event.ImageType)));
} else {
eventElement.find('span.fc-event-title').before($(GetImage(event.ImageType)));
}
}
},
});
$(".fc-prev-button span").click(function() {
alert("Hai");
});
});
See https://fullcalendar.io/docs/event_data/events_function/ for more details of the event feed function.
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.
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"
);
});
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
});
}
})