[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 653
  • Last Modified:

$.get JQUERY AJAX

Hi, Please have a look over below code:

$(document).ready(function () {          
    $("#btnSubmit").click(function () {        
        var Proceed=1;
        $.get("../Sports/SprotsHandler.ashx",
                        {Tin_No:qs["SPT_No"]},
                        function (msg) {                  
                        Proceed=msg; //msg=100
                        });                      
       alert(Proceed); // This is still 1 and not 100 its get ting lost WHY? How can I prevent it?    

    the button is:
  <input id="btnSubmit" type="button" value="Submit" />        

Please help.

Dinesh
0
Dinesh Kumar
Asked:
Dinesh Kumar
  • 13
  • 6
  • 3
2 Solutions
 
JonNormanCommented:
$.get is asynchronous, this means that the call is made, but the success function that changes the proceed variable is not run until the answer comes back. The execution of the javascript code continues and you get the alert before the answer comes back.

The other problem that you have is that the underlying form will be submitted and the action on the form will be executed before the success function fires, which destroys the success function.

It's just a matter of timing...

The following code will fire the correct alert, and the form will not submit:
$(document).ready(function () {          
    $("#btnSubmit").click(function (event) {
        event.preventDefault();        
        var Proceed=1;
        $.get("../Sports/SprotsHandler.ashx",{Tin_No:qs["SPT_No"]},function (msg) {                  
                Proceed=msg; //msg=100
                alert (Proceed);
        });
});

Open in new window

0
 
Dinesh KumarAuthor Commented:
I tried:
$(document).ready(function () {          
    $("#btnSubmit").click(function (event) {
        event.preventDefault();        
        var Proceed=1;
        $.get("../Sports/SprotsHandler.ashx",{Tin_No:qs["SPT_No"]},function (msg) {                  
                Proceed=msg; //msg=100
                alert (Proceed); //answers 100
        });
alert (Proceed);  // answers  1,  I need here 100
});
0
 
JonNormanCommented:
The trouble is as I have explained that you cannot have 100 where you have the answer 1 as it is asynchronous and there is nothing that you can do about that.

What are you trying to achieve?

Does something like the following code do it for you?
$(document).ready(function () {          
    $("#btnSubmit").click(function (event) {
        event.preventDefault();        
        var Proceed=1;
        $.get("../Sports/SprotsHandler.ashx",{Tin_No:qs["SPT_No"]},function (msg) {                  
                Proceed=msg; //msg=100
                carryOn();
        });
});
function carryOn(){
    alert (Proceed);  // will answer 100
}

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Dinesh KumarAuthor Commented:
basically when I call to the service the Proceed Variable is updated to 100

when I come out of the $.get, I want to check Proceed value if it is 1 then no action and if has changed to 100 then do something.

but value does n't get persist so I am stuck.
0
 
Dinesh KumarAuthor Commented:
i.e

$(document).ready(function () {          
    $("#btnSubmit").click(function (event) {
        event.preventDefault();        
        var Proceed=1;
        $.get("../Sports/SprotsHandler.ashx",{Tin_No:qs["SPT_No"]},function (msg) {                  
                Proceed=msg; //msg=100                
        });
});

if(Proceed==1)
        {
         alert("Not Enough Balance");
         return false;
        }
        else
        {
         alert("balance check done. Its Ok");
        }
0
 
JonNormanCommented:
ok, so the webservice gives the current balance, and you only want to submit the form if the balance is 100 or more?
$(document).ready(function () {          
    $("#btnSubmit").click(function (event) {
        event.preventDefault();        
        var Proceed=1;
        $.get("../Sports/SprotsHandler.ashx",{Tin_No:qs["SPT_No"]},function (data) {
                balance = parseInt(data);
                if (isNaN(balance)){
                    //do something
                }else if (balance>=100){
                    alert("balance check done. Its Ok, submitting...");
                    $("#btnSubmit").parents("form").submit();
                }else{
                    alert("Not enough balance");
                }
        });
});

Open in new window

0
 
Dinesh KumarAuthor Commented:
I don't want to submit the form but I want to make another post to the Server using $.ajax depending on the current balance value, if no balance no post if balance 100 then make post.
0
 
Chris StanyonCommented:
As Jon has already explained, your GET request is an asynchronous call, which means that your code carries on running while your script is off processing the request at SportsHandler.ashx, so the alert (Proceed) is called before your script has returned the data from the request.

If you absolutely need to set the global variable before continuing, then you need to make the GET call synchronously. This will effectively 'pause' your script until the GET request has finished.

The jQuery get() function is just a shorthand for ajax(), so to set it to synchronous, you will need to use the full version. Something like this:

$("#btnSubmit").click(function () {        
	myVar = 1;
	$.ajax({
		url: "../Sports/SprotsHandler.ashx", // you might want to check the spelling here!
		data: {Tin_No:qs["SPT_No"]},
		async: false, // make the call synchronous
		success: function (msg) {                  
			myVar = msg;
		}
	});
	alert(myVar);
});

Open in new window

0
 
JonNormanCommented:
rather than make it synchronous how about:

$(document).ready(function () {          
    $("#btnSubmit").click(function (event) {
        event.preventDefault();        
        var Proceed=1;
        $.get("../Sports/SprotsHandler.ashx",{Tin_No:qs["SPT_No"]},function (data) {
                if (data+""=="100"){
                    alert("balance check done. Its Ok, posting...");
                    //$.post or $.ajax goes here
                }else{
                    alert("balance is not 100");
                }
        });
});

Open in new window

0
 
Dinesh KumarAuthor Commented:
Please bear with me

1) I will not get the benefits of ajax request If I use async: false?

2)  I am trying:
    function functionName()
{  
             $.get(../Sports/SprotsHandler.ashx",
                {Tin_No:qs["SPT_No"]},
                function (msg) {                  
                if(msg==0) {alert("Please Update Balance");}                        
                else DoPost();
                });                          
}

DoPost() is returning either true or false
but I see that it doesn't matter, the function functionName() always returns true.
can I stop it i.e if DoPost() returns false then whole function should return false and same with true return type.

3) I am trying your previous solution.
0
 
Dinesh KumarAuthor Commented:
I am using $.ajax({   in DoPost() function.
0
 
Chris StanyonCommented:
Even with async:false, it will still send your data to your script in the background. Unless you are doing a lot of server-side processing which will pause the script for several seconds, it's unlikely anyone will notice. If it seems to be a problem, then make use of a 'loader' graphic, or some 'please wait...' text.

As for your code above, you need to return the value of DoPost(), not just run it:

else return DoPost();
0
 
Dinesh KumarAuthor Commented:
Returning true or false is required becuase I am redirecting the page to the previous page if DoPost() returns true and that is done from code-behind.

Response.Redirect(WebConfigurationManager.AppSettings["baseURL"] + "filename.aspx"
0
 
Dinesh KumarAuthor Commented:
else return DoPost();

Its not working.. this is the final thing I need to resolve.
0
 
Chris StanyonCommented:
You're going to have a similar problem as before. functionName() has already finished and returned it's value by the time your GET request has finished, because it's asynchronous.

Also, when you call return, it returns it's value to the calling function, and in your case the function in question is not functionName() - it's:

 function (msg) {

The only realistic way of achieving what you want is to either block the script (synchronous) or, as per Jon's example, put the code in the success() function for the GET request.
0
 
Dinesh KumarAuthor Commented:
function functionName()
{  
             $.get(../Sports/SprotsHandler.ashx",
                {Tin_No:qs["SPT_No"]},
                function (msg) {                  
                if(msg==0) {alert("Please Update Balance");}                        
                else return DoPost();
                });                          
}
0
 
Dinesh KumarAuthor Commented:
async: false, // make the call synchronous

This worked well.

Thanks.
0
 
JonNormanCommented:
This is basically my comment ID: 38398305 above.

You will need to do the redirect with javascript:
function functionName()
{  
             $.get(../Sports/SprotsHandler.ashx",
                {Tin_No:qs["SPT_No"]},
                function (msg) {                  
                if(msg==0) {
                    alert("Please Update Balance");
                }else if (DoPost()){
                    location.href=baseURL+"filename.aspx";
                }
            });                          
} 

Open in new window

You can set the value of baseURL as a javascript variable further up in the script.

Edit: this was in response to 38398397, I would avoid making it synchronous if at all possible.
0
 
Dinesh KumarAuthor Commented:
I Salute You.
0
 
JonNormanCommented:
Yes, I can see it? have you solved that?
0
 
Dinesh KumarAuthor Commented:
Not Yet.

whenever I make call to Handler, it always works

but if  the hitting URL exists in webservice,  it sometimes skips i.e response does not come because server does n't receive the request.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 13
  • 6
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now