Javascript soap client doesn't work (wash_out service) - javascript

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>

Related

Ajax.BeginForm with BeforeSend

I have several Ajax.BeginForm on my MVC website. Meanwhile I need to handle the beforeSend event of my Ajax calls.
So the below code works for my manual jquery ajax calls, but it doesn't work with the Ajax.BeginForm helpers:
$.ajaxSetup({
'beforeSend': function (xhr) {
alert('');
}
});
Is there anyway to handle the beforeSend event on the MVC Ajax.BeginForm?
-------------------------------------------EDIT -------------------------------------
I need the before send event since I want to change the request headers :
'beforeSend': function (xhr) {
securityToken = $('[name=__RequestVerificationToken]').val();
xhr.setRequestHeader('__RequestVerificationToken', securityToken);
}
Thanks
I think you are following samples from http://richiban.wordpress.com/2013/02/06/validating-net-mvc-4-anti-forgery-tokens-in-ajax-requests/ This post does not address the support of Ajax form integration. I did some tests and found the solution.
I assume you use MVC4 with jquery-1.9.1.js, jquery.validate.unobtrusive.js and jquery.unobtrusive-ajax.js referenced.
Following is my code
#model WebApplication1.Models.DummyModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
</head>
<body>
<div id="Parent">
#using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "post", OnBegin = "BeginClient" }))
{
#Html.AntiForgeryToken();
<div>First Name</div><div>#Html.TextAreaFor(m => m.FirstName)</div>
<div>Last Name</div><div>#Html.TextAreaFor(m => m.LastName)</div>
<input type="submit" value="Submit" />
}
</div>
<script type="text/javascript">
function BeginClient(xhr) {
alert("posting...");
securityToken = $('[name=__RequestVerificationToken]').val();
xhr.setRequestHeader('__RequestVerificationToken', securityToken);
}
$.ajaxSetup({
'beforeSend': function (xhr) {
securityToken = $('[name=__RequestVerificationToken]').val();
alert(securityToken);
xhr.setRequestHeader("__RequestVerificationToken", securityToken);
}
});
</script>
</body>
</html>
Basically you need to leverage onBegin event, see http://johnculviner.com/ajax-beginform-ajaxoptions-custom-arguments-for-oncomplete-onsuccess-onfailure-and-onbegin/ there is clear explanation what is the parameters for each event.
Then in your global attribute class, your code looks like
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ValidateAntiForgeryTokenOnAllPostsAttribute : AuthorizeAttribute
{
/// <summary>
/// Executes authorization based on anti-forge token.
/// </summary>
/// <param name="filterContext">MVC pipeline filter context.</param>
public override void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.HttpContext.Request;
// Only validate POSTs
if (request.HttpMethod == WebRequestMethods.Http.Post)
{
// Ajax POSTs and normal form posts have to be treated differently when it comes to validating the AntiForgeryToken
if (request.IsAjaxRequest())
{
var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
var cookieValue = antiForgeryCookie != null
? antiForgeryCookie.Value
: null;
AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
}
else
{
new ValidateAntiForgeryTokenAttribute().OnAuthorization(filterContext);
}
}
}
}
By doing this way you can still force to use anti-forgery token with Ajax form.
Hope this helps.
For Ajax.BeginForm you can use AjaxOptions.OnBegin:
#using (Ajax.BeginForm("actionName", "controllerName", new AjaxOptions() {
OnBegin = "requestBeginHandler"})) {
...markup here...
}
Update. To add new request header you can do something like this:
function requestBeginHandler(ajaxContext) {
var request = ajaxCOntext.get_request();
securityToken = $('[name=__RequestVerificationToken]').val();
request.get_headers()['__RequestVerificationToken'] = securityToken;
}

How to call Wcf Service from javascript using vb.net code?

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:

server side scripting in to javascript

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>

jquery $.get() not working on localhost

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);
}
});

ERROR---Origin null is not allowed by Access-Control-Allow-Origin [duplicate]

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

Categories

Resources