JQuery AutoComplete updating multiple fields ASP.NET - asp.net

I'm trying to use the AutoComplete feature of JQuery to update multiple fields on an ASP.NET web page. The individual textbox is functioning perfectly, but I cannot figure out how to update multiple textboxes on the page once the user selects.
I've read many suggestions here that state I need to implement a result handler, but my intellisense is not showing that as an option, and IE I get a JS error saying that the object doesn't support this method.
I am linking to jquery-1.4.2.min.js and jquery-ui-1.8.5.custom.min.js
Here's my code:
$(function () {
$("#Street1").autocomplete({
source: function (request, response) {
$.ajax({
url: "/address/FindAddress", type: "POST", dataType: "json",
data: { startAddress: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.DisplayText, value: item.ValueText, id: item.ID }
}))
}
})
} /* End source: function */
})
.result(function (event, data, formatted) {
$("#Street2").val("test");
})
/* end Autocomplete */
}); /* Function */

In this case you'd want the select handler, like this:
$("#Street1").autocomplete({
source: function (request, response) {
$.ajax({
url: "/address/FindAddress", type: "POST", dataType: "json",
data: { startAddress: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.DisplayText, value: item.ValueText, id: item.ID }
}));
}
});
},
select: function( event, ui ) {
$("#Street2").val(ui.item.label); //or ui.item.value
}
});
I'm not sure if you want the label, value or id in there, just use ui.item.whatever. Using select, whatever a value is chosen you can populate the #Street2 field as well.

view the source of this example, it's exactly what you want (look at the select method) : http://jqueryui.com/demos/autocomplete/#custom-data
Also, it's JavaScript, don't rely on intellisense.
EDIT: I pasted the wrong link

Related

Ajax data not passing to controller

