ELP24
ELP24

Reputation: 61

DWR response to javascript variable

I have asked for this severals weeks ago, but nobody couldn't help me.

This is very important thing to me, and it's still without any working solution.

In ViewDwr I have simple method which are check some data by given Id and return state as boolean. In javascript (jsp file) I have something like that:

      ViewDwr.checkData(id, function(data) 
        {
            document.getElementById("status").innerHTML=data;
        });

and it's working good. Problem is that I need to put data to variable. Something like:

      var currentDataStatus;

      ViewDwr.checkData(id, function(data) 
            {
                currentDataStatus=data;
            });

      alert(currentDataStatus);

but in this case it isn't working. I trying any combination with that but i could't find any working solution to put resposne value to variable and using it in other functions.

Anybody could help me?

Thanks

Upvotes: 0

Views: 1173

Answers (1)

lexicore
lexicore

Reputation: 43699

This won't work because it's asynchronous processing. Your function will be called later on, when the results come back from the server. At this point, your context is long gone.

When programming asynchronously (like wih DWR) you have to abstract from the specific order of processing. Think in callbacks (OK, I won' start about promises etc. here). Like, "here's what should happen when the results come back".

In your second sample this will be just something like:

ViewDwr.checkData(id, function(data) 
{
  alert(data);
});

Why do you need a variable anyway? If this is meant to be a global variable this is not a good idea anyway. Otherwise consider making it a property in some object.

var myObject = {};
ViewDwr.checkData(id, function(data) 
{
  myObject.currentDataStatus = data;
  alert(myObject.currentDataStatus);
});

Or even better, make your object more intelligent:

var myObject = ...;
ViewDwr.checkData(id, function(data) 
{
  myObject.onDataChecked(data);
});

Important is that you have to do the processing of the results (like alert(currentDataStatus)) in the success callback.

Upvotes: 2

Related Questions