Calling WebService from Ajax/Javascript - c#

I am getting into a little jam here. I created a webservice using C#. When I Invoke the WebService it works fine. The Javascript seems to be hitting the webservice, breaking, and then follows through with the rest of the operation. I think this is a matter of me calling the WebService wrong. I've searched all over and have found tons of different examples, however, none of them seem to work.
If you go to http://success.darkslidedesign.com it triggers test.js which then calls my web service located here: http://www.darkslidedesign.com/services/ms_Alert.asmx
Here is the test.js code -
var xmlHttp;
setTimeout("sendMessage('rory#careercheatcode.com');", 2000);
function doUpdate()
{
if(xmlHttp.readyState===4){
alert("Worked");
}
else{
alert("Broke");
}
}
function sendMessage(strTo)
{
try{
// Opera 8.0+, Firefox, Safari
xmlHttp = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Ajax is not supported
return false;
}
}
}
xmlHttp.open("post", "http://www.darkslidedesign.com/services/ms_Alert.asmx", true);
var params = "op=Sending_Email&strEmailAddrFrom=rory#darkslidedesign.com&strEmailAddrTo=" + strTo;
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange=doUpdate;
xmlHttp.send(params);
return false;
}

You better start with jQuery $.ajax()
Here is one snippet that works for me to post comment from a textbox.
function Post() {
var ow = "username";
var cmt = $("#comment").val();
$.ajax(
{
type: "POST",
url: "/comment/Save",
dataType: "json",
data: "id=2332&author=" + ow + "&cmt=" + cmt,
success: function (result) {
if (result.status === "OK") {
alert('Comment posted');
}
else
alert("Post failed");
},
error: function (req, status, error) {
alert("Sorry! Post failed due to error");
}
});
}
Hope this will guide you.
Thanks

For web service calls from Javascript, I use two things:
jQuery, as pixelbobby mentioned. It is a walk in the park and makes everything super awesome-sauce!
I use the asp.net MVC framework. It is far too verbose for me to explain it here, but it is pretty easy to get it up and running. Basically, you create a controller class, create some methods, and return json-serialized values. You might also have to add some routes to your global.asax file.
I would definately recommend reading up on both of these things... They are both pretty awesome!

Related

How to call API in c# using angularjs

