I describe my problem with following simple example.

function show(str)
{



if (window.XMLHttpRequest){
  xmlhttp=new XMLHttpRequest();
  }
else
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","data.php?q="+str,true);
xmlhttp.send();
}

here,i am getting some responsetext or result from data.php file through my request.

In my responsetext, i've used some input fields, buttons. How can i add functionality to that fields, which are fetching from external file(eg: data.php) through ajax request.

Can anyone plz help me?

Dani AI

Generated

Short answer: injected HTML won't magically get event handlers. asked about making inputs/buttons sent back from the server "work"; and requested clarification and showed a typical injection-into-#txtHint example. Three practical, future-proof choices follow: event delegation on a stable parent, attach listeners immediately when creating elements in JS, or return structured data (JSON) and build elements programmatically.

Event delegation (recommended when the container is stable and elements are dynamic):

// attach once to the container that receives the AJAX HTML
var host = document.getElementById('txtHint');
host.addEventListener('click', function(e) {
  var t = e.target;
  if (t.classList && t.classList.contains('ajax-btn')) {
    // data attributes are handy: <button class="ajax-btn" data-id="42">...
    var id = t.getAttribute('data-id');
    // perform action for that button
  }
});

Create elements and bind handlers (preferred when control and safety are needed):

// parse JSON from server, or build nodes instead of dumping innerHTML
var container = document.getElementById('txtHint');
container.textContent = ''; // clear
var input = document.createElement('input');
input.type = 'text';
input.className = 'ajax-input';
input.value = serverData.value;
input.addEventListener('input', function() {
  // live validation or AJAX save
});
container.appendChild(input);

Notes and quick troubleshooting: script tags inside a plain innerHTML insert may not execute — to run code create script nodes and append them (but avoid eval and never execute untrusted code). Avoid duplicate IDs, watch for double-binding when responses replace the same container, use data-* attributes to pass IDs, and prefer delegation for large or frequently replaced fragments. Sanitize server output to prevent XSS. These patterns cover most common cases raised in the thread and keep behavior predictable across browsers and future edits.

Recommended Answers

All 3 Replies

what functionality did you have in mind?

To add anything, you may add something to the code written either in Javascript or in PHP. So, you have to take into account type of the changes you want to make. You can't just say I want to add something and add it anywhere.
Please clarify what you intend to do so that we might help you.

Here is a simple ajax search...

<?php
require "../db_connect.inc.php";
$query = "SELECT username FROM login";
$result = mysql_query($query);
$a=array();
while($row = mysql_fetch_array($result)){
    $a[]=$row['username'];
}
//get the q parameter from URL
$q=$_GET["q"];

//lookup all hints from array if length of q>0
if (strlen($q) > 0)
  {
  $hint="";
  for($i=0; $i<count($a); $i++)
    {
    if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
      {
      if ($hint=="")
        {
        $hint=$a[$i];
        }
      else
        {
        $hint=$hint." , ".$a[$i];
        }
      }
    }
  }

// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
  {
  $response="no suggestion";
  }
else
  {
  $response=$hint;
  }

//output the response
echo $response;

?>

the ajax / html

<FORM ACTION='' NAME='SearchFriend' method="POST">
<INPUT type="text" NAME="SearchFriend" onKeyUp="showHint(this.value)"/>
<input type="submit" name="searchFriend" value="Search"/>
</FORM>
<p>Suggestions: <span id="txtHint"></span></p>
<script type="text/javascript">
function showHint(str){
if (str.length==0){ 
  document.getElementById("txtHint").innerHTML="";
  return;}
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","path/to-php-code.php?q="+str,true);
xmlhttp.send();
}
</script>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.