B. Clay Shannon B. Clay Shannon - 2 years ago 78
Javascript Question

How can I access the data passed back to an AJAX call?

Now that I'm successfully calling my controller method from Ajax now (see Update 2 here for the specifics), my next step is to access the data passed back from the Controller method in the Ajax success function.

In this case, I'm passing back a jsonified generic list of string (0..N string vals).

How can I access them from the success function embedded in the jquery ajax call:

var model = JSON.stringify({ unit: unitval, report: rptval });
type: 'GET',
url: '@Url.Action("GetUnitReportPairEmailAddresses", "UnitReportPair")',
data: { unit: unitval, report: rptval }, // data: model,
contentType: 'application/json', //<= this is paired with stringify above; if comment out one, comment out both
cache: false,
success: function (result) {
error: function () {

I assume it's by querying the "result" object, but how? I tried this:

success: function (result) {

...but only saw an "undefined" alert after the "success" alert. A simple "alert(result)" showed nothing, as did "alert(result.data)"

The Controller (in the test case scenario) is passing back a single string, an email address. In "real life" usage, it will be 0..N email addresses, but for now it is successfully passing back one string, yet it is either not in "result" for some reason, or I am not getting it out of there as it should be extracted.


Okay, now we're getting somewhere; I put a breakpoint in the "success" function, hovered over its "returneddata" param, and saw:

enter image description here

Yet when I then added this code to the "success" callback:

success: function (returneddata) {

(replacing "returneddata" with "UnitReportPairEmailVals" which is the value of returneddata), on stepping into the second alert I got "Uncaught reference error: 'UnitReportPairEmailVals' is not defined"


Once I pieced together several different answers, I wrote up a tip on how to do this here.

Answer Source

Uncaught reference error: 'UnitReportPairEmailVals' is not defined

By itself it isn't defined anywhere. It's not a variable, it's a property on a variable. Specifically, on returneddata. Variables here essentially work the same way as they do in C#:

function (returneddata) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download