Calling a C# webservice from the Success function of another Webservice? - javascript

My question is simple. Can you call a C# webservice from the Success function of another webservice? I think that the answer is no.
I have a login webservice which is called when a user tries to do something that requires the user to be logged in. This then calls another webservice, when the action is complete it does not go into the onSuccess function. I am assuming that it is not able to do so? Is this correct?
Example code, not actual code.
webservice.login(onLoginSuccess)
function onLoginSuccess(){
webservice.doSomething(onDoSomethingSuccess)
}
function onDoSomethingSuccess(){
.... does not get here.
}
This is the code to it's bare bones.
On client JavaScript call, success of login webservice.
function onLoginSuccess(result){
negotiateWithUser(true,
activeUser.id,
negotiation.dateID,
activeUser.showChat,
true);
}
function negotiateWithUser() {
<code>
if (justLoggedIn) updateDateData();
<code>
}
function updateDateData(){
if (populate==false){
populate=true;
WebService.Negotiations.DatesGet(activeUser.id,SucceededtoCallbackDateRefresh, ErrorHandler);
}
}
Does not go into the function SucceededtoCallbackDateRefresh even though data is returned and there are no errors.
I think I know what the problem is, in the negotiateWithUser function the updateDateData is called, execution control is given back to the negotiateWithUser function instead of going into the SucceededtoCallbackDateRefresh success funtion, as it is an asynchronous call. I think some kind of callback function is required.
I have got round the problem by calling the updataDateData function in a setInterval() in the onLoginSuccess function instead.
function onLoginSuccess(result){
if (negotiate) {
timerInterval = setInterval("updateDateData()", 300);
}
}
It works. If someone has a more graceful approach, I would be very interested.
Thanks.

How about to use jQuery.ajax()?
function Func1() {
$.ajax({
url:'MyWebService.asmx/Func1',
success:Func1Success,
error: function () {
alert('there was an error!');
},
});
return false;
}
function Func1Success(output){
$.ajax({
url:'MyWebService.asmx/Func2',
success:Func1SuccessToSuccess,
error: function () {
alert('there was an error!');
},
});
}
function Func1SuccessToSuccess() {
return false;
}

You definitely can.
Just to give a suggestion/advice theoretically, you can have 1 local variable for the status response of the first web service method, you can have it as boolean, representing the success of the first invocation. Then sequentially, you can call the other web service method if your local variable matches your success condition.
What I provided is just an idea, for a more specific answer, I recommend you posting the actual code you're working on.
Thanks.

I am assuming you are using .cs files on your server and then calling them from android.
If this is what you are doing then there is one way to call a method on success of another method. Just make two .cs files say x and y and store it on your server. Then call one of them from android (x) and then make object of y in x and that will be all.
for eg. This is my one .cs file named abc.cs which il call from android.
[WebMethod]
public xyz IsLoggedIn()
{
xyz example = new xyz();
//do something
.
.
return example;
}
now xyz.cs will be:
[WebMethod]
public void onSuccessofIsLoggedIn()
{
//do something
.
.
}
i hope this helps.... All this is just based on assumption though...please be clear about what you are using and we will be also more clear in our answers.

Related

Writing jQuery inside a Javascript function not working

I have a js file called example.js which has a line as follows:
gridOptions.api.setRowData(createRowData());
Then there's another file data.js which has the createRowData() function that should return ROW_DATA. It is as follows:
function createRowData() {
jQuery.getJSON('/file.txt',function(ROW_DATA){
return ROW_DATA;
});
}
But, whenever this createRowData() function is called from example.js file, it does not go inside the jQuery block and simply comes to the last curly bracket. Can anyone please tell me what is going wrong here??
I believe that you're not getting the value because getJSON is asynchronous as others have said. createRowData is retrieving the value at a later time rather than when it's called.
Here is one way to get the data with promises. I commented what's going on below:
function createRowData() {
//return a new promise
return new Promise(function(resolve, reject){
jQuery.getJSON('/file.txt',function(ROW_DATA){
//on reject, send an error
if (ROW_DATA === null) reject("Error fetching data");
//on resolve, send the row data
return resolve(ROW_DATA);
});
});
}
//use then to describe what happens after the ajax request is done
gridOptions.api.setRowData(createRowData()).then(function(rowdata){
return rowdata; //log data or error
})
Edit: to do a synchronous ajax request, you may be able to do something like this, referring to this SO question.
function createRowData() {
$.ajax({
url: "/file.txt'",
async: false,
success: function(rowdata){
return rowdata
}
})
}
To read some data to a variable like you mentioned, nodejs may help because it can handle reading input/output, and probably to a variable as well.:
You get JSON from the file, pass the result to the callback function, and then return it. Return it where??
As I said, your anonymous function is a callback one.
Program says: When you are done reading from the file, call this function, OK?.
While you do that, I am doing something else.
And that is what it does. The program, would go on, until the file is read, when your callback anonymous function would be called.
You can do sth like this.
createRowData(gridOptions.api);
// add code here if you want this code to execute even before you get the response
function createRowData(api) {
jQuery.getJSON('/file.txt',function(ROW_DATA,api){
api.setRowData(ROW_DATA);
//Whatever else you want to do. In case you want this to be done only
//after the values have been read
});
}
If you want to wait, for the file to be read, just, dont do anything after the function, but put it inside the callback function.

How to make function response synchronous with the other statements in the other function

