Changing textbox value from dropdown list using Ajax and PHP

Advertisement

Yesterday Tarquin macey asked me how can we change the value of the textbox based using Ajax and PHP based on the changing value of the dropdown list.Today, I’ve come up with a solution from him.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.

View Live Demo

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. 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

<?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.

Download Full Source Code

Enter your email address and get free tutorials, tips and tricks of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

21 Comments on “Changing textbox value from dropdown list using Ajax and PHP”

  • Tarquin wrote on 5 September, 2008, 0:16

    Ohh, thank you very much :) this is extremly useful, and soo quick!

    seems very easy to adapt into a database powered system, very nice indeed :)

  • Hum wrote on 7 September, 2008, 23:47

    Hi,
    Nice to landed in this page after googling. How can I add extra output values, lets say add country code in your example. Furthermore, show the results in plain area, not in box (form).
    Thanks in advance.
    Hum

  • Roshan wrote on 8 September, 2008, 4:51

    @Hum- you can change the value of div with id “divid” like below

    document.getElementById(‘divid’).innerHTML=
    req.responseText;

    and regarding adding two values, you have to make a string with these two values separated by a symbol for example string like “1#USA” can be returned and then separate the two part from JavaScript

  • Tarquin wrote on 8 September, 2008, 5:25

    I adapted this a little bit differently. If your using a database for example and your having the data post to this form you can instead use a query like these:

    if($_POST['data'] == “var1″){
    echo “output content”;
    }elseif… etc

    or you can use a MySQL statement to grab data and simply echo the results you want.

    The brialliant and simple part of this code is you can do ANYTHING you want, cause it will display anything that you output in the echo statement.

    Again thanks, im using this for several projects now, very awsome and easy to use script.

  • Tarquin wrote on 8 September, 2008, 5:28

    Sorry to double post but ive decided to post the code im using incase you wish to use a database query. As i said very easy;

    $obtain_ID=$_REQUEST['ID'];

    $movie_list = @mysql_query(“SELECT * FROM movies WHERE `id` = ‘”.$obtain_ID.”‘”);
    while($movielisting=mysql_fetch_array($movie_list))
    {
    $movie_size = $movielisting['size'];

    echo “”.$movie_size.””;

    }

    As you can see all i need to be displayed is the movie size, therefore thats all being displayed.

  • Roshan wrote on 8 September, 2008, 7:23

    @Tarquin-thanks for sharing the code but always sanitize the input..change the following code to

    $obtain_ID=$_REQUEST['ID'];
    to
    $obtain_ID=intval($_REQUEST['ID']);

    why checkout this post..

    http://roshanbh.com.np/2007/12/sql-injection-attack-examples-and-preventions-in-php.html

  • Tarquin wrote on 8 September, 2008, 7:32

    Yeah its just an example, the database this particular code is on, is on my local server and is for testing purposes only. but thx for that, will keep that particular thing in mind.

  • selvi wrote on 2 December, 2008, 5:41

    hi, i want to know that mysql data should be displayed on textbox after selected the combobox selected value…..Pls help me genious….

  • Pacleb Aphryl wrote on 8 February, 2009, 12:14

    whats tha appropriate field for cooment and how to make the cooment not to be expand , what i mean is the fix field for comment . . email me please this is my e-mail aphryl_10@@yahoo.com

  • vinoth wrote on 5 March, 2009, 19:47

    hi, in java scrip xmlHttp.readyState value 0,1,2,3,4. in my program i got only 1 is my value means what is the err and how i can change plz tell me.

  • adinda wrote on 24 March, 2009, 6:33

    how can we change the value of the multiple textbox based using Ajax and PHP based on the changing value of the multiple dropdown list ???

  • Caksono wrote on 25 March, 2009, 4:20

    Thanks .. really really useful for me :)

  • ones wrote on 20 May, 2009, 8:16

    how to with mysql ???

  • Adan-Sos wrote on 23 June, 2009, 20:47

    thanks!!!!
    it’s excelente.
    very good work

  • Jones wrote on 17 October, 2009, 3:28

    It’s great and it solved my problem struggling for 3 hours in this morning.

  • Marco wrote on 22 January, 2010, 7:37

    Hello,

    I use it for a while now, but it comes to my attention that
    its working with firefox, but not with IE8 even not in compatability mode on
    Is there a fix?

  • APC wrote on 17 February, 2010, 9:16

    How shoul I modify this example to make it change the values in 3 ore more textareas (not only one) ?

    thanks.

  • Ashafakk4u@gmail.co wrote on 17 May, 2010, 12:59

    Hello Roshan Thanks Dear for nice script. I use it and it’s working perfectly .
    However i have one query in this script we can fill one text box value after dropdown selection suppose we have to fill more than one text field ..then how can we do that .
    I tried it but it is giving me a combined strings of all value .
    Plz reply

  • Ashafak wrote on 18 May, 2010, 15:05

    Dear Roshan Thanks for nice script ;
    I just wana know that how we can populate more than one textfield with the same dropdown selection

  • Mwathi wrote on 21 February, 2012, 16:27

    Thanks for this, really appreciate…

Trackbacks

  1. pligg.com

Write a Comment

 


Copyright © 2014 Roshan Bhattarai's Blog. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.