0

i have one AJAX function getting results from php file as bellow

$.ajax({
             type: "POST",
             url: "GeteT.php",
             cache:false,
             data:"id="+ encodeURIComponent(1),
             dataType:'json',
             success: function(json)
             {
         g_foo = json.foo;
         }
        });

now i want to use the value of g_foo but i can't i try using console.log but i am facing strange problem. like

if i use function like that

       $.ajax({
         type: "POST",
         url: "GeteT.php",
         cache:false,
         data:"id="+ encodeURIComponent(1),
         dataType:'json',
         success: function(json)
         {
     g_foo = json.foo;
        console.log(g_foo);
     }
    });

now i can see the value return from php file

if now i use function like that

         $.ajax({
         type: "POST",
         url: "GeteT.php",
         cache:false,
         data:"id="+ encodeURIComponent(1),
         dataType:'json',
         success: function(json)
         {
     g_foo = json.foo;

     }
    });
        console.log(g_foo);

now i got error undefined g_foo;

thanks

2 Answers 2

3

As ajax is asynchronous, there's no way of making sure that g_foo is available as soon as you call the $.ajax() request, hence it's not available outside that callback.

You could however, specify async:false to that .ajax() call, but it will most likely block the browser, attempting to wait for the request, something I don't think you want to happen.

Sign up to request clarification or add additional context in comments.

Comments

2

To use it outside you have two ways:

1)make the call syncronous like this (this is not a best practice as the browser has to wait for the call to continue the flow):

   $.ajax({
     type: "POST",
     url: "GeteT.php",
     cache:false,
     data:"id="+ encodeURIComponent(1),
     dataType:'json',
     async: false,
     success: function(json)
     {
 g_foo = json.foo;


 }
});
    console.log(g_foo);

2) call a function on success and continue the flow from there using whatever data has been returned from the function (this is the best practice)

       $.ajax({
         type: "POST",
         url: "GeteT.php",
         cache:false,
         data:"id="+ encodeURIComponent(1),
         dataType:'json'
         success: function(json)
         {
     g_foo = json.foo;
        yourfunction(g_foo);
     }
    });

function yourfunction(g_foo){
    //here g_foo is set
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.