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
Related
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?
I am working on vNext, and trying to create a web api in asp.net vNext. following are the sample code that i used to create api
public class UserController : Controller
{
public IActionResult Get()
{
return Result.Json(new { message = "Valid" });
}
}
I can access this api on browser directly and even i can access this api in same domain view by ajax get request, sample code is below
$.ajax({
type: "GET",
// Get the action URL
url: "http://mydomainname/api/user",
dataType: "json",
success: function (data, textStatus, jqXHR) {
alert(data.message);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
But, when i am trying to access this api by means any other domain or jfiddler , it is not working.
check this jfiddler link
http://jsfiddle.net/2r8wj62a/14/
I am using VS2014 CPT.
an i missing anything... any help will appreciated.
Thanks in Advance...!
beta.smallshiptravel.com resolves to ip 74.114.167.68 on my end. Is it the same on your end?
I've tried the link and it is returning:
HTTP/1.1 404 Not Found
Content-Type: text/html
Server: Microsoft-IIS/8.5
X-Powered-By: ASP.NET
So it looks like you are running inside iis and iis returns not found. I would check the iis logs if the request are actually ending up inside your iis server, or if another server (or reverse proxy) is returning the calls. It it does end up in your server then I would add some logging in my code to every request so i could see it my code actually gets called.
HTH,
Bart
I am trying to learn how to program a web service with ServiceStack and call it via ajax in JavaScript. I did this by watching the pluralsight movies and I think I almost figured it out how to do that except for passing data as parameters with a service call.
I try to call the service with this ajax-call:
var request = { };
request.Amount = 32;
$.ajax({ type: 'POST',
contentType: 'application/jsonp; charset=utf-8',
url: "http://localhost:1879/entry",
dataType: 'jsonp',
data: {request: request},
success: function(result){
alert(result.Id);
}});
The service looks like this:
public class EntryService : Service
{
public object Post(Entry request)
{
return new EntryResponse() { Id = request.Amount };
}
}
[Route("/entry", "POST")]
public class Entry
{
public int Amount { get; set; }
}
public class EntryResponse
{
public int Id { get; set; }
}
I expect the alert in the callback to show the number 32, but it shows the number 0. And when I debug my service I see that request.Amount is 0 as well, so I think I do something wrong at the Ajax service call but I cannot figure out what. So I wonder what I am doing wrong here.
author of that Pluralsight course here. Hopefully I can help you.
First thing you should do is make sure the API is working correctly.
Go to this: http://localhost:1879/entry
In your web browser you should see a page displayed that has information about the service. If you don't your URL is wrong or ServiceStack is configured wrong.
Assuming the URL is correct, all you should need to do is wrap your data in JSON.Stringify().
When you do a post, the data has to be in JSON format as a JSON string. You are currently sending a JSON object.
Also, most likely you can drop the localhost bit off your url in the $.ajax call and just do "entry"
You can not do a post with JsonP. If you are trying to do a cross domain POST you need to look into cors and make sure that is enabled for the the service you are POSTing to.
Post data to JsonP
I only used jsonp cause I read and hoped that it could be the solution for my problem. But based on your explanation I shouldn't need it, so I changed my code to this:
var request = { };
request.Amount = 32;
$.ajax({ type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "http://localhost:1879/json/reply/Entry",
dataType: 'json',
data: request,
success: function(result){
alert(result.Id);
},
error: function(xhr, ajaxOptions, thrownError){
alert("Failure!");
alert(xhr.status);
alert(thrownError);
}});
First I had this call without the error part and nothing happened, no alert, no error, nothing. So I assumed the error was consumed instead of being showed, so I added the error callback and my assumption seemed to be right. Now I get 3 alerts and the last 2 alerts shows "400" and "bad request".
I searched on those errors and tried but none of the possible solutions I found fixed my problem. I tried 2 urls: /json/reply/Entry and /entry after the localhost part but both didn't work. So what am I doing wrong?
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.