views:

112

answers:

2

I think I have not got the syntax correct for writing a javascript function and calling it to assign its return value to a variable.

My function is:

getObjName(objId){
  var objName ="";
$.ajax( {
    type : "GET",
    url : "Object",
    dataType: 'json',
    data : "objId="+objId,
    success : function(data) {
    objName = data;
    }
});
  return objName;
}

I am trying to call it and assign it to a variable with:

var objName = getObjName(objId);

However Eclipse is telling me that "the function getObjName(any) is undefined"

+3  A: 

There are two things wrong here. First, you need to add function before getObjName

Secondly, you can't return a variable asynchronously. If you absolutely must do this, you can set the ajax to be synchronous, however this will block the running thread the entire time the ajax call is communicating to the server.

function getObjName(objId){
  var objName ="";
    $.ajax( {
        async: false,
        type : "GET",
        url : "Object",
        dataType: 'json',
        data : "objId="+objId,
        success : function(data) {
            objName = data;
        }
    });
  return objName;
}
Matt
@OP: **Strongly** recommend avoiding synchronous requests, because as Matt says, they completely lock up the browser UI. Instead, pass a callback reference into the function and have the ajax success handler call the callback. `getObjName` then becomes (effectively) `requestObjName` and the response comes back some time later. It's a shift in your thinking, but once you've got the hang of it, it's really powerful.
T.J. Crowder
+1  A: 

Have to declare functions with the function keyword:

function getObjName(objId){
   //...
}

But anyway, your code would not work. The Ajax call is done asynchronously that means, the function getObjName will return, before the Ajax call is finished and objName will be empty.

You could define your function to accept a callback, e.g. :

getObjName(objId, cb){
    $.ajax( {
        type : "GET",
        url : "Object",
        dataType: 'json',
        data : "objId="+objId,
        success : cb    // <-- call the callback on success
    });
}

and then later:

var objName;
getObjName(objId, function(data) {
    objName = data;    // <-- objName refers to the the variable defined 
                       // outside this function and gets set 
                       // after the Ajax call is finished
});
Felix Kling