0

For example:

In the HTML page


xmlHttpObj.open("GET", "url.php", true);
xmlHttpObj.onreadystatechange = function(){
   ..
   document.getElementById('divInThisPage').innerHTML = xmlHttpObj.responseText;
   ..
}
..
..

function foo(arg){
   alert(arg);
}

In the url.php


echo "<input type='button' value='ok' onclick=\"foo('ok')\" />";

The question is, why the alert won't work?

edit: even if in the url.php I put a inline javascript code the button still doesn't work


echo "<input type='button' value='ok' onclick=\"alert('ok')\" />";

9
  • 1
    where is the alert? where is the ajax code? put more code please Commented Apr 27, 2011 at 13:46
  • Have you got a live example of the page? Commented Apr 27, 2011 at 13:48
  • 1
    Does your input element get put into the document? If so, does your browser display a JS error when you click on it? Commented Apr 27, 2011 at 13:48
  • no, I mean why the alert won't work when I click the button with the "ok" value? Commented Apr 27, 2011 at 13:48
  • @Bagong21: Do you see any JavaScript errors? Check your browser's console. Commented Apr 27, 2011 at 13:50

2 Answers 2

2

I think what you are asking is why, when you click the button that has been created by your ajax request, the alert is not alerting. This is probably because the onclick event handler foo() has not been registered. This I think is browser dependent - try in a different browser and it may work.

Anyway it's not working because when you dynamically add HTML to a page like this the onclick is not being registered in your browser. You can add event listeners to an element like this:

function doAddEventListener(elem, eventName, fn) {
  if(elem.addEventListener ) {
       elem.addEventListener(eventName, fn, false);
    } else if (elem.attachEvent) {
         elem.attachEvent('on'+eventName, fn);
    } 
}

where fn is the function you want to add, i.e foo, and eventName in this case would be "click", and elem is the element you want to add the listener to.

Sign up to request clarification or add additional context in comments.

Comments

0

Just tried the same code on FF3 and it seems to work just fine. Are you sure there is no typo somewhere? Try using firebug for clues.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.