0

In my Rails 3 ajax scaffolding I have a hook on ajax:success which takes any code defined in a data-loaded attribute of the calling entity (a, form etc) and executes it using jQuery.globalEval. I want to access a local variable in the hook, for example the returned data, but if I use...

alert( data )

...in the loaded param it gives me a unreferenced variable error even though that parameter is in the hook params.

Any idea how to use the data variable without changing the scaffold? It wouldn't be hard to change the scaffold but it'd be nice not to have to!

An example of what I'm talking about in it's simplest form:

function testMe( data )
{
    jQuery.globalEval( 'alert( data );' );
}

This code is telling me data is not defined, how do I pass data to the globalEval is my question.

Jay Croghan
  • 445
  • 3
  • 16

1 Answers1

2

globalEval evaluates code globally, so it ignores the scope. Since data is a variable inside testMe, and not on the global scope, it's in fact, undefined. You can do this:

var testMeData;
function testMe( data )
{
   testMeData = data
   jQuery.globalEval( 'alert( testMeData );' );
}

That will output what you want. But i don't understand why you'd want to do this.

Bruno
  • 1,368
  • 9
  • 11
  • This may create issue, if `testMeData` is defined in some outer scope, but not global. More secure way to define global variable is to refer to it using `window` object like that: `window.testMeData = data` or `window['testMeData'] = data`. After such assignment `testMeData` will more likely be global. – Tadeck Jun 24 '12 at 18:27