I have a function, ajaxinclude() which includes the content of a page.
It works perfectly when written like:
<div>
<script type="text/javascript">
ajaxinclude("info/content/About.php")
</script>
</div>
Now, I want a button on-click this should come.
Thus,
<button onclick="document.getElementById('aaa').innerHTML = '<script type='text/javascript'>ajaxinclude(\'info/content/About.php\');</script>">Hello</button>
But this doesn’t work.
Another method would be
<button onclick="document.getElementById('aaa').innerHTML = '<script type='text/javascript'>' + ajaxinclude('info/content/About.php') + '</script>">Hello</button>
But this doesn’t work either.
This is my ajaxinclude() function:
var rootdomain = "http://" + window.location.hostname;
function ajaxinclude(url) {
var page_request = false
if (window.XMLHttpRequest)
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.open('GET', url, false)
page_request.send(null)
writecontent(page_request)
}
function writecontent(page_request){
if (window.location.href.indexOf("http")==-1 || page_request.status==200)
document.write(page_request.responseText)
}
How, how do I include the text on a button click?
PS: I don’t want jQuery.
Try
However I must warn that inline JavaScript is bad practice, especially like this! You can rewrite your
writecontentfunction to accept two parameters: the page request and the ID of the target to write to.Your new
writecontentfunction would be:You’ll need to pass the ID of the write target there, and since you’re calling
writecontentfromajaxinclude, you’ll need the parameter there too:And in the button:
Optionally continuing…
Even better would be binding the
clickaction to the button instead of usingonclick. This would be easier with jQuery, but since you explicitly stated you do not want to use jQuery, you can also do it usingaddEventListener()in your JavaScript:And that would change the button to:
Read more about event listeners at the Mozilla Developer Network.