al404IT al404IT - 4 months ago 8
jQuery Question

call javascript page function inside ajaxed html

I have a page where i use jQuery to load some content into a div element

<div id="contents-box-in"></div>


jQuery code in page

$(document).ready(function() {

$("#contents-box-in").load("new-01.php", function() {
$('#contents-box-in').fadeIn(120);
});

var updateBoxData = function(data) {

$('#contents-box-in').fadeOut(100, function() {
$('#contents-box-in').html(data).fadeIn(130);
});

}

});


the content that i load is a form that needs to load a new page sending collected data from form

$('#form-buttons-next').click(function(e) {

var formData = new FormData($(this)[0]);

var formS = $.ajax({
url : 'new-02.php',
type : 'POST',
data : formData,
async : false,
cache : false,
processData : false,
contentType : false
});

formS.done(function(data) {

if (data != null) {

updateBoxData(data);

}

});

formS.fail(function(jqXHR, textStatus) {

alert("error");

});

});


since i do this in different step i would like to use a shared function contained in page that is loading the ajax content but i get updateBoxData is undefined

I guess that ajaxed content can't see parent container function

The easy way would be to load a different .js file containing shared function, i was wondering if is possible to access the updateBoxData from ajaxed contents

Answer

The function updateBoxData is defined inside a callback function you passed to .ready and hence its scope is limited to that function. Let us call this callback function Fx.

The click handler (the function passed to .click in the second part), which we call it Fy is defined outside of Fx and as a result does not have access to the variables defined in Fx (remember updateBoxData is a variable inside Fx).

That is why your code does not work. To get it working simply take updateBoxData out of the callback in .ready function:

$(document).ready(function() {
    $("#contents-box-in").load("new-01.php", function() {               
        $('#contents-box-in').fadeIn(120);              
    });
});
function updateBoxData(data) {
    $('#contents-box-in').fadeOut(100, function() {
        $('#contents-box-in').html(data).fadeIn(130);
    });
}
...

The rest is the same.