Possible Duplicate:
Use variable outside the success function from an ajax/jquery call
I have this code and i don’t understand why the accessing of the html elements is only working inside the ajax success function. the form is pulled in from ajax either way but i can only access it when i put all the selects for elements of it inside the ajax function.
The console.log('submit clicked'); gets not triggered this way, but inside the “ajax success” it does, i thaught everything pulled in with ajax is part of the DOM?
jQuery(document).ready(function($) {
console.log('ready');
$.ajax({
type: 'GET',
url: 'admin-ajax.php',
data: { action: 'get_arve_form' },
success: function(response){
// var table = $(response).find('table');
$(response).appendTo('body').hide();
console.log('response');
[ if i move the code below this ajax function in here its workign fine why not outside of it?]
}
});
// handles the click event of the submit button
$('#mygallery-submit').click(function(){
console.log('submit clicked');
[...]
});
Ajax is asynchronous so your elements don’t exist until the ajax call finishes.
That being said, there are two ways to fix it:
1) Move your code into the success handler
2) Use event delegation to bind your event handler to all current and future elements.
An example of #2:
Check out jQFundamentals to learn more about event delegation.