I have an ajax form that I would like to submit, and the response contains two divs, one containing html content and the other containing dynamic javascript in a script tag.
I’m submitting the form and receiving the response ok, but I can’t seem to get the javascript to evaluate. I’ve put an alert inside but it never fires. This is the code I am using to submit the form:
$("#categoryFormSubmit").live("click", function(event){
event.preventDefault();
var action = this.form.action + '?_eventName=' + this.name + 'Ajax';
var params = $(this.form).serialize();
var xhr = $.post(action, params, function(response) {
var responseDom = $(response);
var contentData = $('#content', responseDom).html();
var javascriptData = $('#javascript', responseDom).html();
$('#content').html(contentData);
$('#javascript').html(javascriptData);
}, 'html');
});
In the response I am trying to convert the response data to a DOM object and parse out the content and the javascript, and insert them into the existing dom. The content replacement works fine, but nothing seems to be working with the javascript. I can’t get it to evaluate. How should I be doing this? I imagine I shouldn’t be trying to insert it into the DOM like I am.
There is no need to manually parse the response and separately add the HTML and JS to your page. jQuery will detect scripts inside of markup you attempt to add to the DOM and will handle the proper addition and execution of them.