EDIT
To make it easier to read I’ve rewritten my explanation here.
In short, a function in remote .js file requires a global variable. A previous function in remote .js file brings that var into the page with the jQuery .load(), but the function that requires the variable is not finding it after the .load() has brought it into the page. Below functions are in chronological order.
The remote .js file is loaded into the main page before the .load() page is.
Below is the code that I have:
Function Loads Remote Page Into Main Page (in remote .js file)
$(".activity_choice").live('click',function(e) {
var selection = $(this).attr('id');
var address = my_url + "pg/course/activity_form?style=" + selection + "&activity=" + activity;
$("#stage_choice_holder").load(address,function(){
});
});
The Global Var Coming In With Loaded Page
var controls_setup = $.parseJSON('<?php echo json_encode($setup);?>');
The Final Function That Should Save Things Using This Variable (in remote .js file)
$("#save_controls").live('click',function(e) {
datastr = "&activity=" + activity;
$.each(controls_setup, function (i,elem) {
datastr += "&"+elem+"=" + $("#"+elem).attr('value');
});
$.ajax({
type: "POST",
url: my_url + "action/course/saveactivitycontrols",
data: datastr,
dataType: "json",
success: function(msg){
}
});
});
The global variable controls_setup is not being recognized (I think), because when the $(".activity_choice").live('click',function(e) { is clicked the main page is already rendered with the remote .js file in it. This function brings the global variable in, but I’m guessing the DOM isn’t picking it up. So the final function that requires this var can’t find it.
Hope this is clearer.
Any help much appreciated. I am a somewhat novice with jQuery.
It’s very hard to tell exactly what’s going on in that code, because there’s lots of code quoted which is unrelated to the problem, and (conversely) it’s quoted in somewhat disconnected bits.(You’ve fixed that, nice one.)But if I understand you correctly, this call from your first code block:
…is loading HTML with embedded
scriptelements from a PHP page, and in ascriptelement on that page you have:First off, you don’t want that
parseJSONcall, simply this:json_encodewill return valid JSON, which conveniently (and intentionally) is a subset of JavaScript object literal notation, so the end result there is thatcontrols_setupwill receive a reference to an object. This may actually be the problem, because throwing single quotes around the output ofjson_encodemay well result in a syntax error (if there are any single quotes in the material output byjson_encode, or line breaks).Then in code later, you’re trying to access
controls_setupand not seeing it.Although not best practice, that should work because of the way jQuery ensures things get loaded. Here’s a very simple example of it (live copy):
…which loads
So it could be as simple as removing the
parseJSONcall per the above.