I want to get data from Webservice( Soap), but it not successfull. My service herehttp://icafe.ipos.vn/WSUitility/evsServiceUtility.svc?wsdl
I use jquery to request to service, code below
var soap = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<Test xmlns=''>" +
"</Test>" +
"</soap:Body>" +
"</soap:Envelope>";
$.ajax({
url: 'http://icafe.ipos.vn/WSUitility/evsServiceUtility.svc?wsdl',
method: 'post',
data: soap,
contentType: "text/xml",
dataType: "xml",
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction", "urn:evsServiceUtility/Test1");
},
crossDomain: true,
success: function(SOAPResponse) {
alert('ok');
},
error: function(SOAPResponse) {
alert('no ok');
}
});
And my service:
public string Test()
{
try
{
return "Successfull!";
}
catch (Exception ex)
{
return ex.Message;
}
}
I spended many many times to search and try many solutions but it not working.
Can anyone help me?
I suppose your data type can be XML, not a problem there. Question is, how do you encode your data or parameters? Perhaps check the response in the POST request in the console of your browser.
I picked up a few things in c# to enable this automatically which is nicely documented here:
http://encosia.com/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/
Then one thing left to do was to JSON.stringify() the data. So bhRequest is a json object right?
... and then cross browser you'll have to implement json2.js:
https://github.com/douglascrockford/JSON-js
I don't see where your var named soap is being used. It looks like it should be the "data: " that's being sent to the SOAP service, but there's something called bhRequest there instead.
Also make sure you're allowing Phonegap access to your remote server with
<access subdomains="true" origin="*" />
in your config.xml. When you get things working you can make it more restrictive by limiting it to your icafe.ipos.vn domain.
Related
I have an ASP.NET application sending data through AJAX to a handler withing my application. This works as it should when debugging locally, but as soon as I deploy the solution to the server, the handler only receives an empty string. I tried fiddling around with contentType and dataType, but without luck.
Here is my code so far.
aspx of the sending page, while "myData" is a simple string:
$.ajax({
type: "POST",
url: "handlers/changeRiskGroup.ashx",
data: myData,
// tried all those content/dataTypes without any luck
//contentType: "text/plain",
//dataType: "text",
//contentType: "application/json; charset=utf-8",
//dataType: "json",
error: function (xhr, status, error) {
console.log(xhr.responseText);
},
success: function (msg) {
console.log(msg);
}
});
.ashx.cs of the receiving handler:
public void ProcessRequest(HttpContext context) {
//string data = new StreamReader(context.Request.InputStream).ReadToEnd();
var data = String.Empty;
context.Request.InputStream.Position = 0;
using(var inputStream = new StreamReader(context.Request.InputStream)) {
data = inputStream.ReadToEnd();
}
if (data != "") {
// doing something with my data here.
// this is never reached while on the server, but works fine locally!
} else {
context.Response.Write("Please supply data to the risk group service!");
}
}
public bool IsReusable {
get {
return false;
}
}
}
The data variable in the .ashx.cs file is filled when debugging locally, but always "" on the server. I have no clue why.
var para={};
para.myData="abcd"
$.ajax({
type: "POST",
url: "handlers/changeRiskGroup.ashx",
data: para,
error: function (xhr, status, error) {
console.log(xhr.responseText);
},
success: function (msg) {
console.log(msg);
}
});
from server side
string myData=contect.Request.Form["myData"].toString();
Easy, just took me ~20 hours to figure out. Found the answer here: Web service returns "301 error moved permanently" in production environment
In short, I created a blank page within my project to ensure no plugins etc were interfering with the jQuery execution. Further, I created a very simple mask to submit certain data to the handler URL. Within this mask I varied different ways to POST data, when I tried implementing the POST as a [WebMethod] I finally got a clue, as the response was "301 moved permanently" from the WebMethod. Therefore I could start investigating and found out that my server was lowercasing the urls, obviously jQuery/HTTP does not like that.
I hope this post helps others struggling with similar problems.
I am getting this error "There was an error processing the request" in the UAT environment. In my local, the code seems to be working fine.
This line Utility.WriteLogEvent("TestService", strMessage); is writing directly to db. Either way if this line fails or not, I should still be able to recieve a message coming from the server since it is properly handled.
But since I don't receive any response from the server, that means my webmethod is not reachable.
Given that the code below works, is there anything that I need to set in the web.config to make this work? Or anywhere I can start inspecting on the IIS that could give me some clues?
Thanks.
$('#lnkTest').click(function () {
alert('Click event is firing!');
$.ajax({
type: "POST",
url: "/_layouts/ServiceForm.aspx/TestService",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response.d && response.d.length > 0) {
alert(response.d);
}
},
error: function (xhr, err) {
alert('responseText:' + xhr.responseText);
}
});
});
Here is my c# web method
[WebMethod]
public static string TestService()
{
string strMessage = string.Empty;
try
{
strMessage = "The service is running.";
Utility.WriteLogEvent("TestService", strMessage);
}
catch (Exception ex)
{
strMessage = "TestService fail.";
}
return strMessage;
}
For others who might come across the same error while calling a WebMethod with parameters.
Ensure that none of the arguments are empty as that also throws the same error without a proper reason. Provide a solution to prevent empty arguments from being passed to the Method on the client side. Perhaps an if statement.
I have resolved the issue. This is due to a dll deployed in the application server and it was blocked by the installed antivirus.
I have a page called: tar-url.com
I want to ping target page with a PUT request viai C#.
I want to return a Success or Error to client.
This exists and works with all clients NOT IE.
var xml = "[XMLDOC]";
$.ajax({
type: "PUT",
contentType: "multipart-form",
url: "tar-url.com",
headers: {Authorization: "Basic herpderp="},
data: xml
success: function(){console.log("success");},
error: function(){console.log("error");}
});
This is the request i normally do. It works in my old format, but there is 1 hitch, it doesnt work in IE9, SO i came up with this brilliant idea; Have my server do it, not the browser.
I create a Generic Handler: gHand.ashx which allows me to carry out my calls.
I do this for some other calls, but it is simple GET requests, that return some JSON. Here is where i need help.
I create my method as given in C#:
public void ProcessRequest(HttpContext context)
{
WebClient wsb = new WebClient();
//pass *tar-url.com here*.
string url = context.Request.QueryString["url"];
//pass contentType here.
string ct = context.Request.QueryString["contextType"];
string type = context.Request.QueryString["type"];
string headers = context.Request.QueryString["headers"];
//not sure how to access the xml?
// something like this?
string xml = context.Request.QueryString["save"];
//HERE I NEED TO ASSIGN REST OF STUFF TO *wsg*
string response = wsb.DownloadString(url);
context.Response.Write(response);
}
How i Call it in javascript:
$.ajax({
url:"gHand.ashx",
type: "get",
data: JSON.stringify({
save: xml,
type: "PUT",
url: "tar-url.com",
contentType: "multipart/form",
headers:{ Authorization: "Basic HerpDerp="}
}),
success: function(){...},
error: function(){...}
});
My calls are all seeming to be correct in the sense that i can build a WebClient and execute similar scripts, but it seems that this particular set up boggles my mind.
Edit: Has anyone any idea?
When you send your data to the server, you will want to decode it.
example:
You are sending a map of:
{
save:xml,
url: url,
type:type,
contenType: ct,
headers:{...}
}
So you can look at that and say, similar to how it says:
string url = context.Request.QueryString["url"];
and proceed as normal. Your REQUEST TYPE is the last thing you should check because it determines HOW your WebClient object will react.
Since data is going to be saved, instead of you doing
wsb.DownloadString(url);
which is more or less a get request, you would want to do something like:
wsb.uploadString(URL, METHOD, DATA);
Since you are pushing an XML DOC, or:
wsb.uploadData(URL, METHOD, DATA);
if you are uploading images.
Source: http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx
It doesnt matter which order you assign variables, but when you call uploadData, it is executing the webclient request. There is NOT an wsb.execute() command.
[I realise this might seem like a stupid question but I am lost.]
Using umbraco 4.9 I have a multi-lingual site where I have made an event handler to replicate content nodes to all languages as they are created in the back office to all languages. I am now trying to attach this to a custom context menu item(umbraco.interfaces.IAction) to give the creator a choice.
In the context menu item it is only possible to call a javascript function as a string. I shouldn't touch the umbraco code itself so how can I pass a value to a web service? Where do I include the reference?
This is what I have at the moment:
public string JsSource
{
get
{
return "function AddItem(){" +
"var multiLang = confirm('Create for all languages?');" +
//"$.ajax({" +
//"type: 'Post'," +
//"url: 'TryAgain.aspx/' + SendMultiVal" +
//"data: multiLang})" +
//"PageMethods.SendMulti(multiLang);}" +
string.Format("{0}.actionNew()", ClientTools.Scripts.GetAppActions)+"};";
}
}
Thanks in advance.
So the first thing that you need to do is to store the boolean value in a variable called boolvalue and then call the callservice function once you have the value.For eg:
CallService("POST", "YourServiceUrl",boolvalue,
function (data) {
alert("Service Call Success");
},
function (result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
});
This will make a service call and get data from service if it returns some data.
CallService = function (method, serviceUrl, value, successHandler, errorHandler) {
$.ajax({
type: method,
url: serviceUrl,
contentType: "application/text; charset=utf-8",
dataType: "json",
data:JSON.stringify(value),
success: successHandler,
error: errorHandler
});
};
Modify the dataType and dataType fields depending upon the type of data that you send and receive from the service.
Look into this if you need more information:
http://api.jquery.com/jQuery.ajax/
Let me know if this works out for you.
I want to post data to a web service with ajax. there is my ajax code:
function Looping() {
var Grid = document.getElementById("<%= gvHastalar.ClientID %>");
var Row;
var Cell;
if (Grid.rows.length > 2) {
for (i = 1; i < Grid.rows.length - 1; i++) {
Row = Grid.rows[i];
Cell = Row.cells[3];
alert(Cell.innerHTML);
var html = $.ajax(
{
type: "POST",
url: "http://localhost:7753/HastaTahlilUyariServisi.asmx/f_HastaninAktarilacakAlislabTestleri",
data: "{_sTcKimlikNo:" + Cell.innerHTML + ",_iKlinikKodu:18001,_bAy:12,_iYil:2009}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: alert('success'),
error: alert('error')
}
).responseText;
Row.style.backgroundColor = "#D3EFD1";
}
}
}
And my webservice function's code is here:
[WebMethod]
[SoapHeader("_ticket", Direction = SoapHeaderDirection.In)]//SoapHeaderDirection.Out
public DataSet f_HastaninAlisLabTahlilleri(string _sTcKimlikNo, int _iKlinikKodu, byte _bAy, int _iYil)
{
try
{
string QSelect =
#"SELECT * FROM [V_EUCLID_SONUC]
WHERE MONTH(KAYITTARIHI) = " + _bAy + #"
AND YEAR(KAYITTARIHI) = " + _iYil +
AND TCKIMLIKNO = '" + _sTcKimlikNo + #"'";
return dbA.ExecuteDataSet(CommandType.Text, QSelect);
}
catch (Exception ex)
{
throw (ex);
}
}
There is a break point on function which is in the web service but debug never go that break point. I pasted webservice's url from browser but may be url is wrong. And when i run project, i have 3 alert.
First Cell's text its normal.Second alert is success and the last alert is error. I want to send parameters to f_HastaninAlisLabTahlilleri and user return dataset. How can i do this?
Thanks in advance
Here are a few remarks about your code:
success and error are callback functions, they should be defined like this:
success: function(data) { alert('success'); },
error: function(XMLHttpRequest, textStatus, errorThrown) { alert('error'); }
ASMX web services use SOAP by default unless you decorate them with ScriptServiceAttribute in which case JSON could be used to invoke a method. It is not clear from your code if the web service is decorated with this attribute.
When you pass parameters, you need to encode them, use JSON. stringify instead of concatenating strings:
data: JSON.stringify({_sTcKimlikNo: Cell.innerHTML,
_iKlinikKodu: 18001,
_bAy: 12,_iYil: 2009});
Use FireBug to inspect network AJAX requests and server responses and post them on StackOverflow to facilitate debugging.
You cannot put a break-point in the web-service code i.e. even the IDE would not let u debug the web-service code.... it is an old legacy the VS.Net IDE has since its inception... lets see if it is resolved in VS 2010.
The url that you have specified in the JQuery script is not equal to the name of the function in c# code. Isn't it the point. *f_HastaninAktarilacakAlislabTestleri* in url and *f_HastaninAlisLabTahlilleri* in c# code. Some reasons for such a problem can be wrong url or deference between argument list of client request and argument list of the server side method or action.