Reputation: 5064
[REVISED]
Hi, thanks for the feedback guys. I revised by question btw. To make things clearer here's my html page (sample only)
<html>
<head>
<body>
<form>
<div class="loadAjax"></div>
<div class="toggle">[form inputs here]</toggle>
<a href="#" class="btn">Submit</a>
</form>
<script>[several js scripts here]</script>
</body>
</html>
And here's my main js file:
$(function() {
[some lines here]
$('.toggle').toggle();
$('.btn').on('click', function(e) {
e.preventDefault();
$.ajax({
url: 'http://example.com/ajaxpage',
type: 'POST',
data: $('form').serialize(),
beforeSend: function() {
...
},
success: function(data) {
$.getScript('js/main.js');
$('.content').html(data);
}
});
});
});
The page that will be loaded in div.loadAjax.
<div class="toggle">ajax page load</div>
Taking this as an example, the toggle on the main page seems to work. But the div.toggle
on the div.loadAjax
doesn't. I need to set the $.getScipt()
in order to reload the main.js file again. Shouldn't the div.loadAjax
inherit the main.js since it is loaded already in the first place? Why do I still need to reload it again using the $.getScript()
?
NOTE: I'm using ajax to do a form post on a PHP page.
Thanks again!
Upvotes: 0
Views: 3436
Reputation: 7332
The code for toggle was already executed on your first page load. That will not execute again automatically without a page reload, otherwise you have to trigger it again or should load your script again as you did now.
Try attaching it to click event and trigger it dynamically using .trigger
$(function() {
[some lines here]
$(".toggle").on("click", function(){
$('.toggle').toggle();
});
$('.toggle').trigger("click");
$('.btn').on('click', function(e) {
e.preventDefault();
$.ajax({
url: 'http://example.com/ajaxpage',
type: 'POST',
data: $('form').serialize(),
beforeSend: function() {
...
},
success: function(data) {
$('.content').html(data);
$('.toggle').trigger("click");
}
});
});
});
Upvotes: 1
Reputation: 4057
Why don't you use the $.load()
method: http://api.jquery.com/load/
This will let you perform an Ajax call, inject the results back onto the DOM of your page and also supports executing scripts loaded via the request.
Upvotes: 0