Hi I am calling my API using below code
$http.get('/api/controller/method?param=value').
then(function (response) {
if (response.status == 200) {
console.log(response.data);
}
});
It is working fine in my local machine (http://localhost/api/controller/method?param=value).
But when I deployed it in server with application name app, it is not able to call the API(http://server-ip/app/api/controller/method?param=value).
Obviously, it won't, as URL are different. So what is the correct way to call an API in c# so that it will work in any server.
What I have tried:
1. URL.Action : It is not working in this case.
2. I don't want to Use #HTML.hidden
3. Call starting with or without slash (/)
I usually solve this by using a factory like this -
First in the .cshtml page I load all the angular js required.
Then create a factory for the baseURL like this -
function(angular){
var module = angular.module('NameOfMyModule'); //gt the module
module.factory('BaseUrl', function(){
return '#Url.Action("Action", "Controller")';
});
}(window.angular);
Then inject that BaseURL inside the controller -
....
module.controller('SomeController', [...., 'BaseUrl', function(...., BaseUrl){
$scope.baseUrl = BaseUrl;
}]);
....`
Finally prepend it in the url
$http.get($scope.baseUrl + /...../).then(....);
I'm not sure if I undestood your question correctly, but I'm using angular constant to set server url
angular.constant("CONSTS", {
"DEV_URL": "http://localhost:12345",
"LIVE_URL": "http://server-ip/app"
})
and then in $http call
$http.get(CONSTS.DEV_URL + '/api/controller/method?param=value').
then(function (response) {
if (response.status == 200) {
console.log(response.data);
}
});
I'm sure there is a way to automate this (gulp, grunt), but I didn't get there yet.
When deploying the app I would just manually change the constant.
If I'll find outomatic way to it I'll update the answer.
Hope this helps a bit...
I don't know your build process etc. but usually you can store application path in some constant value in Angular and use it when calling your API as a prefix.
If you have some kind of automated build, it is easy to prepare deployment packages with changed values(by using Gulp/Grunt/TeamCity/Octopus, whatever you like).
//controller
app.controller("sampleController", function($scope, commonService) {
//post
$scope.postData = function() {
var command = {}
commonService.postSample(command);
}
//get
commonService.getSample().then(function(data) {
$scope.permissionList = data;
});
});
//service
app.service('commonService', function($http, $q) {
this.postSample = function(command) {
var deferred = $q.defer();
$http({
method: 'POST',
data: command,
url: '/Attendance/CreatePersonDailyLeave'
})
.success(function(data) {
deferred.resolve(data);
})
.error(function(data) {
deferred.reject(data);
});
return deferred.promise;
}
this.getSample = function(id) {
var deferred = $q.defer();
$http({
method: 'GET',
async: true,
url: '/Attendance/GetRoles?id=' + id
})
.success(function(data) {
deferred.resolve(data);
})
.error(function(data) {
deferred.reject(data);
});
return deferred.promise;
}
});

Ajax not making function call

I have ajax function as:
function LoadTeacherObservationData(_CategoryID, _SearchText) {
alert("In here");
alert(_CategoryID);
alert(_SearchText);
flag = 1;
$.ajax({
url: "PP/getTeacherObservationData",
data: {
'CategoryID': _CategoryID,
'SearchText': _SearchText
},
dataType: "json",
type: 'POST',
cache:false,
success: function (data) {
OnlebelChange(_CategoryID);
$('#hdnCategoryID').val(_CategoryID);
$("#lvTeacherData").kendoListView({
dataSource: data,
dataBound: function(e) {
if(this.dataSource.data().length == 0){
//custom logic
$("#lvTeacherData").append("<h4> No record found.</h4>");
}},
template: kendo.template($("#lvTeacherData_Template").html())
});
},
error: function () {
alert("error in click");
}
});
}
I have made sure that function is getting called with correct parameters as i have checked it through alert box.
My problem is its not getting rendered to:
PP/getTeacherObservationData as i have mentioned in URL.
PP is my controller and getTeacherObservationData is my function.
I have written that function as follows:
public JsonResult getTeacherObservationData(string CategoryID, string SearchText)
{
try
{
if (CategoryID == "1")
return Json(new TeacherObservation().ScheduledObserVations(SearchText));
if (CategoryID == "2")
return Json(new TeacherObservation().InProcessObservations(SearchText));
if (CategoryID == "3")
return Json(new TeacherObservation().CompletedObservations(SearchText));
return Json(new List<TeacherObservation>());
}
catch (Exception ex)
{
throw ex;
}
}
Instead of calling this function ajax function code goes in error block and gives me alert as: error in click
What can be the problem??
Please help me.
I want to make function call through ajax.
Using MVC4.
Expanding on my comment: the URL PP/getTeacherObservationData is relative so if you are currently not in the root of the site, then this won't work.
Using a forward slash prefix /PP/getTeacherObservationData will work if your site is in the root of the domain.
You could also use one of the solutions in this answer. Such as ResolveUrl("~/") to dynamically get the site's root, which is better because it's more portable. For example if you move your site out of the domain's root and into a directory, this will continue to work unlike hard coding the root.
I don't know what PHP Framework you are using, but normally you can't just return a value to an AJAX call, you have to ouput it somehow to send it back to the caller. Try to use echo or print instead of return.
To prevent further rendering (if any), you should somehow end the script after it has echoed your specified JSON.
You should also check for the output that is rendered in firebug or similar consoles to see if you get a plain JSON (which you obvoiously expect) or some HTML wrapped content which is rendered by your php framework and connot be parsed.

How to get data from Soap service by jquery?

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.

How can we call AJAX in Firefox

I am making an AJAX call using the XMLHttpRequest.
It's working fine in IE7, but when i try the same in Firefox, I am not able to get it back thru the response.write
I am using the function below:
<script type="text/javascript">
function ddSelect_Change() {
var xmlhttp;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
}
}
}
xmlhttp.onreadystatechange = function () {
//alert(xmlhttp.responseText);
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
}
}
var url = "http://" + location.hostname + "Locationurl?Method=methodname";
xmlhttp.open("POST", url);
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlhttp.send();
}
ADDED
I have two separate web application one is tridion web application and other is custom web application. and i am making interaction from tridion web application to custom web application. Both the url are having different domain.and state i am getting 0 in firefox, and for readystate i am not getting (3) in my alert.
The code you've shown so far should work in Firefox. Firefox support XHR.
This might be at help: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
Update:
onreadystatechange is fired several times during an AJAX call, so you probably want to extend your callback to something like this:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
alert(xmlhttp.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
xmlhttp.readyState === 4 verifies that the request has completed, so that you don't try to alert the response before you actually have it. xmlhttp.status === 200 verifies that you recieved a 200 OK from the server, to make sure that there were no server-side errors, or that the URL was incorrect.
Have you considered using a library like jQuery? It already has taken care of these issues for you.
If you are working on a SDL Tridion GUI extension, check out the PowerTools project for a ton of examples. (http://code.google.com/p/tridion-2011-power-tools/)

Ajax post error

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.

Categories