How to call Wcf Service from javascript in vb.net ?I am getting error "Service call failed: 415 Unsupported Media Type".
My WebService code:
<ServiceContract()>
Public Class Service <OperationContract()> _
<WebInvoke(Method:="POST",
BodyStyle:=WebMessageBodyStyle.Wrapped, ResponseFormat:=WebMessageFormat.Json)> _
Public Function MyFunction(ByVal Count As String) As String
Return String.Format("Welcome in WCF call")
End Function
End Class
My HTML Code:
<!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>
<!DOCTYPE html>
<title>Call WCF</title>
<script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
var counter = 0;
function CallMyService() {
// debugger;
//alert("hi");
counter++;
$.ajax({
type: "POST",
url: "http://localhost:25057/WCFVB/Service.svc/MyFunction",
data: '{"Count": "' + counter + '"}',
processData: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
// contentType: "application/json", // content type sent to server
success: ServiceSucceeded,
error: ServiceFailed
});
}
// ---- WCF Service call backs -------------------
function ServiceFailed(result) {
//debugger;
Log('Service call failed: ' + result.status + ' ' + result.statusText);
}
function ServiceSucceeded(result) {
// debugger;
var resultObject = result.MyFunctionResult;
Log("Success: " + resultObject);
}
function Log(msg) {
$("#logdiv").append(msg + "<br />");
}
</script>
</head>
<body>
<input id="Button1" type="button" value="Execute" onclick="CallMyService();" />
<div id="logdiv"></div>
</body>
</html>
Here's a sample of a little JavaScript request that runs against our WCF service - it's just a simple ping function in this case, but all the parts are there:
_________ edit _____________
<html>
<head>
<meta http-equiv="Content-Type" content="text/xml; charset=UTF-8" />
<title>SOAP JavaScript Client Test</title>
<script type="text/javascript">
function Ping() {
//set up varable
var sContent;
// 'Content-Type: text/xml \r\n ' +
// 'Host: localhost:8085 \r\n \r\n ';
var s;
s+="<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
s+="<s:Body><HostConnect xmlns=\"http://SomeURL \">";
s+="<inMsg xmlns:a=\"http://schemas.datacontract.org/2004/07/ \" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
s+="<a:TextSection>" ;
s+="<Method value=\"ping\" >";
s+="</a:TextSection>";
s+="</inMsg>";
s+="</HostConnect>";
s+="</s:Body>";
s+="</s:Envelope>";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', Demo.URL.value, true);
//xmlhttp.overrideMimeType("text/xml; charset=UTF-8"); /* ... */
// alert(Demo.URL.value);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4||xmlhttp.readyState == 0) {
//alert("Ready state: " + xmlhttp.readyState.toString());
if (xmlhttp.status == 200) {
//alert("good");
Demo.pingresponse.value = "Response: " +xmlhttp.responseText;
}
if (xmlhttp.status !=200){
//alert("bad");
Demo.pingresponse.value = "Error: " +xmlhttp.status.toString() +" response text: " +xmlhttp.responseText;
}
} else {
//alert("readystate bad");
}
}
xmlhttp.setRequestHeader("POST http:servername:8085/HostInterface/HostConnect HTTP/1.1");
xmlhttp.setRequestHeader("VsDebuggerCausalityData","uIAA");
xmlhttp.setRequestHeader("SOAPAction","\"http://ServerName\"");
xmlhttp.setRequestHeader("Host","localhost:8085");
xmlhttp.setRequestHeader("Expect","100-continue");
xmlhttp.setRequestHeader("Accept-Encoding","gzip, deflate");
xmlhttp.setRequestHeader("Connection","Keep-Alive");
xmlhttp.setRequestHeader("Content-Length","639");
xmlhttp.setRequestHeader("Content-type", "text/xml; charset=utf-8");
xmlhttp.send(sContent);
}
</script>
</head>
<body>
<form name="Demo" action="" method="post">
<div>
Web Service URL
<input id="URL" type="text" size="140" value="" /><br />
<input type="button" value="Ping" onclick="Ping();" /><br />
<textarea id="pingresponse"cols="100" rows="10"></textarea> <br />
</div>
</form>
</body>
<html>
Try this:
Related
I am working on an Asp.Net MVC application where I am using signalR for real time database notifications
I am trying to create a proxy using the following script
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>JobStatus</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery.signalR-2.0.1.min.js"></script>
<script src="~/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var job = $.connection.jobHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblJobInfo');
$.ajax({
url: '../JobInfo/',
type: 'GET',
datatype: 'json',
success: function (data) {
if (data.length > 0) {
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th><th>Last Executed Date</th><th>Status</th></tr>');
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].LastExecutionDate.toString().substr(0,10) + '</td><td>' + data[i].Status + '</td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
</script>
</head>
<body>
<div>
<table id="tblJobInfo" style="text-align:center;margin-left:10px"></table>
</div>
</body>
</html>
my SignalR Hub class is as follows
public class JobHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<JobHub>();
context.Clients.All.displayStatus();
}
}
but for some reason when I go to my view on the browser and look at the console it throws me follwing error
TypeError: $.connection is undefined
var job = $.connection.jobHub;
Not sure how to deal with this
Check if:
~/Scripts/jquery.signalR-2.0.1.min.js
is available and loading correctly
You can also reference it from cdn:
http://ajax.aspnetcdn.com/ajax/signalr/jquery.signalr-2.0.1.min.js
i am try to get latitude and longitude value from ip address
after getting lat and lng value POST in to php file using AJAX and generate new xml file
this is my html file:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js" ></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function getlg(){
var lan=geoip_latitude();
var lng=geoip_longitude();
var gen = $('#Sex').val();
var date = $('#date').val();
$.ajax({
type: "POST",
url: "http://localhost/SVN/trunk/home/url.php?lat="+lan+"&lng="+lng+'&radius'+$('#radius1').val(),
contentType: "text/html",
success: function(token) {
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
}
});
}
</script>
<body>
<div id="region"><h5></h5></div>
Enter Radius: <input type="text" id="radius1"></input>
<input type="button" id="filter"onclick="getlg()" value="Go">
</body>
</head>
</html>
this is my php file:-
<?php
function convertNodeValueChars($node) {
if ($node->hasChildNodes()) {
foreach ($node->childNodes as $childNode) {
if ($childNode->nodeType == XML_TEXT_NODE) {
$childNode->nodeValue = iconv('utf-8', 'ascii//TRANSLIT', $childNode->nodeValue);
}
convertNodeValueChars($childNode);
}
}
}
$url='http://services.gisgraphy.com/geoloc/search?lat='.$_GET['lat'].'&lng='.$_GET['lng'].'&radius='.$_GET['radius'];
$doc = new DOMDocument();
$doc->load($url);
$doc->save('General.xml');
?>
in this file i am try to Get lat and long and radius from html ajax function and getting one new xml file with help of url.
but its take so much time if radius is biggest.
i want to try this php code in java script dont like server side scripting.
please help me out with this...
thanks...
try this:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js" ></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function myFunction(){
var lan=geoip_latitude();
var lng=geoip_longitude();
var gen = $('#Sex').val();
var date = $('#date').val();
var location = "http://services.gisgraphy.com/geoloc/search?lat="+lan+"&lng="+lng+'&radius'+$('#radius1').val();
document.write('Link text');
}
</script>
<body>
<div id="region"><h5></h5></div>
<input type="text" id="radius1" onchange="myFunction()"></input>
</body>
</head>
I'm trying to use jquery $.get() to obtain values from a server file.
Both files are currently on my machine in the /var/www directory (using linux).
I am aware of the cross-domain restriction for ajax, hence I placed the two files in /var/www.
The "client" file (f1.htm) is:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.9.1.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.get( "f11.htm", function( data, status ){ alert( "1" ); } );
/*
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","f11.htm",false);
xmlhttp.send();
alert( xmlhttp.readyState + " " + xmlhttp.status );
*/
alert( "2" );
</script>
</body>
</html>
while the "server" script (f11.htm) is simply:
<html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
</head>
<body>
<?php
echo "server text";
?>
</body>
</html>
the client script ("f1.htm") gets stuck at the $.get() line. I've tried this with xmlhttprequest (which is commented), and it works. why is the $.get() line not working?.
TIA
You can try this code to examine the error function being returned instead of the shorthand $.get.
$.ajax({
type:'GET',
url: 'f11.htm',
data: {},
success: function(data) {
console.log(data);
}, error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
I'm developing weather application which is working fine in browsers.
But when I try to deploy in my android phone it is not working fine and it is throwing error. XML response is null. please help me.
<html>
<head>
<title>Calling Web Service from jQuery</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script type='text/javascript' src='xmlObject.js'></script>
<script type='text/javascript' src='jquery-1.8.2.min.js'></script>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnCallWebService").click(function (event) {
alert('click' + $("#cityName").val());
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://www.webservicex.net/globalweather.asmx?op=GetWeather",true);
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4)
{
var myXML=xmlhttp.responseXML;
alert("Response XML in getWeatherInformation : ");
alert(myXML);
var json = XMLObjectifier.xmlToJSON(xmlhttp.responseXML);
var body=JSON.stringify(json.Body[0]);
var result = json.Body[0].GetWeatherResponse[0].GetWeatherResult[0].Text;
var myXML2=XMLObjectifier.textToXML(result);
var json2 = XMLObjectifier.xmlToJSON(myXML2);
var body2=json2;
var location=body2.Location[0].Text;
var time=body2.Time[0].Text;
var temperature=body2.Temperature[0].Text;
var pressure=body2.Pressure[0].Text;
alert("location"+location+"..."+time+".."+temperature+".."+pressure);
}
}
xmlhttp.setRequestHeader("Content-Type", "text/xml");
var xml ='<?xml version="1.0" encoding="utf-8"?>'+
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
'<soap:Body>'+
'<GetWeather xmlns="http://www.webserviceX.NET">'+
'<CityName>'+ $("#cityName").val() +'</CityName>'+
'<CountryName>India</CountryName>'+
'</GetWeather>'+
'</soap:Body>'+
'</soap:Envelope>';
alert("Request XML : ");
alert(xml);
xmlhttp.send(xml);
});
});
function processSuccess(data, status, req, xml, xmlHttpRequest, responseXML) {
alert('success' + status + ">>" +typeof $(req.responseXML));
var myObj = new Array();
$(req.responseXML)
.find('GetWeatherResult')
.each(function(){
alert($(this));
myObj.push($(this));
});
$(myObj).each(function(){
var x = $(this).find('Location').text();
alert('loc'+ x + $(this).find('Location'));
var p = $(this).find('Location');
for (var key in p) {
alert(key + " -> " + p[key]);
}
});
}
function processError(data, status, req) {
alert(req.responseText + " " + status);
console.log(data);
console.log(status);
console.log(req);
}
</script>
</head>
<body>
<h3>
Weather Report
</h3>
Enter your city name:
<input id="cityName" type="text" />
<input id="btnCallWebService" value="GetInformation" type="button" />
</body>
</html>
You need to allow the cross domain calls to http://www.webservicex.net
See this post:
Cordova 1.9.0 Ajax not retrieving
Edit your xml in your res folder to include this line:
<access origin="http://www.webservicex.net*"/>
Or if its Phonegap-Build add that line to the config.xml
I wrote Web Service in Ruby (using wash_out). Here is link : http://dictionary.vipserv.org/slownik_de_pls/wsdl
I found solution to write javascript soap client. Code below:
<html>
<head>
<title>SOAP JavaScript Client Test</title>
<script type="text/javascript">
function soap() {
try
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://www.dictionary.vipserv.org/slownik_de_pls/wsdl/', true);
// build SOAP request
var sr = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="urn:WashOut"><soap:Body><tns:get_word_response><value xsi:type="xsd:string">robic</value></tns:get_word_response></soap:Body></soap:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert('done use firebug to see responce');
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
alert(xmlhttp.responseXML.xml);
// send request
// ...
}
catch(error)
{
alert(error);
}
}
</script>
</head>
<body>
<form name="Demo" action="" method="post">
<div>
<input type="button" value="Soap" onclick="soap();" />
</div>
</form>
</body>
</html>
Response is always null. What is wrong?
Cheers, thanks.
Take a look at the WSDL, you probably need to POST to http://dictionary.vipserv.org/slownik_de_pls/action instead of to http://www.dictionary.vipserv.org/slownik_de_pls/wsdl/.
Also, you might want to look at jQuery, and in particular a SOAP library like this one.
I have soap client in Ruby (Savon). There it works fine. I found other solution in jQuery, but I've got parse error. Below:
<html>
<head>
<title>Calling Web Service from jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnCallWebService").click(function (event) {
var wsUrl = "http://dictionary.vipserv.org/slownik_de_pls/wsdl";
var soapRequest = '<?xml version="1.0" encoding="UTF-8"?><env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="urn:WashOut" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"><env:Body><tns:get_word><wartosc>machen</wartosc></tns:get_word></env:Body></env:Envelope>';
$.ajax({
type: "POST",
url: wsUrl,
contentType: "text/xml",
dataType: "xml",
data: soapRequest,
success: processSuccess,
error: processError
});
});
});
function processSuccess(data, status, req) {
if (status == "success")
$("#response").text($(req.responseXML).find("get_word_response").text());
}
function processError(data, status, req) {
alert(req.responseText + " " + status);
}
</script>
</head>
<body>
<h3>
Calling Web Services with jQuery/AJAX
</h3>
Enter your name:
<input id="txtName" type="text" />
<input id="btnCallWebService" value="Call web service" type="button" />
<div id="response" />
</body>
</html>