I need to call a WebMethod that returns an integer, this integer is then displayed to the user in a confirm message. If they confirm then I need to call a second WebMethod and then alert them of the result via an alert message.
When I do this, everything works fine except for the second success function. That function is never reached, and the user is never alerted as a result.
This is example JavaScript of my situation:
$( "a" ).live( "click", function() {
PageMethod.GetCount(OnSucceed, OnFail);
});
OnSucceed(result)
{
var retVal = Confirm(result);
if(retVal == false)
return false;
PageMethod.Create(Succ, OnFail); //Produces the correct files
}
function Succ(resultStr)
{
alert(resultStr); //This is never reached
}
function OnFail(error)
{
alert(error);
}
Well .. It can be for different reasons
You have an error calling the second PageMethod. You can check your console to see if you have "500 INTERNALL ERROR".
The problem is before calling the page method but guessing you have already checked your PageMethod this is not likely.
You are calling PAGEMETHODS from your JS codes, but you mentioned WebMethods which are 2 different things. Make sure what is that are
you really calling.
your PageMethod/WebMethod does not return anything
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 following Javascript code snippet :
authData=ref.getAuth();
if(authData == null){
//TODO find an elegant way to manage authorization
// window.location = "../index.html";
} else {
ref.child("users").child(authData.uid).on("value", function(snapshot){
$( "span.user-name").html(snapshot.val().displayName);
loggedInUser.displayName = snapshot.val().displayName;
//alert("Name inside : "+loggedInUser.displayName);
//Here it displays the value
});
}
alert("Nameada is out : "+loggedInUser.displayName);
//Here it shows 'undefined'
why?
I want to use the variable value loggedInUser.displayName where did I shown alert.
Can someone please help me in accessing the value and displaying the alert?
Thanks.
Your final alert is executed when the callback function (function(snapshot){ ... }) has not yet been called. Note that the callback function is called asynchronously, so it only gets executed after the currently running code has completed and the value event is triggered.
This also explains why the inner (commented out) alert does work. Just realise that this piece of code (the call back function) is executed later than the other alert, even though it occurs earlier in your code.
You could "solve" it by calling another function from within the call back, like this:
authData=ref.getAuth();
if(authData == null){
//TODO find an elegant way to manage authorization
// window.location = "../index.html";
} else {
ref.child("users").child(authData.uid).on("value", function(snapshot){
$( "span.user-name").html(snapshot.val().displayName);
loggedInUser.displayName = snapshot.val().displayName;
whenUserLogged();
});
}
function whenUserLogged() {
alert("Name : "+loggedInUser.displayName);
// anything else you want to do....
}
Some suggestions for improvement
Don't use too many global variables (in your code all of them are global), and instead pass variables as function arguments.
You may want to look into promises.
I am creating a jquery plugin. In that am using some global variablse
$.rmtableparams.recordsCount: 0 is one of them.
I am assigned some values to this from one function inside an ajax call.
callAjax = function (surl, pselector, pi, rec) {
$.ajax({
..
success: function (data) {
$.rmtableparams.recordsCount =10;
}
});
}
But while I am trying to access $.rmtableparams.recordsCount in some other function it returns 0. But strange thing is that if i alert anything before that it will returns 10 correctly.
Ie: if my script is
alert("hi");
alert($.rmtableparams.recordsCount);
the second alert will shows 10
But if only alert($.rmtableparams.recordsCount); is there it returns 0
I was wondered with this. If any body knows the reason please help me.
The assignment $.rmtableparams.recordsCount =10; is inside the success callback of an $.ajax request. So the value isn't assigned until the ajax call is completed, and a response received. This happens fairly quickly, so while you're first alert is waiting to be closed, the ajax response is received, and the assignment is processed. Then, the second alert shows the new value.
If you leave out the first alert, the call is still being processed and the $.rmtableparams.recordsCount value hasn't changed yet.
It's as simple as that: AJAX stands for Asynchronous JavaScript And XML. Async is key, but often overlooked...
You can't just go ahead and set $.rmtableparams.recordsCount because $.rmtableparams doesn't exist.
You first need to set $.rmtableparams:
$.rmtableparams = {};
Then you go ahead and add data to the object:
$.rmtableparams.recordsCount = 10;
Make sure that the success callback is being fired. Add an alert or console.log inside the callback to do the check.
Can someone one explain it please?
Why alert 2 pops before alert 1?
Why value of pageCount in alert 1 is different than alert 2?
function naviSet()
{
var pageCount;
if($.ajax({
type: "POST",
url: "http://localhost/mywebsite/wp-content/themes/twentyeleven/more-projects.php",
success:function(data)
{
pageCount = data;
alert(pageCount); //alert 1
return true;
},
error:function()
{
$("#direction").html("Unable to load projects").show();
return false;
}
})) alert(pageCount); //alert 2
}
The alert1 is inside a callback - this function will only be called when the ajax request completes successfully (ie asynchronously).
The pageCount is different for the same reason - the success callback has not been made when alert2 is called.
As most answers mention you make an asynchronous call, but thats not really the reason. So JavaScript is single threaded, only on think can be done per time.
So first you call your function and this function will put on the execution context stack. This function will be executed before any other function that will be added to stack can be executed. In this function you make your ajax call and on success the success function will be put on the execution context stack. So this function could never ever called before naviSet. As alert1 is made in the naviSet function it will be the called first.
And to your second question:
From your function I think you believe, when $.ajax() returns true, your ajax call was succesful and pageCount was set to data. But it isn't. $.ajax doesn't return true but the truethy value $. Its a function that return reference to the main jquery object, so you can chain function calls.
function naviSet()
{
//you create a new var which is undefined
var pageCount;
// return $ which is a truethy in JavaScript, but it does not mean the ajax call was successful
if($.ajax({
type: "POST",
url: "http://localhost/mywebsite/wp-content/themes/twentyeleven/more-projects.php",
success:function(data)
{
// now you in the context of your success function
// and set the value of your variable to data
pageCount = data;
alert(pageCount); //alert 1
return true;
},
error:function()
{
$("#direction").html("Unable to load projects").show();
return false;
}
}))
//here you are still in the context of your naviSet function where pageCount is undefined
alert(pageCount); //alert 2
}
Why alert 2 pops before alert 1?
Alert 1 is fired by the callback function that is fired when a successful HTTP response has been received.
Alert 2 fires as soon as the HTTP request has been sent.
Networks are slow.
Why value of pageCount in alert 1 is different than alert 2?
Because it is changed when the response has been received (just before it is alerted), by the same callback function as mentioned above.
The ajax-function retrieves data from the given url asynchronously. That means that it is doing it in the background, while the rest of your code executes. As soon as it is finished, the function assigned to "success" is called (or "error", if it fails).
The second alert is called first because of this. Like I said, the rest of the code continues execution while the ajax-function is working.
The reason the second alert happens first is because the ajax call is asynchronous. It essentially schedules a web call and returns immediately. Hence the line after it which is the second alert happens directly after.
At some point later in time the web request will complete and call into the success function. Hence the first alert happens at that point
Here's my code
errors=0;
$(document).ready(function () {
var chk=$("#usnm").val();
$.post("register.php",{'chkuser':chk},function(data){
if(data==" Username already exists.Choose a new one"){
errors++;
alert(errors);
$("#alerts").html(data);
}
});
if(errors==0){
alert(errors+"post");
}
});
Here, the first alert gives me a "1" whereas the second alert runs, so therefore it give me '0post' . What i'd like to know is: How is the value of the variable errors, changing to 0 all of a sudden after being 1 ?
Thanks
Change errors=0; to var errors=0;
and put the error check inside the $.post function:
$.post("register.php",{'chkuser':chk},function(data){
if(data==" Username already exists.Choose a new one"){
errors++;
alert(errors);
$("#alerts").html(data);
}
if(errors==0){
alert(errors+"post");
}
});
jquery.post is called asynchronously. you might be debugging it locally otherwise the second alert would go on the first place. anyways because it runs async the value is different inside and outside the post function