Changing textbox value from dropdown list using Ajax and PHP

July 12, 2009 | In: ajax, php

from PHP using Ajax and this currency code will replace the value of textbox each time the dropdown list changes.

Writing Code for changing textbox value from dropdown list using Ajax and PHP

After looking at the above demo, let’s start writing code for the changing the currency code value in the textbox form Ajax using PHP when you changes the country from the dropdown list.

HTML Code

<select name="country" onChange="getCurrencyCode('find_ccode.php?country='+this.value)">
 <option value="">Select Country</option>
        <option value="1">USA</option>
        <option value="2">UK</option>
        <option value="3">Nepal</option>
</select>
<input type="text" name="cur_code" id="cur_code" >

As you can in the above code, there are two main components one dropdown list whose name is country and contains the list country in it.The JavaScript function getCurrencyCode() is called when user change value in the list. Note down the name and id of textbox which will have the currency code fetched from Ajax.

JavaScript Code for changing textbox value without refreshing the page

function getCurrencyCode(strURL)
{
  var req = getXMLHTTP();
  if (req)
  {
        //function to be called when state is changed
        req.onreadystatechange = function()
        {
          //when state is completed i.e 4
          if (req.readyState == 4)
          {
                // only if http status is "OK"
                if (req.status == 200)
                {
                        document.getElementById('cur_code').value=req.responseText;
                }
                else
                {
                        alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                }
          }
        }
        req.open("GET", strURL, true);
        req.send(null);
  }
}

In the first line of the above code, the XMLHTTPRequest object is created using getXMLHTTP() function. After checking the appropriate value of readystate(4 means completed) and status(200 means ok) property of XMLHTTPRequest object, the value of textbox is replaced with the returned value from PHP using Ajax . The response ,which is can be accessed via req.responseText property, is written to textbox via the value property of textbox.

PHP code for changing the value of textbox using Ajax and PHP

<?php
$country=$_REQUEST['country'];
switch($country)
{
        case "1" :
                echo "USD";
                break;
        case "2" :
                echo "GBP";
                break;
        case "3" :
                echo "NPR";
                break;
}
?>

As you can see the above PHP code, it is fairly simple which just print the currency code value according to the name of country. The value which is in the echo statement is going to returned from PHP via Ajax.