Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a function which is return the JSON object, i am calling this function into another function.
in second function didn't read the first json object and getting undefined error in javascript.

JavaScript
var var1={};

function function1()
{
//calling weservice retuning the json data successfully 
return data;
};

function function2()
{
var var1= function1();

alert("show username :" +var1.UseName);  //now here i am getting the undefiend error in alert box
}
Posted
Updated 7-May-14 2:36am
v2
Comments
Kornfeld Eliyahu Peter 7-May-14 8:38am    
Undefined on UserName?
Unareshraju 8-May-14 0:08am    
yes exactly getting same error on UserName as undefined
Vi(ky 7-May-14 8:40am    
make sure your json data is correct
Unareshraju 8-May-14 0:06am    
function returns the json data correctly
Kornfeld Eliyahu Peter 8-May-14 1:52am    
Can you show us a sample JSON data function1 returns?

1 solution

The problem with your code seems to be related with async operation delay. When you call function1() and expect to get the result in var1 then you will get the result only after the successful completion of your web service call in function1().
However your alert() is being called before any data is actually returned from the async call and hence you get undefined error.

So the solution is to call the alert() when your async operation has been completed successfully. For example use jQuery to call your web service and assign success and failure callbacks appropriately:

$.ajax({
    type: "POST",
    url: 'Web Service Url',
    data: JSON.stringify(Data),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (result) { alert("show username :" + result.UserName); },
    error: function (e) { }
});


I hope you are understanding this correctly. :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900