function test() {
/*some business logic*/
return response;
}
function calculate() {
if (test() == true) {
console.log("Success");
} else {
console.log("Fail");
}
}
my test function is in different js file which does some business processing (processing takes some time) on data and return boolean response.
I am calling test function from calculate function (in different js file).
I am expecting console output as 'success'(test function always return true), but it is giving me 'Fail'. But if I debug this code and wait sometimes on '(if(test()==true))' then i get expected output . Basically it is a synchronization issue. How can i solve that?
I try to modify your code little bit to cater for your need which make use of JQuery Deferred object.
If you comment out "deferred.reject()", you should get the case when your function is considered as failed.
It would make your function waiting for another function to give a response.
var test = function(){
var deferred = $.Deferred();
setTimeout(function(){
deferred.resolve(); //deferred.reject();
},3000);
return deferred.promise();
};
test().done(function(){
console.log("success");})
.fail(function(){
console.log("fail");})
I think from the codes above, you would not have any problems to get "Success" route run. It really depends on how does your business logic run. If they are running in asynchronize manner then you should probably using event driven model to run your calculation logic. For example, you register an event via document.addEventListener('testCompleted', caculate()) and then you fire this event in test().
Hope it helps.

Make js functions execute one after another

Note : No jQuery
I have four functions and I want to call them one after another ie. call a function after the previously called function is executed (in core js, not jquery). I tried searching in the internet but I could not find a satisfied answer. Here is what I've done so far :
function func1() {
noAjaxCall.click();
return true;
}
function func2() {
ajaxCall.click(); <--------- sending an ajax request
return true;
}
function func3() {
noAjaxCall.click();
return true;
}
function func4() {
//anything here
}
if(func1())
if(func2())
if(func3())
func4();
What happens is that, func3 is not called. Why this happens and any work around to this?
Thanks!
I'm sure you're not doing what you expect.
The AjaxCall is not really done when func3 will be called, cause... it's asynchronous.
I prefere you find the real solution (what you really wanna do) than trying to solve this problem.
Could you give the real goal you try to achieve?
edit
Let's imagime the handle on 'click' for ajaxCall. I know u don't have jQuery on the app but I create what I know.
function requester(){
//do some asyn work
$.ajax({ //...
success: function() {
//HERE call the other functions
}
});
}

How do I pass an action to a javascript function

I could explain my problem but it is likely easier to demonstrate it...
If you take a look at http://jsfiddle.net/XxT2B/ you'll see my issue. I am having trouble figuring out how to pass an action to a function. You'll see what I mean.
Please note that the action could be different based on what calls the function. The action may be an alert on time and something different the next.
Here is my code...
function abc(action)
{
//Do a bunch of stuff first and then do the action sent to this function
alert('This function is named "abc"');
//This is the part I do not know how to do.
//The action might be an alert or something totally different so I can't just pass text
//I need to know how to execute the action passed.
action;
}
abc('alert("I like pizza")');
You can pass a function as a parameter to another function.
function abc(action)
{
//Do a bunch of stuff first and then do the action sent to this function
alert('This function is named "abc"');
action();
}
abc(function(){
alert("I like pizza");
});
You can pass a function into abc(), but be sure to sanitize
function abc(action)
{
alert('This function is named "abc"');
if(typeof(action) == "function") { //sanitize
action();
}
}
abc('alert("I like pizza")'); //will execute without a problem
abc(50); //will not run, since 50 is not a function
The good way:
Pass it as a function:
function abc(action)
{
//Do a bunch of stuff first and then do the action sent to this function
alert('This function is named "abc"');
action();
}
abc(function(){alert("I like pizza")});
the bad way (if your actions need to be strings):
function abc(action)
{
//Do a bunch of stuff first and then do the action sent to this function
alert('This function is named "abc"');
eval(action);
}
abc('alert("I like pizza")');
The second way is not advised because eval causes issues. It can run arbitrary code that can cause unexpected side effects, prevents compiler optimizations, and leads to difficulty debugging (since it can literally do anything depending on what you pass it). More on why eval is bad here.
But it will run an arbitrary string as javascript code like you were asking.
You just need to instantiate a function:
abc(function() { alert("I like pizza"); });
edit and then to call it, you use the value of your parameter exactly as if it were a function name (because, well it is!):
action();
You can use the eval method:
function abc(action)
{
//Do a bunch of stuff first and then do the action sent to this function
alert('This function is named "abc"');
eval(action);
}
abc('alert("I like pizza")');
And that's that.
Don't know what JavaScript version supports this syntax but you also can try:
function abc(action) {
if (typeof(action) != 'function')
return;
action();
}
abc(() => console.log('A B C'));

Calling jQuery Function with Javascript Function

Having some trouble getting this to work, specifically with $.getJSON(). I want to wrap the getJSON function from jQuery in a Javascript function like so:
function reload_data() {
$.getJSON("data/source", function(data) {
$.d = data;
});
}
But when I call reload_data() it doesn't execute the jQuery function inside. Any ideas?
You're not telling us enough. I will just take a guess!
If you are calling this function, and then immediately checking $.d for the results, that is not going to work because you don't allow time for the asynchronous AJAX request to complete...
reload_data();
alert($.d); // What?! It's not displaying the updated results?!
You'll have to utilize a callback structure, like jQuery uses, in order to make it work...
reload_data(function() {
alert($.d);
});
function reload_data(func) {
$.getJSON("data/source", function(data) {
$.d = data;
//Execute the callback, now that this functions job is done
if(func)
func();
});
}
Put an Alert in side the function to know its getting called.
and a try catch around the jQuery call to see if there is an error
function reload_data() {
alert('reload_data start');
try{
$.getJSON("data/source", function(data) {
$.d = data;
});
}
catch (ex){
alert ('error in jQuery call:' + ex)
}
}
Thanks for the help everyone, but the solution was actually really simple. It was just a matter of synchronization. The page was reloading before the JSON data got reloaded, so that's why I wasn't seeing an error.

Categories