I have a problem where the data in the ajax isn't passing the sessionStorage item. I have tried using JSON.stringify and added contentType: 'application/json' but still it's not passing. Can this be done using POST method? Also, I have debugged and returned those sessionStorages, hence the problem isn't because the sessionStorge doesn't contain data.
Here my function:
function functionA() {
$.ajax({
url: URLToApi,
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
data: {
access_token: sessionStorage.getItem('pageToken'),
message: $('#comment').val(),
id: sessionStorage.getItem('pageId')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}
Check below things in Controller's action that
there should be a matching action in controller
name of parameter should be same as you are passing in data in ajax
Method type should be same the ajax POST of the action in controller.
function AddPayment(id, amount) {
var type = $("#paymenttype").val();
var note = $("#note").val();
var payingamount = $("#amount").val();
$('#addPayment').preloader();
$.ajax({
type: "POST",
url: "/Fixed/AddPayment",
data: {
id: id,
amount: payingamount,
type: type,
note: note
},
success: function (data) {
}
});
}
Here is the working code from my side.
Check with this, and for the header part you need to get it from the Request in action
The solution to this problem has been found. The issue was the sessionStorage, hence I've passed it directly to the URL and now it working as follows:
function functionA() {
$.ajax({
url: 'http://localhost:#####/api?id=' + sessionStorage.getItem('pageId') + '&access_token=' + sessionStorage.getItem('pageToken') + '&message=' + $('#comment').val(),
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}

Fullcalendar jquery plugin loading times after selecting and inserting new events

I am using fullcalendar plugin for our users to set their available times. Now everything works fine when reloading the page and when user adds one event, but when they add another event or start selecting, the page almost frozes. I tried all the solutions I found out on Stack but nothing.
I tried calendar.fullCalendar('addEventSource', response.new_events); to add only the new events returned, but lag persist. Tried removing all the eventRender functions, but still the same result. Only thing that seems to work is when I reload the page after each event insert.
IS there any way to decrease the lag while adding new eventSource after select?
These are the parts of my calendar js code
eventSources: [{
url: '/nanny/calendar/availability/all',
type: 'GET',
success: function (response) {
},
error: function (jqXhr, textStatus, errorThrown, data) {
$(".loading-icon").hide();
console.log(jqXhr, textStatus, errorThrown, data);
},
}],
eventRender: function (event, element) {
var delete_icon = '<i style="float: right; cursor: pointer;" class="' + event.icon + '"></i>';
if (event.icon) {
element.find("div.fc-time").append(delete_icon);
}
},
eventAfterRender: function (event, $el, view) {
$(".loading-icon").hide();
var formattedTime = $.fullCalendar.formatRange(event.start, event.end, "HH:mm");
// if event has fc-short class, data-start value will be displayed
// remove fc-short class and update fc-time span text
if ($el.is('.fc-short')) {
$el.find(".fc-time span").text(formattedTime + " - " + event.title);
$el.removeClass('fc-short');
$el.find('.fc-title').remove();
}
},
select: function (start, end) {
//in the past so give error
if (start.isBefore(moment())) {
$('#calendar').fullCalendar('unselect');
return false;
}
//get the event data
eventData = {
start: moment(start).format('YYYY-MM-DD HH:mm:ss'),
end: moment(end).format('YYYY-MM-DD HH:mm:ss')
};
if (eventData) {
if (eventData) {
$.ajax({
type: "POST",
url: "/nanny/calendar/store",
data: eventData,
dataType: "JSON",
success: function (response) {
console.log(response);
swal({
title: "Yay",
text: response.msg,
type: "success",
showCancelButton: false,
confirmButtonColor: "#e36159",
confirmButtonText: "CLose",
closeOnConfirm: false
});
calendar.fullCalendar('addEventSource', response.new_events);
},
error: function (jqXhr, textStatus, errorThrown, data) {
console.log(jqXhr, textStatus, errorThrown, data);
}
});
}
}
},
EDIT
Here's the video.
Lag example
A single event should be added using the renderEvent method. Create the event struct using the appropriate input and pass it to the renderEvent method.
$.ajax({
type: "POST",
url: "/nanny/calendar/store",
data: eventData,
dataType: "JSON",
success: function (response) {
var myEvent =
{
id: response.ID,
title: response.TITLE,
start: eventData.start,
end: eventData.end,
};
$( "#calendar" ).fullCalendar( "renderEvent", myEvent );
}
});
According to the documentation (https://fullcalendar.io/docs/event_data/Event_Object/) the start, end, and title attributes are required. If you are not collecting a title you can hardcode it to something such as "Event".
If you are updating your events in a db and want to allow your users to modify an event (ie. drag and drop, resize, etc.) without refreshing/reloading the calendar you must also provide the id attribute. This can be the unique key assigned to the meeting when stored in the database. You will want to pass this value back in the ajax response. If this functionality is not necessary, then you can ignore the id attribute.
**refetchEvents recall the function CalendarApp.prototype.init and refresh the calendar **
$.ajax({
url: "BASE_URL",
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json"
},
type: "POST",
data: JSON.stringify(dataEvent),
dataType: "json",
contentType: "application/json",
success: function(data) {
window.swal({
title: "Checking...",
text: "Please wait",
buttons: false,
timer: 2000
});
$("#calendar").fullCalendar("refetchEvents",dataEvent);
}
});

Asynchronous ajax call causing issue in KnockOutjs

I have a button on click of that i am calling something like :
ViewModel:
self.MyArray = ko.observableArray();
self.remove = function(c) {
ko.utils.arrayForEach(c.sData(), function(ser) {
if (ser.Check() == true) {
self.MyArray.push(service);
count++;
}
});
if (count) {
$.ajax({
url: "/api/LoadCustomer/?reason=" + reason,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(self.MyArray),
success: function(data) {
ko.utils.arrayForEach(self.MyArray(), function(removedata) {
c.sData.remove(removedata);
});
}
});
self.MyArray([]);
}
};
If i include async:false in my ajax call i get everything fine but if i didn't include async (its default property is true) i dont know somehow in my success function of ajax call self.MyArray() remains Empty but its not the case if i keep it false (Awkward).
Sometimes i fear like if i have series of ajax calls with async:true while loading into a observable array(OnLoad) there may be a slight chance of misplacement of data .
Help me understand .
The reason your observable array MyArray is empty sometimes is because this line of code self.MyArray([]); executing before the ajax call is done. How about this instead -
if (count) {
$.ajax({
url: "/api/LoadCustomer/?reason=" + reason,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(self.MyArray),
success: function (data) {
ko.utils.arrayForEach(self.MyArray(), function (removedata) {
c.sData.remove(removedata);
});
},
complete: function() { // complete fires after success and error callbacks
self.MyArray([]); // empty the array no matter what happens (error or success)
}
});
}

jquery Post does not work in asp.net mvc 3?

I just copied some code from an asp.net mvc 2 app which works. Now i am trying it in asp.net mvc 3 and it does not call the save method on the controller?
controller:
[HttpPost]
public JsonResult save(string inputdata)
{
return Json(new { Result = string.Format("From the controller - you have clicked the GO-button ! ") }, JsonRequestBehavior.AllowGet);
}
view:
<button id="but">go</button>
<div id=result></div>
<script type="text/javascript">
$(document).ready(
$("#but").click(
function () {
$.ajax({
url: "/Home/save",
dataType: "json",
type: 'POST',
data: "test",
success: function (result) {
$("#result").html(result.Result);
}
});
}
)
);
</script>
You are not passing the data correctly. The action argument is called inputdata. So you should use this same name in the data hash of the AJAX request:
$.ajax({
url: '/Home/save',
dataType: 'json',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
Also never hardcode urls in your javascript, always use url helpers or your application will simply stop working when you deploy due to the possibility of having a virtual directory name:
$.ajax({
url: '#Url.Action("save", "home")',
dataType: 'json',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
Another issue that you have with your code is that you are not canceling the default action of the button meaning that if this is an action link or a submit button the AJAX request might never have the time to execute before the browser redirects.
Also you don't need to specify the dataType to JSON as jQuery is intelligent enough to deduce this from the Content-Type response header sent from the server.
So the final version should look something along the lines of:
<script type="text/javascript">
$(function() {
$('#but').click(function () {
$.ajax({
url: '#Url.Action("save", "home")',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
return false;
});
});
</script>

Fire a controller action from a jQuery Autocomplete selection

I have a jQuery autoselect box displaying the correct data. Now I would like to fire an ASP.NET MVC 3 controller when an item is selected. The controller should then redirect to a View. Here's my jQuery autocomplete code (I'm sure something is missing in the 2nd Ajax call, but I haven't found it yet):
<script type="text/javascript">
$(function () {
$("#Client").autocomplete({
source: function (request, response) {
$.ajax({
url: 'Entity/GetClientAutoComplete', type: 'POST', dataType: 'json',
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item, value: item };
}))
}
})
},
minLength: 1,
select: function (event, ui) {
$.ajax({
url: 'Entity/GetApplicationsByName/' + ui.item.value, type: 'POST'
})
}
});
});
</script>
And here's the controller I'm trying to call:
public ActionResult GetApplicationsByName(string id)
{
ViewBag.Client = id;
var apps = _service.GetDashboardByName(id);
return View("Dashboard", apps.ToList());
}
When I watch the Ajax call fire in Firebug, I see the correct URL configuration, but nothing else happens. It's acting as though it wants to load something rather than send something. I'm confused. Thank you for any guidance.
Well you sent an id by POST to the GetApplicationsByName controller and the controller is sending back the view.
If you want redirection, you can use the following:
select: function (event, ui) {
window.location.href = 'Entity/GetApplicationsByName/' + ui.item.value;
}

Resources