Changing textbox value from dropdown list using Ajax and PHP

December 14, 2008 | In: php

In this post, you’ll see how to get the currency code of a country 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.


<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>
<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)
                        alert("There was a problem while using XMLHTTP:\n" + req.statusText);
        }"GET", strURL, true);

In the first line of the above code, the XMLHTTPRequest object is created using getXMLHTTP() function. To look at the the structure of this function, take a look at this old post change the value of dropdown list using Ajax and PHP . 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

        case "1" :
                echo "USD";
        case "2" :
                echo "GBP";
        case "3" :
                echo "NPR";

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.