I really need help with getting data from my webservice, but all I get is "internal server error". The desired result is to be able to have a webservice return data to my javascript function.
Yesterday I was successfully able to call a webservice, but not able to get data from it.
Below is my javascript code which I understand is executed on the client
function Test(myid) {
var projects;
var opt = document.getElementById(myid);
var constring = '<%=this.ConnectionText %>';
document.getElementById("Text1").value = opt.value;
$.ajax({
type: 'GET',
url: 'Overview.aspx/ExecuteSelectListBox',
contentType: "application/json;charset=utf-8",
dataType:"json",
success: function (data) {
projects = data.d;
},
error: function (requeset, status, error) {
alert( error);
}
});
}
If succesful then projects should become "hello world"
Below is my C# code which I have understood is executed on the server.
However, I dont think my function on the server is called at all. If I replace Overview.aspx with something else I get "not found" from server instead of "internal server error".
But the "executelistbox" itself I can call whatever and I still get "internal server error" and not "not found".
[System.Web.Script.Services.ScriptService]
public class AjaxWebService : System.Web.Services.WebService
{
[System.Web.Services.WebMethod(EnableSession = true)]
/**************************************************
*** Returns a datatable with projectnames. ***
*************************************************/
public static string ExecuteSelectListBox()
{
return "hello world";
}
}
So the desired problem is to be able to retrieve data from a webservice written in c#. Both c# and javascript are actually part of the same webpage in this example. I keep it minimalistic. I hope others can use this too, as a basic example how youre able to get data from your webserver. In the future I will make database calls from the server and send back to the client, but I cannot even think about this now, as I even cant get "hello world" to work :)
I would be so grateful if anyone could help!! I tried posted this before but was shut "on hold".
I would take a look at the following tutorial and use WebApi instead of System.Web.WebService. You are making it yourself rather difficult.
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
At the moment you're requesting Json, but im not sure whether you are actually returning Json, but perhaps xml?
Related
I have a small angularjs application where I'm trying to call a server side function.
I'm not sure but I feel kind a lost when it comes to use the right url for GET/POST from client to server...But I'm not sure the problem is there..
My angular:
$http.get({
method: 'GET',
url: '/Models/Person/GetTestPersons'
}).then(function successCallback(response) {
alert(response);
}, function errorCallback(response) {
alert("ErrorCallback");
});
My server function (Models/Person.cs):
public static string[] GetTestPersons()
{
return new[]
{
"Person1",
"Person2"
};
}
Now I get to the "alert("ErrorCallback")"
And if I could get this to work.. How do I read the array that is returned?
Error:
GET http://localhost:51203/Views/[object%20Object] 404 (Not Found)
You ought to create a Web API project,
The controller will orchestrate call to your Person model.
A quick starter tutorial is here
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
I have a running WCF service that exposes a method GetStuff(String type). It's called by the automatically created client class, so the syntax is embarrassingly simple.
ServiceClient client = new ServiceClient();
String response = client.GetStuff("other's");
client.Close();
The straight-forward question is this. How do I convert that to a call in JavaScript (possiblyusing jQuery) in an easy way?
After some serious googling, I concluded that I'm only going to find examples of how to consume a JSON-formatted stream using jQuery. I prefer not to touch the service-side of the software, if at all possible.
I tried the code below (along with a bunch of derivatives that I could think of) but the error I got was "No Transport" and googling that didn't yield anything that I got me going.
$.ajax({
type: "GET",
url: "http://hazaa.azurewebsites.net/Service.svc",
success: function (response) { console.info(response); },
error: function (response) { console.error("Error! " + response.statusText); }
});
Will I have to write a totally different service that exposes the data in JSON format? How do I specify that the service is supposed to call this or that method? Am I out of luck and these convenience methods are for .NET clients only?
Please note that I've got another way of getting the data where I want, not using JavaScript at all but I'd prefer to see if this is (easily) doable too.
I would convert server method to use web invocation = WebInvoke attribute. Here you can specify uri for the method call.
Link to the info
Look into Jquery SOAP .. http://plugins.jquery.com/soap/ etc.
haven't tried it myself but it's the kind of thing you might be needing here.
I'm doing a project for college where one WebSite sends commands to a Windows Forms application. This application is responsible for access to serial port and send and receive commands.
Communication between the Website and the Windows Forms application, I used Web Api, however after publishing, auditioning remembered that the localhost in a C # WebSite. Net's own site and not my Windows Forms application.
I changed the call to the Web Api directly use Ajax and not a controller.
In the examples I found I saw that I use JSONP, but I can not read the results and use it on my website.
The calling code and return seen by Chrome are below
function cmdLocal() {
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://local host:8089/api/gps/",
jsonpCallback: "cmdTorre",
jsonp: "cmdTorre"
});
}
function cmdTorre(data) {
alert(data);
}
Response Header
Content-Length:10
Content-Type:application/json; charset=utf-8
Date:Tue, 10 Jun 2014 11:18:30 GMT
Server:Microsoft-HTTPAPI/2.0
Response
No Properties
Windows Forms APIController
namespace TCCWindows.Lib
{
public class GPSController : ApiController
{
[HttpGet]
public string Posicao()
{
var coordenada = TCCWindows.FormPrincipal.PegarCoordenadas();
return coordenada.Latitude + "|" + coordenada.Longitude + "|" + coordenada.Altitude;
}
}
}
First, you ajax call looks overly complicated try replacing it with :
function cmdLocal() {
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://local host:8089/api/gps/",
success: cmdTorre,
error: function(err){
alert("You have a error"+err);
}
});
}
function cmdTorre(data) {
alert(data);
}
Please validate the new code carefully. I just typed it in here so can have errors. If this runs at this point you should probably see the error message. That is because your GPSController doesnt seem to be returning a valid JSONP (or JSON for that matter). Please read up on JSONP for more clarification but, I think if you modify your return statement to make it look like following, it should work. Assuming your controller is actually getting called and your network stuff is working:
return "cmdTorre({\"lat\":"+coordenada.Latitude+" , \"lon\":"+coordenada.Longitude+" });"
Basically your return string should look like following when printed on console:
function cmdTorre({
"lat": 23.34,
"lon":34.23,
"alt":50
});
Again I suggest you check the code I wrote for syntax issues as i just typed it up in here, but it should give you the idea.
So problems were:
The return string you are generating is NOT in JSON format
It is also not wrapped in a function call making it a invalid JSONP too.
Lastly my solution should get your code working and JSONP started but its not the right way to do things. Its more of a ugly hack. Your GPS controller should read the HTTP request for parameter called 'callback' which is a accepted convention for JSONP calls. Then instead of hardcoding the function name in the return statement, you should use the value of this callback parameter. Then you dont need to use a specific function like 'cmdTorre' in your jQuery. Instead a anonymus function like success:function(response){...} will work just fine.
Hope that helps.
Im trying to call a server method in my aspx.cs to delete all the files in a directory when a user closes the browser.
[WebMethod]
public static void fileDelete()
{
string[] uploadedFiles = Directory.GetFiles(#"C:\Users\Lambo\Documents\Visual Studio 2010\Projects\test\test\testPdfIn");
foreach (string uploaded in uploadedFiles)
{
File.Delete(uploaded);
}
}
======================================================================
EDIT
I've tried the POST method but it still doesn't seem to work. I've changed the URL too.
Over at the client side im using this:
$(function () {
$(window).unload(function () {
alert("Files have been deleted")
jQuery.ajax({ type: 'POST', url: "http://localhost:19642/success.aspx/fileDelete", async: true });
});
});
However it doesnt seem to be working. Are the codes wrong in someway?
To investigate failures of AJAX calls use HTTP debugger (like Fiddler ) to see what requests are made and what responses are received.
My guess is that your Url is wrong and request is made to wrong file. Consider making absolute (or at lest server relative) url.
I have a small webservice written in C# and WCF.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello Worlds";
}
}
I have a little jQuery code;
$.support.cors = true;
$.ajax({
type: "POST",
url: "http://localhost:61614/Service1.asmx/HelloWorld",
data: '{}',
dataType: "json",
success: function (msg) {
alert(0);
}, error: function (a, b, c) { alert("Err:" + c );
}
});
This calls the webservice. There are no problems making the call, but it errors out on the return.
The webservice is in one application, and the Web page is simply an HTML page on it's own. Eventually, the HTML will be used within PhoneGap.
I have tried all sorts of things.
Adding in contentType: "application/json; charset=utf-8", causes the whole call to fail.
Using dataType: 'jsonp" causes call to fail.
Basically, the above calls the WS but errors out on return which is weird.
My requirement is that I need to return a JSON object from the webservice, and it has to work in Safari.
Does anyone have complete sample code of a JSONP call?
From jQuery getJSON:
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.
In order for your request to be treated as a JSONP request, you need to include callback=? in your URL. This tells jQuery to create a callback function and pass the name of that function as the callback parameter to your server.
In the server-side code, your method must then return JSON code wrapped, or padded, with the name of the JavaScript function passed in as the callback parameter in the query string.
Essentially, what you're doing is returning JavaScript to the client browser, which runs immediately, and invokes a function already defined in the context of the page.
JavaScript:
$.getJSON("http://localhost:61614/Service1.asmx/HelloWorld?callback=?",
function(data) {
// alert raw JSON data
alert(JSON.stringify(data));
// access the "say" property and alert it
alert(data.say);
}
);
Server-Side:
This is a crude version of what you'd need to do on the server-side:
// get the callback parameter value and assign to the String callback
...
return callback + "( { 'say' : 'HelloWorld' } );";
Further technical explanation of what is happening under the hood:
While this is not something you need to know today, this may help you understand more about how jQuery is implementing JSONP.
This evaluates to something that might look like this:
return "jquery43214321432143242({'say':'HelloWorld'});"
where jquery43214321432143242 is the random name given for your success callback function. Again, since the returned text is returned using text/javascript, it runs immediately, passing the {'say':'HelloWorld'} object in as a parameter to the function.
The resulting output should be an alert message representing the raw JSON, and the words "HelloWorld", pulled from the .say property.