0

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"

2 Answers 2

4

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

@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.
1

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
});

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.