Populating drop down menu from databse on onChnage() of first dropdown without refre

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tokcy
    New Member
    • Sep 2008
    • 45

    Populating drop down menu from databse on onChnage() of first dropdown without refre

    Hi everyone,
    I am new in php and ajax, i am facing the prob while i click on element of first drop down then in second dropdown all element showl come from database.
    I mean i have three dropdown 1. category which comes from database 2. brand which comes from databse according to content of first dropdown . and 3. price which is static.
    when i am doing these things without ajax on every onChange() thw whole page is refreshing that i do not want. and with ajax i am facing some prob like i have two php pages in one page all drop down is written and in socond php page only brand' s drop down is written i mean when i ma calling any category from databse then in brand dropdown category comes from database but suppose i am choosing a COPUTER then computer related brand comes from databse and replace the existing drop down . i do not want to replace the drop down i want to clear the content of first page dropdown and populate the content which comes from second page.

    here is code:
    selectbrand.js
    [CODE=javascript]var xmlHttp

    function showBrand(str)
    {
    xmlHttp=GetXmlH ttpObject()
    if (xmlHttp==null)
    {
    alert ("Browser does not support HTTP Request")
    return
    }
    var url="search2.ph p"
    url=url+"?id="+ str
    url=url+"&sid=" +Math.random()
    xmlHttp.onready statechange=sta teChanged
    xmlHttp.open("G ET",url,true)
    xmlHttp.send(nu ll)
    }
    function stateChanged()
    {
    if (xmlHttp.readyS tate==4 || xmlHttp.readySt ate=="complete" )
    {
    document.getEle mentById("txtHi nt").innerHTML= xmlHttp.respons eText
    }
    }

    function GetXmlHttpObjec t()
    {
    var xmlHttp=null;
    try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest( );
    }
    catch (e)
    {
    //Internet Explorer
    try
    {
    xmlHttp=new ActiveXObject(" Msxml2.XMLHTTP" );
    }
    catch (e)
    {
    xmlHttp=new ActiveXObject(" Microsoft.XMLHT TP");
    }
    }
    return xmlHttp;
    return true;
    }
    [/CODE]
    and first php page
    search1.php

    [PHP]<html>
    <head>
    <script src="selectbran d.js"></script>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>MB Solution Wikki</title>
    <link rel="stylesheet " href="css_searc h.css" title="wikki">
    </head>
    <body>
    <table cellpadding="0" cellspacing="0" width="100%">
    <tbody><tr><t d align="center">
    <table style="margin-top: 1em; width: 80%;" cellpadding="0" cellspacing="0" >
    <tbody>
    <tr>
    <td align="left">
    <div class="outer-box">
    <div class="qbuilder-env" style=""></div>
    <form method="get" name="f">
    <div style="width: 100%;">
    <h3>Find Article that have...</h3>
    <input name="hl" value="en" type="hidden">< table cellpadding="2" cellspacing="0" width="100%">
    <tbody>
    <tr>
    <td class="label">K eyword</td>
    <td class="input">< input type="text" name="key" id="key" size="55"><td>
    <td class="tip">&nb sp;</td>
    </tr>
    <tr>
    <td class="label">< label>Category: </label></td>
    <td class="input">
    <select name="cat" id="cat" onChange="showB rand(this.value )">
    <option value="0" >Select</option>
    <?

    $conn = mysql_connect(" localhost", "root", "");
    $db = mysql_select_db ("gadget");

    $result = mysql_query("se lect id, name from `category` GROUP BY name");
    $i = 0;
    while($rows = mysql_fetch_arr ay($result))
    {
    $val[$i] = $rows['id'];
    if($id == $val[$i]) $selected = "selected = 'selected'"; else $selected = "";
    print "<option value='".$val[$i]."' ".$selected.">" .$rows['name']."</option>";
    $i++;
    }

    ?>
    </select> </td>
    <input name="h2" type="hidden" value="" id="h2">
    <td class="tip">&nb sp;</td></tr>
    <tr>
    <td class="label">

    <label>Brand Name:</label></td>
    <td class="input">
    <div id="txtHint"> <select name="bname" size="1" id="bname">
    <option value="0">Selec t</option>
    <?

    if($id == 0)
    {
    $results = mysql_query("se lect prod_name from `products` GROUP BY prod_name");
    while($row = mysql_fetch_arr ay($results))
    {
    //echo $row['prod_name'];
    print "<option value='".$row['prod_name']."'>".$row['prod_name']."</option>";
    }
    }
    else
    {
    $results = mysql_query("se lect prod_name from products where cat_id = '".$id."'");
    while($row = mysql_fetch_arr ay($results))
    {
    print "<option value='".$row['prod_name']."'>".$row['prod_name']."</option>";
    }
    }
    ?>
    </select> </div> </td>
    <td class="tip">&nb sp;</td></tr>
    <tr>
    <td class="label">< label>Price Range :</label></td>
    <td id="or-cell" class="input">
    <table border="0" cellpadding="0" cellspacing="0" width="100%">
    <tbody>
    <tr>
    <td width="33%"> <select name="range">
    <option value="0" selected>Select </option>
    <option value="1000 - 2000">1000-2000</option>
    <option value="2000 - 4000">2000-4000</option>
    <option value="4000 - 10000">4000-10000</option>
    <option value="10000 - 15000">10000-15000</option>
    <option value="15000 - eof">15000 and above</option>
    </select> </td>
    </tr></tbody></table>

    <input name="as_oq" value="" type="hidden"> </td>
    <td class="tip">&nb sp;</td></tr></tbody></table>
    <h3 align="right" style="margin-top: 1em;">
    <label>
    <?
    $range = $_REQUEST['range'];
    $range = trim($range);
    $range1 = explode(" ",$range);
    ?>
    <input type="submit" name="search" value="Search" id="search">
    </label>
    </h3></div>
    <?php

    if(isset($_REQU EST['search']))
    {
    if($_REQUEST['cat'] == 0 && $range1[2] != "eof")
    {
    $qry = "SELECT prod_descr, prod_img, name, prod_name, prod_price_gros s from (SELECT * FROM `category` JOIN `products` ON category.id = products.cat_id ) as cp WHERE cp.prod_name = '".$_REQUEST['bname']."' AND cp.prod_price_g ross BETWEEN ".$range1[0]." and ".$range1[2]."";
    }
    elseif($_REQUES T['cat'] == 0 && $range1[2] == "eof")
    {
    $qry = "SELECT prod_descr, prod_img, name, prod_name, prod_price_gros s from (SELECT * FROM `category` JOIN `products` ON category.id = products.cat_id ) as cp WHERE cp.prod_name = '".$_REQUEST['bname']."' AND cp.prod_price_g ross >= ".$range1[0];

    }
    elseif($range1[2] != "eof")
    {
    $qry = "SELECT prod_descr, prod_img, name, prod_name, prod_price_gros s from (SELECT * FROM `category` JOIN `products` ON category.id = products.cat_id ) as cp WHERE cp.id = '".$_REQUEST['cat']."' AND cp.prod_name = '".$_REQUEST['sel']."' AND cp.prod_price_g ross BETWEEN ".$range1[0]." and ".$range1[2]."";
    }
    else
    {
    $qry = "SELECT prod_descr, prod_img, name, prod_name, prod_price_gros s from (SELECT * FROM `category` JOIN `products` ON category.id = products.cat_id ) as cp WHERE cp.id = '".$_REQUEST['cat']."' AND cp.prod_name = '".$_REQUEST['sel']."' AND cp.prod_price_g ross >= ".$range1[0];
    }
    $search = mysql_query($qr y) or die($qry);
    while($show = mysql_fetch_arr ay($search))
    {
    echo "<table width='100' border='0'>";
    echo "<tr>";
    echo '<td height="58"><ta ble width="100" height="100" border="0">';
    echo "<tr>";
    echo '<td height="79">';
    print "<img src=' ".$show['prod_img']." ' align='center' width='100' hieght='100' border='0'>";
    echo "</td>";
    echo "</tr>";
    echo "</table>";
    echo "</td>";
    echo '<td valign="top">';
    echo '<table width="200" border="0">';
    echo "<tr>";
    echo "<td><b>Categor y:</b>&nbsp;&nbsp;& nbsp;";
    print $show['name'];
    echo '</td>';
    echo '</tr>';
    echo '<tr>';
    echo '<td height="31"><b> Product Name:</b>&nbsp;&nbsp;& nbsp;';
    print $show['prod_name'];
    echo "</td>";
    echo "</tr>";
    echo '<tr>';
    echo '<td height="31"><b> Price:</b>&nbsp;&nbsp;& nbsp;';
    print $show['prod_price_gro ss'];
    echo "</td>";
    echo "</tr>";
    echo '<tr>';
    echo '<td height="31"><b> Description:</b>&nbsp;&nbsp;& nbsp;';
    print $show['prod_descr'];
    echo "</td>";
    echo "</tr>";
    echo "</table>";
    echo "</td>";
    echo "</tr>";
    echo "</table>";
    }

    }
    ?>
    </div>

    </form>

    </div></td>
    </tr></tbody></table></td></tr></tbody>
    </table> </body></html>
    [/PHP]
    and scond php page is ;;

    search2.php

    [PHP] <?php

    $id=$_REQUEST["id"];
    //echo $id;
    $con = mysql_connect(' localhost', 'root', '');
    if (!$con)
    {
    die('Could not connect: ' . mysql_error());
    }

    mysql_select_db ("gadget", $con);

    //echo "Select Brand:";
    echo '<select name="sel" id="sel" size="1">';
    echo '<option value="0">Selec t</option>';
    //$row = mysql_fetch_arr ay($result);
    if($id == "0")
    {
    $results = mysql_query("se lect prod_name from `products` GROUP BY prod_name");
    while($row = mysql_fetch_arr ay($results))
    {
    //echo $row['prod_name'];
    echo "<option value='".$row['prod_name']."'>".$row['prod_name']."</option>";
    }
    }
    else
    {
    $results = mysql_query("se lect prod_name from `products` where cat_id = '".$id."'");
    while($row = mysql_fetch_arr ay($results))
    {
    echo "<option value='".$row['prod_name']."'>".$row['prod_name']."</option>";
    }
    }

    echo "</select";
    mysql_close($co n);
    ?>[/PHP]
    Last edited by acoder; Sep 12 '08, 11:58 AM. Reason: Added [code] tags
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    Instead of returning the HTML code to replace the drop down, return a string delimited by a special character which you can use to populate the drop down element. Alternatively, you can use JSON or XML.

    PS. please use code tags when posting code. See How to ask a question.

    Comment

    • tokcy
      New Member
      • Sep 2008
      • 45

      #3
      Originally posted by acoder
      Instead of returning the HTML code to replace the drop down, return a string delimited by a special character which you can use to populate the drop down element. Alternatively, you can use JSON or XML.

      PS. please use code tags when posting code. See How to ask a question.
      Hi,
      thanx for reply .now i am using ur solution but in javascript populate function is not working . on click of first dropdown list it remove all yhe element of second dropdown but in case of filling second dropdown its not working..
      javascript code
      [CODE=javascript]
      // for removing element

      function dropdown(str,te xt,value)
      {
      var item=str.split( ',');
      var obj=document.ge tElementById("b name");
      //var opt = document.create Element("bname" );

      len=parseInt(ob j.length);
      for ( i=0;i<len;i++)
      {
      obj.options[i]=null;

      }
      //for adding element

      for(i=0;i<item. length;i++)
      {
      obj.options[obj.options.len gth].value=item[i];
      obj.options[obj.options.len gth].text=item[i];
      //alert(obj.optio ns[i].text);
      //var optn = document.create Element("bname" );
      //optn.text = text;
      //optn.value = value;
      //str.options.add (optn);
      */
      }[/code]
      please do something ...
      Last edited by acoder; Sep 13 '08, 12:09 PM. Reason: fixed code tags

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        Show the code/line where you call dropdown().

        Comment

        • tokcy
          New Member
          • Sep 2008
          • 45

          #5
          Originally posted by acoder
          Show the code/line where you call dropdown().
          here is the code where dropdown is calling

          Code:
          function stateChanged() 
          { 
          if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
           { 
           //document.getElementById("txtHint").innerHTML=xmlHttp.responseText 
          dropdown(xmlHttp.responseText);
           } 
          }
          line 6

          Comment

          • acoder
            Recognized Expert MVP
            • Nov 2006
            • 16032

            #6
            What's the response from the PHP script?

            Comment

            • tokcy
              New Member
              • Sep 2008
              • 45

              #7
              Originally posted by acoder
              What's the response from the PHP script?
              it removes all the element from second dropdown on click of the category of first dropdoen but not populating ...

              Comment

              • acoder
                Recognized Expert MVP
                • Nov 2006
                • 16032

                #8
                No, I meant if you run the PHP script directly without Ajax. Do you get the expected response?

                Comment

                • tokcy
                  New Member
                  • Sep 2008
                  • 45

                  #9
                  Originally posted by acoder
                  No, I meant if you run the PHP script directly without Ajax. Do you get the expected response?
                  yes i am getting expected response but there is a prob it refresh page on every change of category that i do not want...

                  Comment

                  • acoder
                    Recognized Expert MVP
                    • Nov 2006
                    • 16032

                    #10
                    I meant the responseText value. You could alert to check.

                    Try replacing the lines:
                    [code=javascript]obj.options[obj.options.len gth].value=item[i];
                    obj.options[obj.options.len gth].text=item[i];[/code]with
                    [code=javascript]obj.options[obj.options.len gth] = new Option(item[i], item[i]);[/code]

                    Comment

                    • tokcy
                      New Member
                      • Sep 2008
                      • 45

                      #11
                      Originally posted by acoder
                      I meant the responseText value. You could alert to check.

                      Try replacing the lines:
                      [code=javascript]obj.options[obj.options.len gth].value=item[i];
                      obj.options[obj.options.len gth].text=item[i];[/code]with
                      [code=javascript]obj.options[obj.options.len gth] = new Option(item[i], item[i]);[/code]
                      thanx dude...
                      its working now...i was making a mistake in php page i used implode function thats why not working and now i using string concate operation by using this code is working properly
                      but anyway thanx for your co-operation...

                      Comment

                      • acoder
                        Recognized Expert MVP
                        • Nov 2006
                        • 16032

                        #12
                        ...which is why I was saying that you should check the PHP page.

                        Anyway, glad it's working.

                        Comment

                        Working...