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
}
});
}
Related
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.
I've been trying to read as much as I can about javascript callbacks and jquery deferred objects but apparently things just aren't clicking for me. It seems to make a vague amount of sense when I read through it and practice examples, but when I try to apply it to my specific problem, I'm just hitting a wall. If anyone can understand what I'm trying to do and offer ideas, it would be much appreciated!
Here's some existing code:
$(document).ready(function() {
firstFunction();
secondFunction();
});
For the sake of keeping things simple here, I won't get into what firstFunction() and secondFunction() do, but suffice it to say that they both perform asynchronous work.
Here's my problem:
firstFunction() is dependent on the document being ready so needs to be inside $(document).ready(function() { }. secondFunction() isn't dependent on $(document).ready(function(), but should only execute after firstFunction has completed. I'm hoping to do all the computation for secondFunction() before the $(document).ready(function() { } block, but only execute it after firstFunction() has completed. This way firstFunction and secondFunction will execute in a more visually seamless manner. So basically, I'd like to do something like the following pseudo code:
var deferredSecondFunction = secondFunction().compute().defer(); //perform computation for secondFunction but defer execution
$(document).ready(function() {
firstFunction().done.execute(deferredSecondFunction().execute()); //finally execute secondFunction once firstFunction has completed.
});
Does anyone know if this is even possible? An important caveat is that I need to do this without the Javascript Promise object, since, for reasons outside the scope of this question, the webkit I'm working with is an old version. If anyone could help me understand this it would be appreciated!
The code shown uses a callback function and a self-invoking anonymous JavaScript function such has:
var calculatedObject;
(function(){
// Will be executed as soon as browser interprets it.
// write code here & save your calculations/operations
calculatedObject = { ... };
})();
function firstFunction(callback){
// Do stuff
callback();
}
function secondFunction(){
// Do more stuff
// Use your calculations saved in the calculated object.
}
$(document).ready(function(){
firstFunction(secondFunction);
});
This way the second function will only be called at the end of the first one.
you can use a callback..
function f1(){
//do some stuff
}
function f2(callback){
// do some async stuff
callback();
}
f2(f1);
this example passes one function to another function. the second function then calls the first whenever it's ready.
I have read other answers here and couldn't exactly match my issue. Should be simple for someone with lots of experience in Promises. Code below, I need help fixing up the Recursive function because everything that happens in that ajax call is not available in first done. Code below will explain (Note the TypeScript syntax):
//Main
private Start(){
this.PopulateSomething().done(() => {
alert('done');
});
}
private PopulateSomething(): JQueryPromise<any> {
var dfd: JQueryDeferred<any> = jQuery.Deferred<any>();
//app.ExecuteAjax is just a wrapper for a ajax call.. note i'm using callbacks
app.ExecuteAjax("SomeParamater1", function (returnedObject) {
//Do something with returnedObject
$.each(returnedObject.something, function () {
app.RecursivelyDoSomething(this);
});
dfd.resolve();
});
return dfd.promise();
}
private RecursivelyDoSomething(Thing: any) {
//Do something with Thing
//Anything that happens within this Ajax call is not available when alert('done'); is executed
app.ExecuteAjax("SomeParamater1", function (returnedObject) {
$.each(returnedObject.something, function () {
app.RecursivelyDoSomething(this);
});
});
}
Seems you want to recursively make ajax queries and only want to execute done after the last one. One way to do that would be to keep a count of pending ajax queries, increment this count based on Thing and decrement this count from based on Ajax finishing. And then only resolve dfd once count = 0.
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'));
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.