0

I have a JQuery-Code like this:

    $.post("count_images.php",{}, function(data)
    {
        if (data != '')
        {
            alert(data);
        }
        else
        {
            //Error
        }
    });

It simply sends a request to count_images.php and returns a number like 23 for example. This works perfectly fine, but when i change it into this:

    var number_images;

    $.post("count_images.php",{}, function(data)
    {
        if (data != '')
        {
            number_images = data;
        }
        else
        {
            //Error
        }
    });

    alert(number_images);

It does not work correctly. The alert-function always outputs an undefined. I simply want to save the result saved in data in a variable called number_images so i can keep on working with that. Thank you very much in advance.

user3877230
  • 439
  • 1
  • 5
  • 18

3 Answers3

1

Keep in mind that $.post() is an asynchronous method and all that code is in a callback function, so when

alert(number_images);

is called, your callback function likely has not run yet because $.post() is still waiting for a response.

You need to put anything that uses number_images in the callback. It might be helpful to define another function like so:

var number_images;

var do_stuff_with_number_images = function() {
  alert(number_images);
  // any other code referencing number_images goes here
};

$.post("count_images.php",{}, function(data)
{
    if (data != '')
    {
        number_images = data;
    }
    else
    {
        //Error
    }

    do_stuff_with_number_images();
});

alert(number_images);
brianjob
  • 360
  • 1
  • 9
1

The $.post() method is asynchronous, so when the second code snippet runs, the alert will be fired off before the AJAX POST returns with date, hence why number_images is undefined (as it hasn't been populated yet).

You can have the POST be executed synchronously by using $.ajax() and passing async: false and method: 'POST' flags. But this is not usually a good idea, as it defeats the entire purpose of AJAX (the A stands for asynchronous, after all).

Alternatively, either use the callback function (same as the first snippet) or attack other callbacks using the jQuery Promise API. For example

    $.post("count_images.php")
    .done(function(data)
    {
        if (data != '')
        {
            alert(data);
        }
        else
        {
            //Error
        }
    });
VLAZ
  • 26,331
  • 9
  • 49
  • 67
0
var number_images,
      data ='';

$.post("count_images.php",{}, function(data)
{
    if (data != '')
    {
        number_images = data;
    }
    else
    {
        //Error
    }
});

alert(number_images);
user3574939
  • 819
  • 3
  • 17
  • 34