Saturday, April 30, 2011

AJAX Function to populate a field in a form?

Hey, I was looking through W3's tutorial on AJAX and I decided to make a javascript function that would populate a form field based on the response of a page. I took all their functions and tried to create the below one.

Can anyone see why it wont work?

function populateForm(myForm,formField,PageFrom,infoToSend)
{
var xmlHttp;
try
  {
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      //alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
      document.myForm.formField.value=xmlHttp.responseText;
      }
    }
 var url=PageFrom;
url=url+"?q="+infoToSend;

  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
  }

This is how I am calling it:

<form id="qwert" name="qwert">

<input id="qwer" name="qwer" type="text" onkeyup="populateForm('qwert','qwerty','echo.php',this.value);">
<input id="qwerty" name="qwerty" type="text">

</form>
From stackoverflow
  • This is wrong:

    document.myForm.formField.value=xmlHttp.responseText;
    

    You might want to try:

    document.getElementById(formField).value = xmlHttp.responseText;
    

    With that you won't even need to pass the form name, just the id of the field you want to update.

    Sam152 : Thanks man, it works perfectly now.
  • Can you post your 'echo.php' page to show how you handle the return?

  • This might be a late reply, but would definitely be helpful to folks having such a question later.


    The best option is to use prototype.js available at http://www.prototypejs.org/api/ajax/updater. It would be as simple as

    new Ajax.Updater('qwerty',url,{asynchronous:true});
    

    This will take care of what you want to do. For any error-handling requirement, please go through the entire API documentation which is simple.


    Hope this helps!

    Sam152 : There are definitely pros and cons to using such frameworks and it all depends on what you are doing. I have looked a jQuery ect but I will have a look at this one too. Good answer, +1.

0 comments:

Post a Comment