How to return the value from Callback function

ramesh_r
Mega Sage

Hi All,

I have client script with GlideAjex and it's returning the value properly

I want to get out the callback function return value but it's not working

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }

    var ga = new GlideAjax('AjaxScriptInclude');
    ga.addParam('sysparm_name', 'greetingFunction');
    ga.addParam('sysparm_my_name', "Tim");
    ga.getXML(myCallBack); 
	
	var val;
	
    function myCallBack(response) {
        var greeting = response.responseXML.documentElement.getAttribute('answer');
        val= greeting; // This is returns correct value
    }
	
  alert(val); // i want to use the value here (Out side the function)
	
	
}
9 REPLIES 9

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Ramesh,

that's because the variable val is outside the function scope and won't be available inside that function

so you cannot use that;

alert that inside the myCallBack() method and it will work

whatever validation etc you want to do do that inside that callback method

Are you getting undefined in the alert(val)?

Mark Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Hi Ankur,

Yes, i am getting undefined in the alert(val). 

Yes we can use the validation in side the callback function by i am trying to get value out side the function.

Thanks

Ramesh  

Dubz
Mega Sage

You have to remember you're calling the callback function in the ga.getXML line. At that point there is no variable called 'val'. Try this, should work, fingers crossed!

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }

var val;
    var ga = new GlideAjax('AjaxScriptInclude');
    ga.addParam('sysparm_name', 'greetingFunction');
    ga.addParam('sysparm_my_name', "Tim");
    ga.getXML(myCallBack); 
	
alert(val); // i want to use the value here (Out side the function)
	
    function myCallBack(response) {
        var greeting = response.responseXML.documentElement.getAttribute('answer');
        val = greeting; // This is returns correct value
    }
	
  
	
	
}

No reason why you can't just do the alert in the callback function though to be honest.

Hi Davi,

Thanks for the response I tried the code but it's not working.

I am getting undefined in the alert(Val). 

 

Thanks