SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2010
    Posts
    61
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Thumbs up Help me create AJAX - Dropdown ???

    I create dropdow list like:

    1)db_ajax.sql
    # phpMyAdmin MySQL-Dump
    # version 2.3.2
    # http://www.phpmyadmin.net/ (download page)
    #
    # Host: localhost
    # Generation Time: Aug 14, 2006 at 09:14 PM
    # Server version: 4.00.00
    # PHP Version: 4.2.3
    # Database : `db_ajax`
    # --------------------------------------------------------

    #
    # Table structure for table `city`
    #

    CREATE TABLE city (
    id tinyint(4) NOT NULL auto_increment,
    city varchar(50) default NULL,
    countryid tinyint(4) default NULL,
    PRIMARY KEY (id)
    ) TYPE=MyISAM;

    #
    # Dumping data for table `city`
    #

    INSERT INTO city VALUES (1, 'Los Angales', 1);
    INSERT INTO city VALUES (2, 'New York', 1);
    INSERT INTO city VALUES (3, 'Toranto', 2);
    INSERT INTO city VALUES (4, 'Vancovour', 2);

    # --------------------------------------------------------

    #
    # Table structure for table `country`
    #

    CREATE TABLE country (
    id tinyint(4) NOT NULL auto_increment,
    country varchar(20) NOT NULL default '',
    PRIMARY KEY (id)
    ) TYPE=MyISAM;

    #
    # Dumping data for table `country`
    #

    INSERT INTO country VALUES (1, 'USA');
    INSERT INTO country VALUES (2, 'Canada');

    2) findcity.php
    <?
    #### Roshan's Ajax dropdown code with php
    #### Copyright reserved to Roshan Bhattarai - nepaliboy007@yahoo.com
    #### if you have any problem contact me at http://roshanbh.com.np
    #### fell free to visit my blog http://php-ajax-guru.blogspot.com
    ?>

    <? $country=$_REQUEST['country'];
    $link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
    if (!$link) {
    die('Could not connect: ' . mysql_error());
    }
    mysql_select_db('db_ajax');
    $query="select city from city where countryid=$country";
    $result=mysql_query($query);

    ?>
    <select name="city">
    <option>Select City</option>
    <? while($row=mysql_fetch_array($result)) { ?>
    <option value><?=$row['city']?></option>
    <? } ?>
    </select>

    3) index.php
    <html>
    <head>
    <title>Roshan's Ajax dropdown code</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <?
    #### Roshan's Ajax dropdown code with php
    #### Copyright reserved to Roshan Bhattarai - nepaliboy007@yahoo.com
    #### if you have any problem contact me at http://roshanbh.com.np
    #### fell free to visit my blog http://php-ajax-guru.blogspot.com
    ?>
    <script>
    function getXMLHTTP() { //fuction to return the xml http object
    var xmlhttp=false;
    try{
    xmlhttp=new XMLHttpRequest();
    }
    catch(e) {
    try{
    xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e){
    try{
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e1){
    xmlhttp=false;
    }
    }
    }

    return xmlhttp;
    }



    function getCity(strURL) {

    var req = getXMLHTTP();

    if (req) {

    req.onreadystatechange = function() {
    if (req.readyState == 4) {
    // only if "OK"
    if (req.status == 200) {
    document.getElementById('citydiv').innerHTML=req.responseText;
    } else {
    alert("There was a problem while using XMLHTTP:\n" + req.statusText);
    }
    }
    }
    req.open("GET", strURL, true);
    req.send(null);
    }

    }
    </script>




    </head>

    <body>

    <form method="post" action="" name="form1">
    <table width="60%" border="0" cellspacing="0" cellpadding="0">
    <tr>
    <td width="150">Country</td>
    <td width="150"><select name="country" onChange="getCity('findcity.php?country='+this.value)">
    <option value="">Select Country</option>
    <option value="1">USA</option>
    <option value="2">Canada</option>
    </select></td>
    </tr>
    <tr style="">
    <td>City</td>
    <td ><div id="citydiv"><select name="city">
    <option>Select City</option>
    </select></div></td>
    </tr>
    <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    </tr>
    <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    </tr>
    </table>
    </form>
    </body>
    </html>
    ==========
    But when I sellect Country , city don't sellect automatic
    HELP ME

  2. #2
    SitePoint Addict
    Join Date
    Dec 2005
    Posts
    336
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Right off the bat, if you are having issues, you should ask the content author as stated in the code you posted:
    Code:
    #### Roshan's Ajax dropdown code with php
    #### Copyright reserved to Roshan Bhattarai - nepaliboy007@yahoo.com
    #### if you have any problem contact me at http://roshanbh.com.np
    #### fell free to visit my blog http://php-ajax-guru.blogspot.com
    I don't like that example so I wrote my own version of it:
    Code PHP:
    <?php
     
    	/* SQL
     
    		CREATE TABLE `city` (
    		  `id` tinyint(4) NOT NULL AUTO_INCREMENT,
    		  `city` varchar(50) DEFAULT NULL,
    		  `countryid` tinyint(4) DEFAULT NULL,
    		  PRIMARY KEY (`id`)
    		) ENGINE=MyISAM;
     
    		INSERT INTO `city` VALUES(1, 'Los Angeles', 1);
    		INSERT INTO `city` VALUES(2, 'New York', 1);
    		INSERT INTO `city` VALUES(3, 'Toronto', 2);
    		INSERT INTO `city` VALUES(4, 'Vancouver', 2);
     
    		CREATE TABLE `country` (
    		  `id` tinyint(4) NOT NULL AUTO_INCREMENT,
    		  `country` varchar(20) NOT NULL DEFAULT '',
    		  PRIMARY KEY (`id`)
    		) ENGINE=MyISAM;
     
     
    		INSERT INTO `country` VALUES(1, 'USA');
    		INSERT INTO `country` VALUES(2, 'Canada');
     
    	*/
     
    	error_reporting(-1);
     
    	try {
    		$dbh = new PDO(
    			'mysql:dbname=test;host=localhost', 
    			'root', 
    			'root'
    		);
    	} catch (PDOException $e) {
    		echo 'Connection failed: ' . $e->getMessage();
    	}	
     
    	function getCountries($db) {
    		$list = '';
    		$sql = 'SELECT id, country FROM country';
     
    		$stmt = $db->query($sql);
    		while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
    			$list[] = $row;
    		}		
    		return $list;
    	}
     
    	function getCitiesFromID($id, $db) {
    		$list = '';
    		$sql = 'SELECT id, city FROM city WHERE countryid = ?';
     
    		$stmt = $db->prepare($sql);
    		$stmt->bindParam(1, $id, PDO::PARAM_INT);
    		$stmt->execute();
    		while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
    			$list[] = $row;
    		}		
    		return $list;		
    	}
     
    	if( isset($_GET['country']) ) {
    		echo json_encode( getCitiesFromID( $_GET['country'], $dbh ) );
    		die();
    	}
     
    ?>
    <html>
    	<body>
    		<form id="testForm">
     
    			<label>Country</label>
    			<select name="country">
    				<option></option>
    				<?php 
    					foreach( getCountries($dbh) as $row ) {
    						echo '<option value="' . $row['id'] .'">' . $row['country'] .'</option>';				
    					}
    				?>
    			</select>	
     
    			<label>City</label>
    			<select name="city"></select>		
     
    		</form>
     
    		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    		<script>
    			$('#testForm select[name="country"]').on( 
    				'change keyup', 
    				function() {
    					var $citySelect = $('#testForm select[name="city"]');
    						$citySelect.empty();				
    					if( parseInt(this.value) ) { // so we don't parse the empty option...
    						$.ajax({
    							url: 'test.php?country=' + this.value,
    							dataType: 'json',
    							success: function(data) {
    								$.each(data, function(k,v) {
    									$citySelect.append('<option value="' + data[k].id + '">' + data[k].city + '</option>');
    								});
    							}
    						});
    					}
    				}				
    			);
    		</script>
    	</body>
    </html>

  3. #3
    SitePoint Enthusiast
    Join Date
    Oct 2010
    Posts
    61
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks you very much!


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •