How to call webservice in HTML page using JQuery? - c#

i have WebService that get 2 string and return if they equals
WebService that in http://192.168.100.MyIP/HTML_SIMPLE_TEST/
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod(Description = "Validate the login credentials")]
public bool Validate(string UserName, string Password)
{
if (Password == "test" && UserName == "test")
return true;
else
return false;
}
}
and i have html page that call this WebService and need to return the Result
<html lang="en-US">
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
var Surl = "http://localhost:3031/WS_HTML/Service1.asmx/Validate";
$(document).ready(function () {
$("input#submit").click(function (event) {
//var uid = document.getElementById("UserName").value;
//var pwd = document.getElementById("Password").value;
var uid = "test";
var pwd = "test";
var dataString = "{ 'UserName' : '" + uid + "', 'Password' : '" + pwd + "'}";
$.ajax({
ServiceCallID: 1,
url: Surl,
type: 'POST',
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
returnVal = result.d;
alert(returnVal);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
returnVal = '';
}
});
});
});
</script>
</head>
<body >
<form method=post runat="server">
<input type="submit" />Connet to my WS
</form>
</body>
</html>
this what i get:
and i try this, still same problem....
<script>
function XX() {
alert("in");
$.post('http://localhost/WS_HTML/Service1.asmx/Validate', { username: 'test', password: 'test' }, function (response) {
response; // Here is response
alert(response);
});
}
</script>
</head>
<body >
<form method=post runat="server">
<input type="submit" onclick="XX();" />Connet to my WS2
</form>
</body>
</html>
i try with $.get - and same.... Nothing happens....
from the browser its work. if i write this: localhost/WS_HTML/Service1.asmx i see my WS,
but if i write this: localhost/WS_HTML/Service1.asmx/Validate i see error on browser =>
Request format is unrecognized for URL unexpectedly ending in '/Validate'.
I swear to God that for several days I break my head and can not figure out why it does not work
):
thanks,

You not forced to use jQuery for make Ajax request. You can use standard javascript (it's more efficient, and you have not to load library for that...)
Also, you don't have to create an click event for submit your form, you can juste create an HTML structure and submit by an onclick attribute, is more efficient (less browser memory).
<!DOCTYPE html>
<html lang="en-US">
<head>
<script type="text/javascript">
var myUrl = "http://localhost:3031/WS_HTML/Service1.asmx/Validate";
function submitMyForm(){
// Define your datas
var uid = "test";
var pwd = "test";
var dataString = "{ 'UserName' : '" + uid + "', 'Password' : '" + pwd + "'}";
// Create and send the request
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
// Log with console.log() or alert if you want...
console.log('State of my request changed! ');
if (XMLHttpRequest.DONE === request.readyState) {
console.log(request.responseText);
}
}
request.open('POST', myUrl, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
}
</script>
</head>
<body>
<form>
<button onclick="submitMyForm()" >Connect to my WS</button>
</form>
</body>
</html>
I see you use a basic javascript alert() on your code, for the debug you can use console.log() (you can see the doc here).
For your question, I don't think the problem is your HTML/Javascript. jQuery method you've look right. HTML too.
I think you've a problem with your server, This not a client problem. It's a server error : you can see that with your HTTP status code (405 -> doumentation for this HTTP code here).
Have you right configured your server ? You can surrely found informations about 405 method not Allowed - ISS server on this website, on or the MSDN forum
Hope I help you.

Why not use $.post() ?
$.post('/your/service/url/', {username:'asd', password:'qwe'}, function(response){
response; // Here is response
});

Related

Passing string from AJAX to ASP.NET C# code behind

I am new to JS, even less experienced at AJAX. I'm just trying to pass a value to the code behind and return an expanded response.
The problem is that despite the call succeeding, the string value passed from AJAX to C# is never anything other than "undefined", and it is driving me insane.
The JS
function test() {
var message = "this is a test" ;
Display(message);}
function Display(words) {
var hummus = { 'pass': words};
$.ajax({
type: 'POST',
url: 'Account.aspx/ShowMe',
data: hummus,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert("Your fortune: " + response.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + words + "\n\nError: " + lion);
}
});}
The Code Behind
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMe(string pass)
{
string beans = pass + ". We repeat this is only a test.";
return beans;
}
The end result is invariably "Your fortune: undefined. We repeat this is only a test."
I would only like to know what I am missing.
Yes this is probably a stupid question but my searches reveal nothing helpful.
Your issue is that you are trying to accept a string in your method public static string ShowMe(string pass) but you are passing a JavaScript object as your data. See when you make an Ajax call ASP.Net will do its best to match up the data you posted to the type you have in your parameter - called Model Binding. When this cannot be achieved then you get an null passed in.
So in your JavaScript you are passing a JavaScript object using this:
var hummus = { 'pass': words};
$.ajax({
....,
....,
data: hummus,
If you wish to post an object then your controller/method needs to have a C# model (class) that your JS will be bound to.
So change your method to accept a model:
// somewhere in your code put this little model
// this is what your JavaScript object will get bound to when you post
public MyModel{
// this is to match the property name on your JavaScript object, its case sensitive i.e { 'pass': words};
public string pass {get;set;}
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMe(MyModel model)
{
// you can now access the properties on your MyModel like this
string beans = model.pass + ". We repeat this is only a test.";
return beans;
}
I found two issues in your code -
Missing data: JSON.stringify(hummus),
Remove lion which variable doesn't exist.
Fix
function test() {
var message = "this is a test";
Display(message);
}
function Display(words) {
var hummus = { 'pass': words };
$.ajax({
type: 'POST',
url: 'Account.aspx/ShowMe',
data: JSON.stringify(hummus), // Missing JSON.stringify
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert("Your fortune: " + response.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// remove lion which variable doesn't exist.
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + words);
}
});
}
Working code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Account.aspx.cs" Inherits="WebApplication1.Account" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<button type="button" onclick="test()">Display Word</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function test() {
var message = "this is a test";
Display(message);
}
function Display(words) {
var hummus = { 'pass': words };
$.ajax({
type: 'POST',
url: 'Account.aspx/ShowMe',
data: JSON.stringify(hummus), // Missing JSON.stringify
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert("Your fortune: " + response.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// remove lion which variable doesn't exist.
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + words);
}
});
}
</script>
</form>
</body>
</html>
public partial class Account : System.Web.UI.Page
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMe(string pass)
{
string beans = pass + ". We repeat this is only a test.";
return beans;
}
}
Thank you both for your help. I'm going to try the Model method, the JSON.stringify was something I had tried before and ultimately worked.
Apparently the problem I was not understanding how my browser worked. No matter what changes I made I was getting the same error. The reason?
My code wasn't in tags on the page, it was in a separate js file which Chrome was caching for me, effectively negating every change I made to try and correct the problem and driving me insane in the process.
In all I've learned a new technique, Model Binding, and that location of code can dramatically effect your Javascript experience.

Is It possible to use web method in C# class?

I'm using web method in C# class file(i.e not a partial class of any web form) and I have html file. I just want to call web method from html file using JQuery AJAX GET and POST methods. Is it possible to do this? Is this have any sense? or i must want use asp web form?
To answer your question it's important that you first understand the prurpose of having a web service.Web services allow us to expose any piece of software over the internet and allow clients to consume it.
In .NET ASMX web services we expose software to the outside world by decorating methods with the [WebMethod] attribute.But even if we apply the [WebMethod] attribute our method will not be available over the internet unless it's inisde a:
.asmx web service file
.aspx web page
Hopefully now you understand why you can't simply define a [WebMethod] inside a standard C# class.Below is a simple example of calling an ASMX web service from a plain html page:
MyService.asmx:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class MyService : System.Web.Services.WebService
{
[WebMethod]
public string GreetUser(string name)
{
return String.Format("Hello {0}",name);
}
}
Index.html:
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnCallService").click(function () {
$.ajax({
type: "POST",
url: "MyService.asmx/GreetUser",
contentType: "application/json;charset=utf-8",
data: '{name:"' + $("#txtName").val() + '"}',
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (errordata) {
console.log(errordata);
}
});
});
});
</script>
</head>
<body>
<input type="text" id="txtName" />
<input type="button" value="Call Service" id="btnCallService" />
</body>
</html>
Yes you can. Your html file can include a tag with functions that make ajax calls.
Here is a simple example from W3School's site:
<!DOCTYPE html>
<html>
<body>
<div id="demo"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
</body>
</html>
You see that the button has an 'onClick' event, which calls the loadDoc function.
And this is the function:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Here is the link to the tutorial's page:
http://www.w3schools.com/ajax/
Your Ajax Call on HTML will look very similar to this
var options = {
type: "POST",
url: '<%=ResolveUrl("~/FileLocationWhereWebMethodIsDefined") %>',
data: "{'Add Parameters if your web method needs it'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
//jQuery(".overlay").show();
//jQuery(".progress").show();
},
success: function (msg) {
},
error: function (jqXHR, textStatus, errorThrown) {
// jQuery(".overlay").hide();
// jQuery(".progress").hide();
throw Error; // "error";
}
};
jQuery.ajax(options);

ajax call to send access token fail

