Hi, I have a system that loads a div with content through the use of AJAX. All is well, I can get the div to load perfectly with details from my database and it works great. The problem is this: Inside the returned div, I have a couple of buttons with onclick events. The onclick events cause an error when I attempt to call a user defined function onclick="my_function();" but the onclick events do not cause an error when I call a js defined function onclick="alert('success');". Anyone know why this would be? my_function() is defined in the of my page. Although, I have also tried to define it in the content returned by AJAX, still with no luck. Any help will be greatly appreciated. Remo
if you are using prototype, jquery, etc.. (any JS framework), you need to be sure you have set the param "evalJS" to true. this last example I put works in prototype.
check here for prototype
You could try adding event handlers via JavaScript instead of onclick handlers on the actual elements.
Then you could use anonymous functions.
If you're simply updating the innerHTML
of a DIV
element with the result of an AJAX request, keep in mind that the browser parses only HTML not scripts.
Probably that's why you're recieving the JavaScript Error.
To parse also the scripts you need to consult the documentation of your library. For instance, if you're using ASP.NET you can call ScriptManager.RegisterClientScriptBlock
in order to instruct the AJAX client componenet to parse the scripts in the result.
On the other hand, if you're doing it by hand (one thing I did awhile back), you need to detect and parse the scripts yourself.
OK, here is the simple answer.. I had the button element name and id as the same as the function which it was trying to call.. stupid mistake I know.. anyhow, it is now working.. however, I do have another problem.. my ajax only fires once.. it works great the first time, but after that the function doesn't work
here is my code:
function delete_account(account_id) {
create_request();
var url = "accounts_ajax.php?action=delete_account&account_id=" + account_id;
show_div('action_window');
document.getElementById('action_window').innerHTML = '<div class="please_wait"><img src="images/working.gif"><br>Loading...</div>';
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = function(){if(xmlHttp.readyState!=4)return;if(xmlHttp.status==200){reload_div('action_window', xmlHttp.responseText);}};
xmlHttp.send(null);
}
it just causes an error second time around.