Ajax not recognized in JQuery file - c#

I uploaded to GitHub days ago an MVC project, I've downloaded it again, and want to set some new functions using JQuery Ajax, but now when I'm trying to do something like this:
$("#btnTrigger").click(function () {
$.ajax({
type: "get",
url: "/Orders/MyJson/"
}).success(function (result) {
alert(result.testing)
})
});
An exception is thrown: Object doesn't support property or method 'success'.
I think that something is wrong with JQuery, when I'm going to write $.ajax inside a function the keyword ajax is not displayed, instead Intellisense shows other keywords like attr etc. Normally the keyword ajax is displayed from Intellisense.
I've been trying uninstaling and installing JQuery again and nothing happened, I've check the BundleConfig class to check if the JQuery files are added and they are there, I've installed unobtrusive ajax and have added it to BundleConfig class too and still the problem continues... What it could be??

Try it like this, putting the success inside ajax definition
$("#btnTrigger").click(function () {
$.ajax({
type: "get",
url: "/Orders/MyJson/",
success: {
function (result) {
alert(result.testing);
}
}})})

Related

launch an excel file from a Controller using JavaScript

What do I need to do to open an excel file via controller action using javascript?
I tried the this way but it does not open the file.
JavaScript Function:
function ExcelExport() {
var link = '/Report/ExcelExportData';
$.ajax({
type: 'POST',
url: link,
success: function (result) {
},
error: function (result) {
}
});
};
Controller Action:
public ActionResult ExcelExportData()
{
return File("~/Reports/ExcelFile.xlsm", Server.UrlEncode("~/Reports/ExcelFile.xlsm"));
}
Actually, you can't open files directly from ajax callback responses. You could try two different approaches:
Use an anchor for opening the file and get rid of the ajax request. Something like <a href="/Report/ExcelExportData"> will do.
Call window.open(link) inside your success callback. The only advantage of this approach is that it allows you to handle unexpected errors (file not found or something like that). It will perform another roundtrip to the server, though.

How does ASP.NET MVC Data Binding work without reloading webpage?

I've just started using ASP.NET MVC 4.0 to build a web application. I've been through the tutorials that explain and demonstrate View/Controller/Models, but now I'm wanting to go a step further.
Instead of having all of my pages constantly reload as users interact with my application, i'd like to learn how to make async calls to the server side to load data.
A great example of what I would like to learn how to implement is:
http://demo.aspnetawesome.com/AjaxDropdownDemo/Index
The Drop Downs are bound to each other, and the page never refreshes. Does anyone have some suggestions on where I can go to learn how to begin learning this? Also, since I am using MVC how can I use Model Binding to help make it more simple?
To Make and async calls to your action you can make ajax call as follows
Jquery Code:
var AsyncCall = function () {
$.ajax({
type: "POST",
url: "Home/Index",
data: JSON.stringify(yourData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// Success implementation
},
error: function () {
}
});
};
In Controller :
[HttpPost]
public ActionResult Index(DataType model)
{
// Implementation
return View(model);
}

Use jquery/ajax to call a c# (or any other .net) function in another project within the same solution

