ASP.NET MVC3 & jquery.getJSON not making request - asp.net-mvc-3

I am working on a MVC 3 site and everything was working until I util I upgraded to jquery1.7.1 using nuget. Now my $.getJSON calls are not making the request to the server. Fiddler does not show a request being made back to the server and code before and after the $.getJSON is executing. Any ideas would be appreciated.
Here is a sample client script:
var srvBaseUrl = "http://localhost:15627/Home/";
$.getJSON(srvBaseUrl + "GetInfo", { 'id': 1 }, function (allData) {
alert(allData);
});
and the corresponding server code:
[HttpGet]
public ActionResult GetInfo(int id)
{
return Json(id, JsonRequestBehavior.AllowGet);
}
I tested that the server code works building up the request in Fiddler.

I had a similar problem, it turned out that JQuery was caching the results. This would explain your comments above that it started working after you made a change.
If you have a look at http://api.jquery.com/jQuery.getJSON/, you will see that $.getJSON is just shorthand for
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
If you use the $.ajax instead of the shorthand $.getJSON you can disable caching using the cache parameter, meaning you should be able to replace your code with:
$.ajax({
url: srvBaseUrl + "GetInfo",
dataType: 'json',
data: { 'id': 1 },
success: function (allData) { alert(allData); },
cache: false
});

Nuget is not going to update your Views/Shared/_Layout.cshtml file with the updated reference to the latest version of jQuery installed. You will need to update this yourself:
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"> </script>
EDIT
Assuming that is all in order like you said, make sure your getJSON call is inside a document ready function as it work as-is for me. I would however change how you are building the Url to use the helper method instead:
<script type="text/javascript">
(function ($) {
$.getJSON('#Url.Action("GetInfo")', { 'id': 1 }, function (allData) {
alert(allData);
});
})(jQuery);
</script>
This tested out fine in a stock ASP.NET MVC3 Internet Application template project using your controller action as-is.

Related

Using form data to dynamically construct url using ajax

I have the following ajax code that takes in 3 variables and passes them to a php file, and this is all fine and dandy. I want to do a redirect using the value stored in one of these variables. I figured I could just do window.location.href = within the success in the ajax call, but for some reason, it doesn't seem to respond to the click, and simply does nothing.
Here is the ajax function, hope y'all can help!
$("#findItem").click(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$.ajax({
type: 'get',
url: 'http://plato.cs.virginia.edu/~aam3xd/cabbage/closestBuildingWeb.php',
data: {
foodItemId: $('#foodItem').val(),
sentLongitude: position.coords.longitude,
sentLatitude: position.coords.latitude
},
success: function(data){
//$('#answer').html(data);
//the following line doesn't seem to be executing....
window.location.href = foodItemId+"/"+sentLatitude+"/"+sentLongitude;
}
});
});
I think you should use your url into that window.location
window.location.href = "www.example.com/"+foodItemId+"/"+sentLatitude+"/"+sentLongitude;

Using jQuery AJAX to Invoke Rails Server Method on Client Side

I am using Ruby on Rails, and I want to invoke a controller method as an onclick event of my pre-existing links.
I am using jQuery and AJAX to do the same. But I don't know much about AJAX.
Here is my code.
<script type="text/javascript">
$("a.browse_history").live("click", function()
{
alert("i am here");
$.ajax({
url: "/user_profile_controller.rb/save_user_history",
type: 'PUT'
});
});
</script>
In user_profile_controller.rb:
def save_user_history
$doc_list << "hello hi"
end
And my link is:
Click here
But this is not working..
Any solutions would be appreciated.
Your URL looks wrong. Run rake routes to get a list of existing routes in your app.
Should be something like
url: "/user_profile/save_user_history"
or
url: "/user_profiles/save_user_history"
Thank you for your reply Stefan.
I changed my code like this:
<script type="text/javascript">
function u_profile(user,url,query)
{
$.ajax({
type: 'POST' ,
url: "http://localhost:3000/user_profiles",
data : {
user_profile : {
user_id : user ,
query_term : query,
visited_url: url
}
} ,
success: function(data){
alert(data);
}
});
};
</script>
And i am invoking it as onclick event of link.
It full fills my requirement of creating an object in database with passed data.

jQuery Ajax request in Grails

How to use jQuery to make Ajax request in Grails pages?
How to setup a URL hitting a method on Grails Controller? Let's say controller:'airport', action:'getJson' and input to the action is 'iata'.
I am able to set static url as http://localhost:8080/trip/airport/getJson but not able to figure out how to pass input for iata specifically.
I am fairly new to Grails and following IBM's 'Mastering the Grails' tutorial series. Do suggest me some good tutorial on using jQuery with Grails.
use the $.ajax method in jquery
$.ajax({
url:"${g.createLink(controller:'airport',action:'getJson')}",
dataType: 'json',
data: {
iata: '.............',
},
success: function(data) {
alert(data)
},
error: function(request, status, error) {
alert(error)
},
complete: function() {
}
});
It's:
$.ajax({
url: '/trip/airport/getJson',
data: {paramName: 'iata'}
});
use your parameter name, that you're expecting in action, intead of paramName, that i've used.

