Wrong to use AJAX? - ajax

I have a view(MVC3) that users place orders from. The view is bound to a model that i use to display modelitems from. There are two functionalities on this view. First you enter the customers details and then you choose the items the user has ordered. This is the code i´m using to build another model to be sent back to serverside:
var modelItems = {
ModelID: [],
Amount: []
};
var serviceModel = {
Name: $.trim($('#name').val()),
Customernumber: $.trim($('#customernumber').val()),
Address1: $.trim($('#address1').val()),
Address2: $.trim($('#address2').val()),
Zipcode: $.trim($('#zipcode').val()),
City: $.trim($('#city').val()),
Country: $.trim($('#country').val()),
Phone: $.trim($('#phone').val()),
Mobile: $.trim($('#mobile').val()),
Email: $.trim($('#email').val())
};
$('div.modelSpan').each(function (i) {
var textBox = $(this).children();
var value = $(textBox).val();
if (value != '0' && value != '') {
var modelID = $(textBox).attr('name');
modelItems.ModelID.push(modelID);
modelItems.Amount.push(value);
}
});
var accessory = {
ModelItems: modelItems,
ServiceModel: serviceModel
};
$.ajax({
url: '/Site/Order', //Renamed sec reasons
type: "POST",
data: JSON.stringify(accessory),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (ordernumber) {
window.location.href = "/Site/OrderInfo/" + businessAB + "/" + ordernumber;
},
error: function () {
alert('error');
}
});
Cool thing in MVC3 is that my accessory automatically binds to my model on serverside called AccessoriesModel. On callback success i´m setting new href to a receipt site to show user what has been created. This all works but my issue is that i would like the receipt view(OrderInfo) to be returned from my controller that receives the [httppost] and not setting new href. Is there a way to do this? This is easy when using regular form submit but because the values for my model dont come from one form it complicates things. Maybe I shouldn´t use AJAX?

You could use knockout JS with Ajax and render your pages with a mixture of JavaScript objects and regular html.

Related

ASP.NET Core 2.2 Razor Pages - AJAX Call to page model not returning data

