1

I have global variable fan_coil_ai_bi, and I use that variable to store some data which I get from request, but problem is that len_1 is 1 ( what is ok value in this case ) and len_2 is undefined (what is wrong). How that happen in my function bellow ? How to achieve that len_2 have same value like len_1 ? What is wrong with this code ?

function read_required_fields(fan_coil_id) {
    var parameters = {};

    parameters['command'] = 'read_required_fields';
    parameters['fan_coil_id'] = fan_coil_id;

    $.get("php_scripts/network_script.php", parameters, function(data) {
        fan_coil_ai_bi=data;
        alert('len_1='+fan_coil_ai_bi.length);
    }, "json");
    alert('len_2='+fan_coil_ai_bi.length);
}

2 Answers 2

3

Asynchronous JavaScript and XML is asynchronous.

The get method means "Make an HTTP get request and when it gets a response, do this".

It does not pause execution of the function until the HTTP response arrives.

If you want to do anything with the data, do it in the callback function (or a function you call from it).

$.get("php_scripts/network_script.php", parameters, function(data) {
    fan_coil_ai_bi=data;
    alert('len_1='+fan_coil_ai_bi.length);
    alert('len_2='+fan_coil_ai_bi.length);
}, "json");
Sign up to request clarification or add additional context in comments.

Comments

2

You might want to learn about asynchronous code. In your case, what's happening is:

  1. Request is being sent
  2. len_2 is being alerted
  3. Request finished (there is a response), len_1 is being alerted

So when len_2 is being alerted, fan_coil_ai_bi.length has not been defined yet.

There is no possibility to solve this; rather you already have a working solution: move dependencies into the callback.

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.