Does anyone know if it's possible to use jquery/ajax to call a c# (or any other .net) function in another project within the same solution?
Let's say that the solution's name is ExampleSolution , the name of the project from which I call the target function is Project.Source and the name of the target project is Project.Target,
and the name of the target function is TargetFunction().
I've tried following in an .js file in the Project.Source:
$.ajax({
url: '/ExampleSolution/Project.Target/TargetFunction',
type: 'get',
success: function (data) {
$(document.body).append(data);
}
});
Then I've modified the url-line in several ways but never succeed.
Do you have any advice?
Thank you all for your fast answers.
I found a solution for the problem and I'd like to share it just in case anybody faces the same problem in the future.
In the .js file before I call the $.ajax function I create a variable with help of window.location which points to the url to the targetfunction of the running target-project and use the variable in the ajax-function. So you don't point to another project. You point to url of running project.
Just as easy as it sounds.
Below follows the solution:
var url = window.location = 'http://localhost:13105/TargetFunction';
$.ajax({
url: url,
type: 'get',
success: function (data) {
$(document.body).append(data);
}
});
});
You can only call functions in the Code Behind because they're being registered by the web server.
If you want to have a function accessible outside the Code Behind it needs to be registered as a ASMX or WCF service.
See Creating and Consuming Your First WCF Service for setting up a WCF Service.
Once it is setup and running you can use Ajax to call the methods just like you would in the Code Behind.
$.ajax({
//Path to WCF Server and Target Method
url: "http://localhost:PORT/wcfsvc/FooService.svc/Foo",
type: 'get',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$(document.body).append(data);
}
});
See also: Consuming WCF from jQuery as JSON
The short answer is "No, it isn't possible." Front-end code (like jQuery and AJAX) run on the client's machine, but C# functions are back-end and run on the server. There's no direct connection between them.
The longer answer is "Not directly, but there are ways to do something similar." Your easiest option is to use AJAX to POST to another controller/action on your server and then process the response. This is close to what you were doing, but you were slightly off. Rather than the url being a function, the url has to be an actual url on your website. Using /Functions/CallTargetFunction as an example, you would then create a controller like this:
public class FunctionsController : Controller
{
public ActionResult CallTargetFunction()
{
return Content(TargetFunction());
}
}
Note that doing this means anyone who visits http://yoursite.com/Functions/CallTargetFunction will get the result of that function.

Jquery call to Controller of MVC: ReferenceError: url is not defined

I tried all my efforts, but just can't understand where the error lies. I searched the google also but did not find any good solution. It is not actually calling the controller/action in mvc. The same is running good in the other parts of the project.
I have a contrller "RB" under a folder "MVC", the action is defined as "SS".
and I am firing following code from my javascript file :
var sSch = function (request, response) {
var t = request.RF.substring(0, 1);
var d = new Date(request.RNR);
$.ajax({
url: "/MVC/RB/SS",
type: "POST",
dataType: "json",
data: {
_rId: request.ReportId,
_date: d.toString(),
_fcy: t
},
success: function (data) {
alert('Success');
},
error: function (data) {
alert('Error');
}
});
};
I am calling this function onClick of a button and properly getting the values in Request variable, but it is not anyhow calling the Controller/Action there.
On firebug I tested it throws the exception "ReferenceError: url is not defined". I am using MVC3 under VS 2010.
Please Help.
You have to define your action properly instead of
url: "/MVC/RB/SS",
use
url: #Url.Action("SS", "RB")
For the url you have 'MVC/RB/SS' this is relative to your current directory a quick test would be to put in url: "../MVC/RB/SS" or url: "../../MVC/RB/SS" depending on how deep you page is in the site structure.
Another way would be to try this:
url: "#Action("/MVC/RB/SS")",
this will create the correct url at the correct level for you and should be picked up.
Try this:
url: "~/MVC/RB/SS",
This will resolve to path "http://site-name/MVC/RB/SS".
What does Firebug say?

Can't access asp controls from static method, but when I remove static, ajax call won't work

I have a method called getPersonInfo and it's header looks like this:
[WebMethod]
public static Hashtable getPersonInfo(int personID)
{
}
The problem I am having is that this method cannot access my asp.net controls. So of course I remove the "static" keyword. But then my ajax calls fail since it's not a static method any more. Any suggestions?
EDIT: After reading and searching for a bit, I've realized that it won't work. What I am asking is if there is another way of maybe getting the final result, as for now I'm unsure of how to do that.
This is fundamentally impossible.
AJAX methods do not run the page lifecycle, so the controls don't actually exist on the server.
Instead, you need to manipulate the page on the client.
You need to pass the values of controls to the getPersonInfo method from client side. For ex: if its JQuery ajax call, additional parameters can be passed using "data" property. Ofcourse, again the getPersonInfo method signature needs to be modified accordingly.
$.ajax({
url: 'adduser.aspx/getPersonInfo',
data: { personID: $('txtPersonId').val() }, //pass additional parameters here
type: "POST",
success: function (template) {
alert('success'); },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});

Categories

Resources