1

How can I update this javascript array using JS Remoting?

var data = [];

Visualforce.remoting.Manager.invokeAction('{$RemoteAction.myController.myMethod}',
    function(result, event) {
        if (event.status) {
            for (var i=0; i<result.length; i++) {
                 data.push({myKey: result[i].fieldName});
            }
            console.log(data);
        } else {
            alret(event.message)
        }
    },
    {escape: true}
);

console.log(Array.isArray(data));
console.log(data);
console.log(data.length);
console.log(data[1].myKey);

Apex controller is supposed to return 4 records, so as expected, from inside invokeAction, javascript console print out this.

enter image description here

But after it passes through invokeAction, I got these from the last four lines of codes above.

enter image description here

Any idea? Thanks.

  • Sang Jung, am sure my answer helps. Please mark it as accepted so that we can close the question. – Praveen Jul 17 '16 at 18:58
4

RemoteAction callback is asynchronous, invoked by the client(browser) when the server returns the response.

So the javascript as soon as executes remote action call, it proceeds to the next part of the code to be executed, without waiting for the server to send an response.

Below is what is happening :

var data = []; // run and moves to next line

    // executes moves to next without waiting for response from the server
Visualforce.remoting.Manager.invokeAction('{$RemoteAction.myController.myMethod}',
        function(result, event) {
            if (event.status) {
                for (var i=0; i<result.length; i++) {
                     data.push({myKey: result[i].fieldName});
                }
                console.log(data);
                console.log(data[1].myKey); // this will work
            } else {
                alret(event.message)
            }
        },
        {escape: true}
    );

// runs and moves to next
console.log(Array.isArray(data)); 

// runs and moves to next, console will display data is empty(initially),
// once the response updates it, data has value in it.
console.log(data); 

// runs and at this time data is empty(no response from server yet)
console.log(data.length); 

// runs and your trying to acesss non-existent element's property data[1] => undefined
console.log(data[1].myKey); //so error!!!!!
  • Thanks. I totally missed that remote action is always async. – Sang-Jung Jul 18 '16 at 1:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.