Disclaimer: I am very new to this stuff so please bare this in mind.
Hello,
Im setting up a site using AJAX to load page content without having to leave the page. I have a few pages that use javascript to load list information.
Here is link setup looks:
#home
#list.php?list=$list_id
I have a variable called $list_id and use that with some javascript to load the list. The problem I am facing is that if I load one list (lets say list with ID 1) then go back and load another list (lets say list with ID 2) the javascript has not reloaded to account for the new list ID.
Is there anyway I can reload the javascript code to account for the new variable without having to refresh the page?
Thanks!
I dont understand what problem you are facing exactly.
but if you want to reload script without refreshing the page, you can do in this way:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "somefile.js";
document.getElementsByTagName("head")[0].appendChild(script);
or use jQuery.loadScript function
When inserting HTML into the DOM scripts are executed. Therefore, when you load some HTML via AJAX you can execute contained scripts.
Could you not store the $list_id in a hidden input field and then update it after an ajax call?
e.g.
<input type="hidden" id="list-id" value="<?php echo $list_id; ?>" />
<script>
//ajax request
var $list_id = $('#list-id');
$.ajax({
url:'http://www.example.com/page.php',
data:'list_id=' + $list_id.val(),
success:function(data){
//do something
$list_id.val() = $list_id.val() + 1;
}
});
just cobbled this together quickly to give you an idea, so there might be some js errors
You can use jQuery's getScript()
function for getting (and executing) scripts dynamically. For example:
$.getScript("/js/myscript.js");
As you posted no Code at all I'm taking a wild guess here.
You don't have to reload your Javascript Code in this case but you could propably store your data in an object.
Please show us some JS Code to answer your question properly.
Typically, it would be best to design a protocol here. You should have one function to parse any 'lists' being loaded, one function to parse the URL hash, and one function to load new lists. You can get the URL hash with location.hash
.
Here's a simple example, that expects the list to be a certain format. So it would be protocol based, as in your Javascript should only need to be loaded once, and it should expect a certain specific format that it would be capable of parsing without any added dependencies. It would be okay to actually require dependencies, but how/when/where should all be worked into the protocol.
<a class="listLoader" href="#list.php?list=1">List 1</a>
<a class="listLoader" href="#list.php?list=2">List 2</a>
<a class="listLoader" href="#list.php?list=3">List 3</a>
.
$('.listLoader').onclick(function() {
$.ajax({
'success': function () {
//Do what you gotta do with your lists
},
'url': location.hash.substring(1)
});
});