webberpuma
webberpuma

Reputation: 733

jquery callback function

instead of writing code in the standard way:

$.get('test.xml',function(){
    //manipulate the code here
})

I wanted to write the code this way to make things easier:

$.get('test.xml',callback(data));

function callback(data){
    //manipulate with the data below...
}

but error show "data is undefined", how can i fix this?

Upvotes: 1

Views: 269

Answers (3)

helle
helle

Reputation: 11660

try:

$.get('test.xml',function(){callback(data)});

JS can't handle variables for callback-functions your way

Upvotes: 0

jigfox
jigfox

Reputation: 18177

Just leave the data out. it is a parameter automatically given to the callback function:

$.get('test.xml',callback);

function callback(data){
    //manipulate with the data below...
}

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816790

Just write

$.get('test.xml',callback);

When you write

$.get('test.xml',callback(data));

then callback gets executed immediately (you call the function).


Or if data is not supposed to be the data returned from the Ajax call, but some parameter you want to pass to the function, you have two possibilities:

  1. Make callback return a function.
  2. Wrap the callback call in an anonymous function:

    $.get('test.xml',function(){callback(data);});
    

Upvotes: 6

Related Questions