jQuery Autocomplete throws 401 - Unauthorised error while calling MVC 3 controller action method

I am getting "401 - Unauthorised" error in jQuery Autocomplete control in MVC3 application (.net framework v4.0.30319) which is deployed on a server containing IIS 7.5
Controller: (SearchSuggestController)
[HttpGet]
public JsonResult SuggestByEmployeeId(string Id)
{
var suggestions = from a in Context.Employees
where a.EmployeeId.Contains(Id)
select new
{
a.EmployeeId,
a.FirstName,
a.LastName
};
return Json(suggestions, JsonRequestBehavior.AllowGet);
}
jQuery: (Autocomplete)
$(function () {
$("#IDFilter").autocomplete({source: function (request, response) {
$.ajax({
url: "/SearchSuggest/SuggestByEmployeeId",
type: "POST",
dataType: "json",
data: { Id: request.term },
error: function (XMLHttpRequest, status, error) {
alert("Error status:(" + status + ") error:(" + error + ")");
},
success: function (data) {
response($.map(data, function (item) {
return { label: item.EmployeeId, value: item.EmployeeId,id: item.EmployeeId };
}));
}
});
},
minLength: 3,
autoFocus: true,
select: function (event, ui) {
$("#IDFilter").val(ui.item.value);
}
});});
jQuery is calling url: "/SearchSuggest/SuggestByEmployeeId" i.e. SearchSuggest controller's
SuggestByEmployeeId action.
Search.cshtml:(View)
#using (Html.BeginForm("BasicSearch", "Employee"))
{
#Html.Label("Employee Id:")
#Html.TextBox("IDFilter")
<input type="submit" value="Search" />
}
BasicSearch action method in Employee controller is working fine if valid EmployeeID is entered in "IDFilter" and clicked on Search button.
Autocomplete is showing expected results when i run the code through visual studio IDE. After publishing and Bin Deploying of this code to IIS 7.5 is throwing 401-Unauthorized error. The application is hosted under Default Web Site in IIS.
Anybody has any idea what is going wrong here?
You are AJAX POST to the action, but your action only accepts GET ?
Does your controller (or base controller) have the [Authorize] attribute?
I think i have got a solution.
Digging into jQuery using IE8 Developer Tools
On host server, the autocomplete XMLHttpRequest is trying to search for Request URL "http://localhost:80/SearchSuggest/SuggestByEmployeeId?Id=123"
But my application is hosted as "MyApp" under Default Web Site, so the URL should be like "http://localhost:80/MyApp/SearchSuggest/SuggestByEmployeeId?Id=123"
Hence i have updated the URL to url: "/MyApp/SearchSuggest/SuggestByEmployeeId"
After this change Autocomplete is fetching the expected results. 401 error is gone.
Probably in host environment, i will have to setup a new web site and bin deploy my MVC application under that.
This way i don't need to make this modification in jQuery everytime.
If anyone has got a better solution, please suggest.
To avoid issues with relative paths, rather than hard-coding the URL, use the #URL.Action helper.
So, your old code: url: "/SearchSuggest/SuggestByEmployeeId",
should become: url: '#Url.Action("SuggestByEmployeeId", "SearchSuggest")'
Good luck!

Umbraco - load content with Ajax

I'm new to Umbraco and only started to figure out the ins and outs of it.
Anyway, I've figured out on my own the way document types, macros, templates, xslt files work and am now trying to do some other stuff. Namely I need to load a document content using an AJAX call. It's basically a panel with a menu (dynamic, which I figured out how to load) that loads content depending on the menu item selected (the documents loaded with the menu). What I need to figure out is how to get that content using an AJAX call since I don't want to reload the page.
Is this done using Umbraco BASE extensions or am I off in my thinking here? If so, how exactly? Do I just write a class and then stitch together an HTML string in a method?
Thanks for the help
You can use rest methods. For this you have to edit restExtensions.config on the config folder.
Ajax Call
$.ajax({
type: 'POST',
url: "/base/AliasName/GetData.aspx",
data: {
},
success:
function (data) {
}
});
restExtensions.config
<ext assembly="/DllName" type="Namespace.ClassName" alias="AliasName">
<permission method="GetData" returnXml="false" allowAll="true" />
</ext>
Yup this is exactly the scenario that Base is used for.
You can find documentation on using base here:
http://our.umbraco.org/wiki/reference/umbraco-base/simple-base-samples
For the consumption of base via AJAX then JQuery is the answer.
http://api.jquery.com/jQuery.ajax/
Here's a hacked together example (not tested code):
$(document).ready(function ()
{
$(".buttonListener").click(function ()
{
$.ajax(
{
url: '/Base/TestAlias/Hello.aspx',
success: function (data, textStatus, XMLHttpRequest)
{
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert("Ka pow!");
}
});
return true;
});
Ajax call using umbraco in MVC
$('#TestClick').on('click',function(){
$.ajax({
url: 'umbraco/surface/Home/TestPage',
type: 'POST',
data: { id:10001},
success: function (data) {
alert(data);
},
error: function () {
alert("error");
}
});
})

Resources