I am new to HTML development.
I am developing a mobile application using phonegap- HTML5.
I want to call a web service which is written in JAVA returning SOAP message.
I am calling my webservice using XmlHttp reguest but which on execution returns null data and status as 0.
So, my question is how can I call webservice in an HTML page?
What should I do to call Java SOAP webservice from HTML page?
Please any help is appreciated.
Please suggest any method soon.
Thanks in advance.
You need to make a soap request in a js file.
In your js file you should have something like this:
function sendSOAPRequest(webServiceMethod, params, callbackMethod, isAsynchronous, callContext)
{
//Get the token from local storage
var token = window.localStorage.getItem("token");
//Get the soap envelope with given parameters
var soapEnvelope = getEnvelopeFromParam(webServiceMethod, params);
//Send the soap request
$.ajax({
url: "https://www.zzz.com/yyy/soap",
type: "POST",
dataType: "xml",
data: soapEnvelope,
context: callContext,
complete: callbackMethod,
async: isAsynchronous,
timeout: 60000,
contentType: "text/xml; charset=\"utf-8\"",
beforeSend: function (xhr) {
xhr.setRequestHeader('SOAPAction', 'http://zzz.com/yyy/uuu/Iooo/' + webServiceMethod);
xhr.setRequestHeader('Authorization', token);
}
});
}
function getEnvelopeFromParam(webServiceMethod, parameters)
{
var soapEnvelope = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><' + webServiceMethod + ' xmlns="http://zzz.com/yyy/uuu">';
$.each(parameters, function(key, value) {
if(value)
{
soapEnvelope += '<' + key + '>' + value + '</' + key + '>';
}
else
{
//Send a null value
soapEnvelope += '<' + key + ' i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"/>';
}
});
soapEnvelope += '</' + webServiceMethod + '></s:Body></s:Envelope>';
return soapEnvelope;
}
this is a method to call webservice. You have the specify the right adresses corresponding to your server.
Now include this js file in your html
<script type="text/javascript" src="myFile.js"></script>
Now you have to call your js function from your html page (for exemple)
sendSOAPRequest("myfunction", params, endFunction, true, this);
And you have to define the endFunction
function endFunction(xmlHttpRequest, status)
{
//Work with xmlHttpRequest and check status
}
Related
I have a js function , which Fortify identified as XSS vulnerable as below. Can you suggest any solution for this since the method is intensively used in my app.
I am here trying to call a partialview in ajax and the result html am appending to a specified dom div
My function look like the below
function loadPartialViewToDiv(div, obj, api) {
try {
const myUrl = new URL(window.location.origin + api); // always local URL only
$.ajax({
url: myUrl ,
data: obj,
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
if (data != undefined && data != null) {
$('#' + div).html(data);
}
}
});
} catch (e) {
('#' + div).html('Error');
}
}
The dynamic DOM element id was the issue ($('#' + div).html(data); ), we fixed it using two methods
giving a static id. $('#abcd').html(data);
OR
change as $('#' + div).text($(data));
when i run below code.
it makes error and alert "fail error:StntaxError: Unexpected token < in JSON at position 0 data:undefined"
what is the problem ??
$("#a").click(function () {
st_dt = $("#st_dt").val();
end_dt = $("#end_dt").val();
lot_cd = $("#lot_cd").val();
var obj = { st_dt: st_dt, end_dt: end_dt, lot_cd: lot_cd };
var json_1 = JSON.stringify(obj);
$.ajax({
type: "POST",
url: '{{ url_for("get_operid") }}',
data: json_1,
dataType: "JSON",
success: function (data) {
alert("Success\n" + data);
},
error: function (request, status, error, data) {
alert("fail\n" + "error:" + error + "\n data:" + data);
}
});
});
Looking at the code it looks like a Laravel API request using Blade Template or the Function url_for is in Flask... In either case
That means the response for the api request is HTML string instead of
a json response...
i.e. The API request is returning a login page or some HTML page...
To check the response you can open the Chrome Devtools in the Network tab check the response of the API...
what you can try is :
var obj = { st_dt: st_dt, end_dt: end_dt, lot_cd: lot_cd };
console.log(obj);
var json_1 = JSON.stringify(obj);
console.log(json_1);
Then See in browser console what is your object and if the JSON converting your object properly.
If that is ok , Your request should be done currectly. And try to see what are the data you getting as response with:
success: function (data) {
consoel.log('response below');
console.log(data);
}
You will find the error. I hope.
I have some JSON objects that I want to process on Client Side, but My WebMethod that I specified does not want to fire.
Here is the Ajax and GetJson methods i used in my Client Side Script:
GetSJON
$(document).ready(function() {
$(document).ready(function() {
//attach a jQuery live event to the button
$('#getdata').live('click', function() {
$.getJSON('/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions', function(data) {
//alert(data); //uncomment this for debug
// alert(data.item1 + " " + data.item2 + " " + data.item3); //further debug
$('#showdata').html("<p>item1=" + data.item1 + " item2=" + data.item2 + " item3=" + data.item3 + "</p>");
});
});
});
Here is the Ajax
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function (res) {
$('#Results').append(CreateTableView(res)).fadeIn();
}
});
});
Both of these Methods Call StockPlacementOptions which is my WebMethod that look like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json,
UseHttpGet = true, XmlSerializeString = false)]
public static List<StockReturnMethod> StockPlacementOptions()
{
scmEntitiesPrimaryCon entities = new scmEntitiesPrimaryCon();
var binOptions = (from avail in entities.ProductAvailibleBins(1, 2)
select new StockReturnMethod() { LotID = (int)avail.LotID, LotName = avail.LotName, AreaID = (int)avail.AreaID, AreaName = avail.AreaName, BinID = (int)avail.BinID, BinName = avail.BinName }).ToList();
return binOptions;
}
If I can just get the JSON web Method to fire on $(document).ready event, I will be able to process and work with the data from there. I have also tried looking at a diffrent jQuery library like KnockoutJS with it's data processing capability, also no luck.
I am using ASP Webforms on Framework 4 with Html5 Markup.
Any advice will be greatly appreciated.
Why are you using two document.ready() handlers at your client side getJson and ajax
$(document).ready(function() { // <-------you can remove this handler
$(document).ready(function() {
$('#getdata').live('click', function() {
$.getJSON('/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions', function(data) {
//alert(data); //uncomment this for debug
// alert(data.item1 + " " + data.item2 + " " + data.item3); //further debug
$('#showdata').html("<p>item1=" + data.item1 + " item2=" + data.item2 + " item3=" + data.item3 + "</p>");
});
});
}); // <-------you can remove this handler
although i am not sure this could be the issue but try this one if this helps.
I got it fixed by using a combination of KnockoutJS and ajax.
By utilizing the knockoutJS mapping model, I am able to manipulate the returned JSON anyway i want :)
Here is my Jquery that does the Mapping and obtains JSON from server.
<script type="text/javascript">
//Declareing Viewmodel For KnockoutJS
var viewModel;
//Using Mapping Plugin for Knockout JS
function bindModel(data) {
viewModel = ko.mapping.fromJS(data);
console.log(viewModel);
ko.applyBindings(viewModel);
}
//Onload ObtainJSON
$(document).ready(function () {
$.ajax({
url: "WebForm1.aspx/StockPlacementOptions",
// Current Page, Method
data: {},
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (result) {
bindModel(result);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
});
</script>
I also changed the Webmethod slightly to obtain the result i wanted:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<StockReturnMethod> StockPlacementOptions()
{
scmEntitiesPrimaryCon entities = new scmEntitiesPrimaryCon();
var binOptions = (from avail in entities.ProductAvailibleBins(1, 2)
select new StockReturnMethod() { LotID = (int)avail.LotID, LotName = avail.LotName, AreaID = (int)avail.AreaID, AreaName = avail.AreaName, BinID = (int)avail.BinID, BinName = avail.BinName }).ToList();
return binOptions;
}
And That's it :D
Thanks for all the help
After authentication with Google oauth2.login getting access_token and expires_in. Everithing going great till my token expires. After expiration, when I send again request for data with old token like that:
var URLHead = 'https://www.google.com/fusiontables/api/query?sql='
var URLTable = encodeURI('SELECT id,COUNT() FROM TABLE_ID')
var URLTail = '&access_token='+ old_token +'&jsonCallback=?'
var queryURL = URLHead + URLTable + URLTail
var jqxhr = $.ajax({
type: "GET",
url: queryURL,
dataType: 'jsonp',
success: function (d) {
var max = d.table.rows[0].toString().substr(1)
localStorage.setItem('cpage', Math.ceil(max / localStorage.getItem('delimeter')))
},
error: function(){alert('token_expired')}
})
working on success and giving nothing if token expired. All over the internet can't find clear example how to handle expiration? Shouold I count myself 3600 seconds and delete old_token or is there any elegant way to handle token expiration error?
What does the response look like when the token has expired? The API is not necessarily going to throw an error, just a normal JSON response. The response probably contains something to say that the token has expired which you can therefore use to check on the fly.
Try:
success: function (d) {
if(d.error){
if(d.error == 'invalid_token'){
alert('invalid_token');
}
} else {
// local storage etc
}
}
or (with error handling) :
var request = $.ajax({
url: "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=1/fFBGRNJru1FQd44Az%20%E2%80%8BqT3Zg",
type: "GET",
});
request.done(function(msg) {
// complete
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Heres the fiddle : http://jsfiddle.net/MFe9d/
i want to call asp.net web service from java script and pass the parameters to it .is there any code sample or demostration that will help me to acheive that??
thanks in advance
JQuery:
function AddLocation(ParentID) {
$.ajax({
type: "POST",
url: "../server.asmx/Save",
data: "{'ID':'0','ParentID':'" + ParentID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var item = document.createElement('option');
item.value = data.d.split("$")[0];
item.text = name;
//do stuff
}
});
}
jQuery supports this behavior. you can use jQuery to do the ajax call as show below. this method has two call back functions for success and for failure.
function loadData()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: 'methodurl',
success: methodSuccedded,
error: methodFailure
});
}
function methodSuccedded()
{
//do your logic.
}
function methodFailure()
{
//do your logic.
}
You can do so, using AJAX, and get the response from the server as an JSON object.
var xmlHttp = new ActiveXObject("Microsoft.XmlHttp");
var url = "Service1.svc/ajaxEndpoint/";
url = url + "Sum2Integers";
var body = '{"n1":';
body = body + document.getElementById("num1").value + ',"n2":';
body = body + document.getElementById("num2").value + '}';
// Send the HTTP request
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(body);
// Create result handler
xmlHttp.onreadystatechange= function X()
{
if(xmlHttp.readyState == 4)
{
result.innerText = xmlHttp.responseText;
}
}
Getting the response as JSON would help you evualte it asn object and u can act on it through JavaScript.
See these links for reference:
http://blogs.msdn.com/b/alikl/archive/2008/02/18/how-to-consume-wcf-using-ajax-without-asp-net.aspx
http://dotnetslackers.com/articles/ajax/JSON-EnabledWCFServicesInASPNET35.aspx
The below link is a pretty decent method from my experience.
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/