I am trying posting a data to a web service. And this service in a different project in same solution.
This project name is WebServices and web service's name is HastaTahlilUyariService.asmx.
My code is here:
$.ajax(
{
type: "POST",
url: "WebServices/HastaTahlilUyariService.asmx/f_HastaninAktarilacakAlislabTestleri",
data: "{_sTcKimlikNo:" + Cell.innerHTML + ",_iKlinikKodu:18001,_bAy:12,_iYil:2009}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(msg) {
alert( 'hata'+ msg);
}
}
);
I think my url is wrong. How can i give correct url.
Thanks in advance...
You might want to change your url to something that isn't relative to where you are right now, such as url: '/WebServices/... (initial slash...)
Using the firebug addon for firefox, you can inspect the AJAX callback and see what exact URL is being requested. You can copy that URL, and you should be able to point your browser to the URL of the asmx (i.e. without the last parameter, which is the method name).
Other than that, you need to make sure you've uncommented the ScriptService attribute in the top few lines of the asmx code file. It is commented out by default, but it needs to be there to allow jQuery to access the webservice.
First of all: build your webservice, and configure it to run under something like http://localhost/services/myservice.asmx in IIS Configuration Manager. Open IIS Manager, rightclick on website -> New Virtual Directory; and navigate to the folder where your webservice is located. Name the virtual directory then services.
Then call the service with it's fully qualified url like http://localhost/myservice.asmx/function.
The most easy way to do what you are trying to do (well, I guess)
Create the method you want to call in your codebehind like
[WebMethod]
public static object MethodToCallFromAjax(string argument)
{
//do something
return result;
}
Then add a ScriptManager to your aspx page; and set enablePageMethods=true. Then call your method from JavaScript like:
PageMethods.MethodToCallFromAjax("argument value", function(msg) { alert(msg); });
edit: removed some stuff about json and asmx that wasn't true :-)
Another option to look into is the standard XMLHttpRequest object that is built into the browser (for IE 6 you have to use the ActiveX object with the same name). It makes calling XML services pretty easy, although you end up having to some of the SOAP formatting yourself.
Wikipedia entry for XMLHttpRequest
Related
This is how I do it if the C# controller is in the same project:
$http({
method: 'GET',
url: '/api/SomeController/SomeMethod',
headers: { 'Content-Type': 'application/json' }
I'm building a SPA, so I want my AngularJS stuff and the WebApi stuff to be in their own projects.
How it's done if the controller is in another project inside the solution?
Your url has to match your url of the Web API. Your problem will be that the port of your localhost will change everytime you start your webserver.
What you can do is setting this port.
For this you just go to the properties of your Web API project, choose the tab "Web" and then mark "Use Visual Studio Deployment Server" and enter a port.
If you take something like "1337" you can make your calls in Angular like that:
$http({
method: 'GET',
url: 'localhost:1337/api/SomeController/SomeMethod',
headers: { 'Content-Type': 'application/json' }
if would really suggest you to store a base url somewhere in your javascript code, so when you deploy your page some time soon, you'll just need to change one variable.
I hope this helps you
You need to inform a full url, like:
http://localhost:5376/api/SomeController/SomeMethod
and in production, change to the IP or domain.
I like to create two constants files in my project:
URL
angular.module('app')
.constant('URL', {
local : 'http://localhost:54341/api',
dev : 'http://...',
hom : 'http://...',
prod : 'http://...'
});
Config:
angular.module('app')
.constant('CONFIG', {
env: 'local'
});
And use like this:
var url = URL[CONFIG.env] + '/anotherPath';
You will likely have problems with POST, PUT (...) request. If so, search for CORS and pre-flight problems.
my stuff works fine with Fiddler and I get desired result. But when i do it on web page thru JQuery AJAx, it says "Not Found". I am struggling since sometime but couldn't get around.
My Controller method is like this
[Route("AddDonors/")]
[HttpPost]
public dynamic addDonors(localDonor localDonor)
{
return localDonor;
}
This is how i am calling from web page
var userInput = { 'FullName': 'Lakshman', 'Mobile': '9924210053' };
$.ajax({
type: "POST",
url: "/AddDonors",
data: userInput,
error: function (result) {
alert(result);
},
datatype: "json"
});
this is the model class
public class localDonor
{
public String FullName { get; set; }
public String Mobile { get; set; }
}
API registering and other settings are just fine since this works in fiddler.
Please help. Thanks.
I strongly suspect that the url in your AJAX request is to blame (404 - Not Found) the request can't be routed to a controller for processing.
Without knowing what your full controller looks like and if you have a RoutePrefixAttribute on this specific controller I can't say what the url should be.
I would suggest you monitor network traffic in your browser developer tools (press F12) and compare the request url for your failing POST request to those of your successful requests in Fiddler
If your webpage is created in ASP.Net MVC as part of the same web project you may want to generate the url server side in future see Construct url in view for Web Api with attribute routing. The #Url helper is only available within your .cshtml files though so you will not be able you shift your JavaScript code to a separate .js file.
i was able to solve the issue by changing the url to url: "AddDonors",
Try to put [WebMethod] attribute.
[Route("AddDonors/")]
[HttpPost]
[WebMethod]
public dynamic addDonors(localDonor localDonor)
{
return localDonor;
}
Hope this works!
Try this for your POST data
var userInput = JSON.stringify({ 'FullName': 'Lakshman', 'Mobile': '9924210053' }),
I had the same error.
As you are using ASP.NET, try making all AJAX calls using the #Url.Action helper.I don't know why, but in some situations in ASP.NET passing the URL as a String doesn't work.And try passing your data like the code belowYour modified code should look something like this:
$.ajax({
type: "POST",
url: "#Url.Action("AddDonors", "ControllerName")",
data: { localDonor: userInput },
error: function (result) {
alert(result);
},
datatype: "json"
});
I'm working on an ASP.Net user control, which is using Jquery UI for rendering controls such as modal dialog, accordion, etc.
I've ajax post method in the javascript file. The javascript file lies in JS folder under Root.
function ajaxPost(someData) {
var serviceUrl = "../Test.asmx/eidTasks";
var param="{'data':'" + someData + "'}";
$.ajax({
type: "POST",
url: serviceUrl,
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: ajaxPostSuccess,
error: ajaxPostFailed
});
}
function ajaxPostSuccess(){
alert("Post Success");
}
function ajaxPostFailed(){
alert("Post Failed");
}
My ajaxPostFailed always gets triggered. I suspect that the issue is I'm not able to reference the .asmx service correctly. I saw while debugging that the service was not at all hit. Any pointers what could be the correct way to give the service URL path here.
I've tested the service separately and it does have the [System.Web.Script.Services.ScriptService] block uncommented to allow AJAX calls.
EDIT
How can I call a webmethod (wrapped in a asmx file) from a JS file? Provided, both are part of same ASP.Net solution with the .js file inside JS folder under ROOT directory. The asmx web service is directly beneath ROOT.
If the issue is with the .asmx file not being correctly referenced from your JScript, try resolving the path using ResolveClientUrl() method. For e.g., var serviceUrl = '<%= ResolveClientUrl("~/Test.asmx")%>'+"/eidTasks"
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.
I'm trying to use jQuery and JSON with a C# Web Service that I wrote. No matter what, the following code will only output in XML.
Webservice Code
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld() {
return "Hello World!";
}
I also have these attributes assigned to the class
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
jQuery Code
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ScheduleComputerDS.asmx/HelloWorld",
data: "{}",
dataType: "jsonp",
success: function(data) {
alert(data);
}
});
The ASMX page always returns as content type "text/xml". Anything I'm missing?
EDITS: In response to a couple answers:
If I have the datatype as just "json" the content is still XML and jQuery also will not call my callback function. If I add the "&callback=?" to the url, IIS throws a HTTP 500 error.
My class does inherit from "System.Web.Services.WebService".
From doing some research on your guys answers, it looks like I do need to mess with WCF. Unfortunately the JSON that is returned is more designed for MS Ajax and is a lot of useless bloat for my use. I may look into an open source library like Jayrock or something similar.
Thanks for all your help!
I think there's a typo:
dataType: "jsonp",
Should be:
dataType: "json",
As far as I know, the ScriptService attribute just allows the service to automatically create a JavaScript proxy (by appending /js to the endpoint address - ScheduleComputerDS.asmx/js in your case). It does not allow you to call the operations on the service the way you're trying to do.
You could instead use a RESTful WCF service (which requires .NET 3.5) which you can access by sending a properly shaped URI via an HTTP GET.
Rich Strahl has a really basic post that should help you out with this.
http://www.west-wind.com/weblog/posts/164419.aspx
Have you tried with datatype json?
Also, have a look at Encosia's Using jQuery to Consume ASP.NET JSON Web Services article on the matter. There's some good info on common pitfalls too.