Hello I'm trying to allow login in my app through facebook, and than I want to get some info with the access token I'm getting.
I'm trying to pass the access token from facebook js sdk to a webmethod on the server for me to use it later, but the call is failing.
here's my aspx:
<html>
<head>
<title>Facebook Login Authentication Example</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Init the SDK upon load
window.fbAsyncInit = function () {
FB.init({
appId: '474928559284763', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function (response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
var dataString = JSON.stringify({ access_T: response.authResponse.accessToken });
alert(dataString);
$.ajax({
type: "POST",
async: false,
url: "Default2.aspx/save_access_token",
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
},
error: function (result) {
alert(result.d);
}
});
FB.api('/me', function (me) {
if (me.name) {
document.getElementById('auth-displayname').innerHTML = me.name;
}
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
//here
//
$("#auth-logoutlink").click(function () { FB.logout(function () { window.location.reload(); }); });
});
}
</script>
<h1>
Facebook Login Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">
<div class="fb-login-button" autologoutlink="true" scope="email,user_checkins">Login with Facebook</div>
</div>
<div id="auth-loggedin" style="display: none">
Hi, <span id="auth-displayname"></span>(logout)
</div>
</div>
</body>
</html>
here's my webmethod:
[WebMethod(EnableSession = true)]
public static void save_access_token(string access_T)
{
HttpContext.Current.Session["a_t"] = access_T;
}
EDIT:
I checked to see what is written on the post and here it is:
Problem solved. something with the web form was not right, when I started a new one it worked.

jQuery Ajax call to database on click ASP.net

Let's say I've got a table in a SQL Server database that looks like
StateName notes
alabama 'notes about alabama'
alaska 'notes about alaska'
..... .........
EDIT: This question will be divided into two parts, one for the initial problem and why it didn't work and my reformed, hopefully more accurate second solution.
In the web form, the name of the state are represented as link button inside of a table. I'm trying to use jQuery to make an Ajax database call when a user clicks on a state name, the text value of the link button will be send to a stored procedure in the database.
That stored procedure is something like
create proc spGetStateData
#stateName varchar(50)
as
begin
select notes from
states
where statename = #stateName
end
For testing purposes, I added a a text box and a button so that when the user types the name of the state into the text box, the Notes column from the States database table is displayed.
[WebMethod]
public static string GetStateData(string stateName)
{
string stateNotes = string.Empty;
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("spGetStateData", con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#stateName", stateName);
stateNotes = cmd.ExecuteScalar().ToString();
}
}
return stateNotes;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
lblStateNotes.Text = GetStateData(txtStateName.Text);
hiddenDiv.Visible = true;
}
This part works, so I know it's not my WebMethod or a database connection that's failing. When I try to do this same thing with jQuery, it fails.
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#states a").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm1.aspx/GetStateData",
data: $(this).text(),
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (x) {
alert('error');
}
});
});
});
</script>
Okay, I pulled open developer tools for Chrome and found out what the reason for the AJAX failing was that I was getting a 'couldn't load resource HTTP 500 error'. It was telling me that the method name and parameter couldn't be found (even though by all rights they were there). So then I tried a second way, which seems like a better way (if I can get it to work!)
So then I thought 'let's use a WebService'. And here is my rendition of that:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("a").click(function () {
var stateName = JSON.stringify({ "stateName": $(this).text() });
$.ajax({
type: "POST",
url: "GetStateData.asmx/GetData",
contentType: "application/json; charset=utf-8",
data: stateName,
dataType: "json",
success: function (data) {
$("#lblNotes").text(data);
},
error: function (x) {
alert('message');
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Alabama
Alaska
<asp:Label runat="server" ID="lblNotes"></asp:Label>
</div>
</form>
</body>
</html>
web service:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Services;
namespace jQueryAjaxWebservice
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class GetStateData : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod]
public string GetData(string stateName)
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
string stateNotes ="test" ;
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("spGetStateData",con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#stateName", stateName);
stateNotes = cmd.ExecuteScalar().ToString();
}
}
return stateNotes;
}
}
}
I've tested the WebService, and it works. However, when I try to call the web service code from default.aspx, I get [Object object] as the lblNotes text. If I change (data) to "test" then I get the correct output of "test" to the screen. So the faulty part is in the success portion of the Ajax call. I put a breakpoint on the GetData function and stateNotes is receiving the proper text value, so the only place left for the problem to be is in the success line of the ajax call.
I think the way you format your data option in ajax might be wrong. It always works in key-value pairs. In the current form you are only sending the value, no key. You might have to change it to this format :
var stateName = { "stateName" : $(this).text()}
or
var stateName = JSON.stringify({ "stateName" : $(this).text()})
But mostly, I've seen only the second one to work, partly because jQuery doesn't pre-process the data option for it be readable in C#. So it's always recommended to use stringify on ajax requests with type set to "POST".
Then, in your ajax call,
$.ajax({
//ajax options
data : stateName
//some more ajax options
});
Also, you might want to make your error option more descriptive, like this :
$.ajax({
//ajax options
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
This will tell you where you're going wrong and you could debug it as well.
EDIT:
In the success function, try looking for data.d instead of data. You'll find that your data lies inside it. Also, as mentioned before (and i cant stress this enough), please use error handler with xhr options. It'll be easier to debug then. Read this if you want to know why the result returns data.d and not just data.
$.ajax({
//some ajax options
success: function (data) {
//data.d will contain your data
console.log(data.d);
$("#lblNotes").text(data.d);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
alert(xhr.status);
alert(thrownError);
}
});
Hope this helps!

Using jQuery to call a web service

I have created a web service which takes a username and password as parameters and returns a list of children in JSON (the user is a Social Worker). The web service is hosted locally with IIS7. I am attempting to access the web service using javascript/jquery because it will eventually need to run as a mobile app.
I'm not really experienced with web services, or javascript for that matter, but the following two links seemed to point me in the right direction:
http://williamsportwebdeveloper.com/cgi/wp/?p=494
http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
This is my html page:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="TestWebService.aspx.cs" Inherits="Sponsor_A_Child.TestWebService" %>
<asp:Content ID="Content1" ContentPlaceHolderID="stylesPlaceHolder" runat="server">
<script type="text/javascript" src="Scripts/jquery-1.7.1.js">
$(document).ready(function () { });
function LoginClientClick() {
$("#query_results").empty();
$("#query_results").append('<table id="ResultsTable" class="ChildrenTable"><tr><th>Child_ID</th><th>Child_Name</th><th>Child_Surname</th></tr>');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost/PhoneWebServices/GetChildren.asmx?op=GetMyChildren",
data: '{ "email" : "' + $("#EmailBox").val() + '", "password": "' + $("#PasswordBox").val() + '" }',
dataType: "json",
success: function (msg) {
var c = eval(msg.d);
alert("" + c);
for (var i in c) {
$("#ResultsTable tr:last").after("<tr><td>" + c[i][0] + "</td><td>" + c[i][1] + "</td><td>" + c[i][2] + "</td></tr>");
}
}
});
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="contentPlaceHolder" runat="server">
<div id="LoginDiv">
Email: <input id="EmailBox" type="text" /><br />
Password: <input id="PasswordBox" type="password" /><br />
<input id="LoginButton" type="button" value="Submit" onclick="LoginClientClick()" />
</div>
<div id="query_results">
</div>
</asp:Content>
And this is my web service code:
[WebMethod (Description="Returns the list of children for whom the social worker is responsible.")]
public String GetMyChildren(String email,String password)
{
DataSet MyChildren=new DataSet();
int ID=SocialWorkerLogin(email, password);
if (ID > 0)
{
MyChildren = FillChildrenTable(ID);
}
MyChildren.DataSetName = "My Children"; //To prevent 'DataTable name not set' error
string[][] JaggedArray = new string[MyChildren.Tables[0].Rows.Count][];
int i = 0;
foreach (DataRow rs in MyChildren.Tables[0].Rows)
{
JaggedArray[i] = new string[] { rs["Child_ID"].ToString(), rs["Child_Name"].ToString(), rs["Child_Surname"].ToString() };
i = i + 1;
}
// Return JSON data
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(JaggedArray);
return strJSON;
}
I followed the examples in the provided links, but when I press submit, only the table headers appear but not the list of children. When I test the web service on it's own though, it does return a JSON string so that part seems to be working. Any help is greatly appreciated :)
EDIT: Thanks to slash197 I discovered the problem. I get the error:
"XMLHttpRequest cannot load http://localhost/PhoneWebServices/GetChildren.asmx?op=GetMyChildren. Origin http://localhost:56018 is not allowed by Access-Control-Allow-Origin."
In Chrome's console. I'm guessing this has something to do with the URL, but when I try that URL in my browser it works fine.
the problem with
"XMLHttpRequest cannot load http://localhost/PhoneWebServices/GetChildren.asmx?op=GetMyChildren. Origin http://localhost:56018 is not allowed by Access-Control-Allow-Origin."
is, localhost and localhost:56018 are per definition two different domains, and Ajax Requests are per default only possible through the same domain.
A best approach for that would be, to run both services on the same port or by using a proxy, which delivers the content from port 56018 to the default localhost port 80. Could be realized through a Rewrite Rule or via an own service which is running, besides your webservice "client".

Categories