I am new to AJAX and cant even get the basics to function correctly.
I run an AJAX call from within a function in the javascript section from razor page but I cannot get the required string value to be returned.
The result I get in the alert box simply shows the HTML layout of the razor page as the message, as opposed to the actual string I want to return. I've spent hours trying to incorporate a X-CSRF-TOKEN in the header, but this makes no difference. I'm not sure the anti forgery token is required here and therefore the issue is before this step.
Razor Page:
$.ajax({
type: "GET",
url: "/Maps?handler=CanvasBackgroundImage",
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
Page Model:
public JsonResult OnGetCanvasBackgroundImage()
{
var result = "test message";
return new JsonResult(result);
}
Below is the code that is now working for me. Thanks for everyone's input.
Razor Page (script section):
function getMapBackgroundImagePath() {
// Get the image path from AJAX Query to page model server side.
$.ajax({
type: "GET",
url: "/Maps/Create?handler=MapBackgroundImagePath",
contentType: "application/json",
data: { imageId: imageId, }, // Pass the imageId as a string variable to the server side method.
dataType: "json",
success: function (response) {
copyText = response;
// Run the function below with the value returned from the server.
renderCanvasWithBackgroundImage();
},
});
}
Page model:
public JsonResult OnGetMapBackgroundImagePath(string imageId)
{
// Get the image full path where the id = imageId string
int id = Convert.ToInt32(imageId);
var imagePath = _context.Image.Where(a => a.ID == id)
.Select(i => i.ImageSchedule);
// return the full image path back to js query in razor page script.
return new JsonResult(imagePath);
}

Multiple Ajax PUTs in Laravel 4 Giving Errors

I am updating my Model through a resource controller via jQuery Ajax Put. No problems at all the first time. This works fine:
$(".addNest").click(function() {
var nid = msg; //once the LI is added, we grab the return value which is the nest ID
var name = $('.nestIn').val();
if(name == '') {
$("textarea").css("border", "1px solid red");
}else {
$.ajax({
type: 'PUT', // we update the default value
url: 'nests/' + nid,
data: {
'name': name
},
success: function(msg) {
alert(msg)
window.location.replace('nests/' + nid ); //redirect to the show view
}
});
}
});
Later in a separate code block, I try to call the PUT again like this:
$(".nestEdit").click(function() {
$(".nestEdit").hide();
var name = $('.nestName').data("name");
var nid = $('.nestName').data("id");
$(".nestName").html("<textarea class='updateNest'>"+ name +"</textarea> <span><a href='#' class='btn btn-mini nestUpdate'><i class='icon-plus'></i> Update</a></span>");
$(".nestUpdate").click(function() {
var updatedName = $('.updateNest').val();
$.ajax({
type: 'PUT', // we update the default value
url: 'nests/' + nid,
data: {
'name': updatedName
},
success: function(msg) {
alert(msg) // showing the error here
location.reload( ); //refresh the show view
}
});
});
The 'updatedName' values and the 'nid' values are passing fine when I 'alert' them. When I view the return for the first PUT it comes back fine. However, when I view the return for the second PUT I get this:
{"error":{"type":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException","message":"","file":"\/Applications\/MAMP\/htdocs\/n4\/bootstrap\/compiled.php","line":8643}}
Anyone have some insights here? As you can tell, I am trying to do an inline edit. I have tried to wrap everything into a function but still not helping...
Laravel does not use PUT and DELETE natively since it is not supported in all browsers, you need to send a POST request with '_method' set to either put or delete.
$.ajax({
type: 'POST',
url: 'nests/' + nid,
data: {
'name': updatedName,
'_method': update
},
success: function(msg) {
alert(msg) // showing the error here
location.reload( ); //refresh the show view
}
EDIT: Ajax request do support PUT AND DELETE.
In your JavaScript code, for the inline editing, you are not making proper use of $.
If you click on .nestEdit, it's inner function should not be calling it by name, provided you have multiple objects of the same class on that page. This is why you get the error. Instead of sending the nest ID, it's sending an array object, which your Laravel Router will not pick up, because it is more than likely not defined.
Simply put, you should not be doing this:
$(".nestEdit").click(function() {
$(".nestEdit").hide();
...
You should be making a call to this:
$(".nestEdit").click(function() {
$(this).hide();
...
So, for every .nestEdit within the inner function, you need to call for this instead.

jquery autocomplete using mvc3 dropdownlist

I am using ASP.NET MVC3 with EF Code First. I have not worked previously with jQuery. I would like to add autocomplete capability to a dropdownlist that is bound to my model. The dropdownlist stores the ID, and displays the value.
So, how do I wire up the jQuery UI auto complete widget to display the value as the user is typing but store the ID?
I will need multiple auto complete dropdowns in one view too.
I saw this plugin: http://harvesthq.github.com/chosen/ but I am not sure I want to add more "stuff" to my project. Is there a way to do this with jQuery UI?
Update
I just posted a sample project showcasing the jQueryUI autocomplete on a textbox at GitHub
https://github.com/alfalfastrange/jQueryAutocompleteSample
I use it with regular MVC TextBox like
#Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", #class = "ui-widget TextField_220" })
Here's a clip of my Ajax call
It initially checks its internal cached for the item being searched for, if not found it fires off the Ajax request to my controller action to retrieve matching records
$("#SearchField").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in entityCache) {
response(entityCache[term]);
return;
}
if (entitiesXhr != null) {
entitiesXhr.abort();
}
$.ajax({
url: actionUrl,
data: request,
type: "GET",
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "json",
success: function (data) {
entityCache[term] = term;
response($.map(data, function (item) {
return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode };
}));
}
});
},
minLength: 3,
select: function (event, result) {
var id = result.item.id;
var code = result.item.code;
getEntityXhr(id, code);
}
});
This isn't all the code but you should be able to see here how the cache is search, and then the Ajax call is made, and then what is done with the response. I have a select section so I can do something with the selected value
This is what I did FWIW.
$(document).ready(function () {
$('#CustomerByName').autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
},
});
},
select: function (event, ui) {
$('#CustomerID').val(ui.item.id);
},
minLength: 1
});
});
Works great!
I have seen this issue many times. You can see some of my code that works this out at cascading dropdown loses select items after post
also this link maybe helpful - http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx

How to call partial view through ajax in mvc3

I need to call a partial view through ajax. I have tried the following, but I am not sure how to complete it.
$("#UserName").change(function () {
var userid = $("#UserName").val();
var ProvincialStateID = $("#State").val();
var Hobbyid = $("#Hobby").val();
var Districtid = $("#DistrictNames").val();
var Homeid = $("#Hobbyhome_EstablishmentId").val();
var urlperson = '#Url.Action("FetchPersonByUserName")';
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
success: function (data) {
//Dont know what to write here
});
});
Here is the function that I have written in my Controller:
[HttpPost]
public ActionResult FetchPersonByUserName(int userid,int stateid,int districtid,int homeid,int Hobbyid)
{
//Code to fetch the data in the partial using all parameters
return PartialView("_LearnerAssociationGridPartial", list);
}
When I click on a dropdown the ajax gets called and I want the function which is called through ajax to redirect it to the partial view. Please help me because currently I am not able to display my partial view
What you need is something like
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid,
stateid: ProvincialStateID,
hobbyid: Hobbyid,
districtid: Districtid,
homeid: Homeid },
success: function (data) {
var result = data;
$('targetLocation').html(result);
}
});
it is recomended to not use data straight from variable but you can.
Now target location is where you want the result to be displayed to.
See more information in here:
http://api.jquery.com/jQuery.ajax/
As to slow fetching data, try optimalize your query
Update
For nhibernate running slow, try http://www.hibernatingrhinos.com/products/nhprof which is nhibernate profiler, for paid version, or try sql profiler to see what is query is beeing executed, often you can get much more that you would expect and or really slow query due to complexity of the query.
I dont understand what you mean by redirect to the parial view. Usually people use ajax and Partial views to get part of a page without a page refresh ( you might have seen this kind of behaviour in this site/facebook/twitter etc..) So i guess you probably want to show the data you are fetching asynchronosly to be shown in a part of your current page. you can do that in your success handler
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
success: function (data) {
$("#divUserInfo".html(data);
}
});
Assumung you have a div with id divUserInfo in your current page.
If you really want to redirect after the ajax post, you can do it like this.
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
success: function (data) {
window.location.href="Why-I-need-Ajax-Then.php";
}
});
Personally, I dont use HttpPost (both in client and server) If it is a method to GET some data. I simpy use the jquery get or load.
$.get("yourUrl", { userid: userid, stateid: ProvincialStateID } ,function(data){
$("#divUserInfo".html(data);
});

Handling objects and routes with MVC3/Razor?

I have a geo collection that contains items like:
[state name]
[city], [state]
[country]
A text box is available for a user to begin typing, and a jQuery autocomplete box fills displays possible options.
The URL structure of the post request will depend on which was selected from the collection above, ie
www.mysite.com/allstates/someterms (if a country is selected)
www.mysite.com/city-state/someterms (if a city, state is selected)
www.mysite.com/[state name]/someterms (if a state is selected)
These are already defined in my routes.
I was initially going to add some logic on the controller to determine the appropriate URL structure, but I was thinking to simply add that as an additional field in the geo table, so it would be a property of the geo collection.
Here is my jQuery function to display the collection details when, fired on keypress in the textbox:
$(function () {
$("#txtGeoLocation").autocomplete(txtGeoLocation, {
source: function (request, response) {
$.ajax({
url: "/home/FindLocations", type: "POST",
dataType: "json",
selectFirst: true,
autoFill: true,
mustMatch: true,
data: { searchText: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.GeoDisplay, value: item.GeoDisplay, id: item.GeoID }
}))
}
})
},
select: function (event, ui) {
alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
: "Nothing selected, input was " + this.value);
document.getElementById("hidLocation").value = ui.item.id;
}
});
});
What I would like is to have structure the URL based on an object parameter (seems the simplest). I can only seem to read the parameters on "selected", and not on button click.
How can I accomplish this?
Thanks.
To resolve this, I removed the select: portion from the Javascript, and added the selected object parameters in the MVC route sent to my controller.

Resources