php and ajax dynamically created select box onchange event

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Leena P
    New Member
    • Mar 2007
    • 11

    php and ajax dynamically created select box onchange event

    i want to basically take some information for the product and let the user
    enter the the material required to make this product

    1.first page test.php
    which takes product code and displays prodcut anme have used
    ajax to avoid refreshing of page this works fine
    2.now i have created one row with
    checkbox|select box|text|text|t ext|text|
    where in the select box values are fetched from table here also i have used ajax for getting the m_name automatically withput refreshi works fine (onchange event)
    3.after that i have given a add rows button on which rows are added dynamically
    with the same like static row i have added
    now i wantto use the same function i have used for static select box for avoiding refreshing here how do i pass the onchange event here
    and after pressing submit button the dynamic rows created disappears
    can anybody help me wot is wrong with this

    how do i pass dynamic elements values from the rows to the php along with the static row values
    my code is as follows

    [CODE=php]test.php


    <?

    include("../include/connection.php" );
    if($_GET)
    {
    $p_cde=$_GET['p_cde'];

    $cnt = count($_GET['m_cde'])+1;
    for ($idx=0;$idx<=$ cnt;$idx++) {
    $m_cde= $_GET['m_cde'][$idx] ;
    $m_name=$_GET['m_name'][$idx];
    $um=$_GET['um'][$idx];
    $qty=$_GET['qty'][$idx];
    $overages=$_GET['overages'][$idx];
    }
    }
    ?>
    <html>
    <head>
    <script src="test.js" ></script>
    </head>
    <body><form name="material" method="GET">
    <table id="tbl" border="1">
    <tr><td>
    <select name="p_cde" id="p_cde" onChange="showC ode(this.value) ;">
    <?
    $sqlpr = "select * from fgmaster order by p_cde ";
    $db_query=$DB_s ite->query($sqlpr );
    while($rspr=$DB _site->fetch_array($d b_query)){
    $combopr=$combo pr."<option value='".$rspr['p_cde']."'";
    if ($rspr['p_cde']==strtoupper($p _cde)){
    $combopr=$combo pr."selected";
    }
    $combopr=$combo pr.">".$rspr['p_cde']."-".$rspr['p_name']."</option>\n";
    }
    echo $combopr;

    ?>
    </select>
    </td>

    <td><input type="text" name="p_name" id="p_name" value=""></td>
    <td><input type="text" name="p_pckunit " id="p_pckunit" value=""></td></tr>
    <?
    $sqlmaterial="s elect * from materialmaster order by m_cde";
    $db_query_mater ial=$DB_site->query($sqlmate rial);
    while($rsmateri al=$DB_site->fetch_array($d b_query_materia l)){
    $option_vals[]=$rsmaterial['m_cde']."-".$rsmateri al['m_name'];
    }
    ?>
    <script>
    select_opt = new Array();
    <?
    for($i=0;$i<cou nt($option_vals );$i++){
    ?>
    select_opt[<?= $i ?>] = '<?= $option_vals[$i] ?>';
    <?
    }
    ?>
    </SCRIPT>

    <tr bgcolor="#CCCCC C" bordercolor="#F FCCFF">
    <th>&nbsp;&nbsp ; </th>

    <th >Code</th>

    <th>Material description</th>

    <th>um</th>

    <th>qty</th>

    <th>overages</th>



    </tr>


    <tr>
    <td><input type="checkbox" name="chk" id="chk"></td>
    <td><select name='m_cde' id='m_cde' onChange='showm code(this.value );'>
    <?
    $sqlmr = "select * from materialmaster order by m_cde ";
    $db_query_mr=$D B_site->query($sqlmr );
    while($rsmr=$DB _site->fetch_array($d b_query_mr)){
    $combomr=$combo mr."<option value='".$rsmr['m_cde']."'";
    if ($rsmr['m_cde']==strtoupper($m _cde)){
    $combomr=$combo mr."selected";
    }
    $combomr=$combo mr.">".$rsmr['m_cde']."-".$rsmr['m_name']."</option>\n";
    }
    echo $combomr;
    ?>
    </select></td>
    </td><td><input type="text" name='m_name' id='m_name' value=""></td>
    <td><input type="text" name='um' id='um' value=""></td>
    <td><input type="text" name='qty' id='qty' value=""></td>
    <td><input type="text" name='overages' id='overages' value=""></td>
    </tr>

    <tbody>
    </tbody>
    </table>
    <DIV>
    <input type ="button" value="Add Row" onclick="add_ro ws(document.get ElementById('tb l'));">
    </div>
    <DIV><input type ="submit" value="Submit" name="myfields" ></DIV>
    </form>
    </body>
    </html>[/CODE]

    [CODE=javascript]test.js
    ------------
    // JavaScript Document
    var xmlHttp;
    function showCode(str)
    {
    xmlHttp=GetXmlH ttpObject(); //Calls on the GetXmlHttpObjec t function to create an XMLHTTP object
    if (xmlHttp==null)
    {
    alert ("Browser does not support HTTP Request");
    return;
    }
    var url="testget.ph p"; //Defines the url (filename) to send to the server
    url=url+"?p_cde ="+str; //Adds a parameter (q) to the url with the content of the dropdown box
    url=url+"&sid=" +Math.random(); //Adds a random number to prevent the server from using a cached file
    xmlHttp.onready statechange=sta teChanged ; //Call stateChanged when a change is triggered
    xmlHttp.open("G ET",url,true) ; //Opens the XMLHTTP object with the given url.
    xmlHttp.send(nu ll); //Sends an HTTP request to the server
    alert(url);
    }
    function showmcode(str)
    {
    xmlHttp=GetXmlH ttpObject(); //Calls on the GetXmlHttpObjec t function to create an XMLHTTP object
    alert(str);
    if (xmlHttp==null)
    {
    alert ("Browser does not support HTTP Request");
    return;
    }
    var url="testget.ph p"; //Defines the url (filename) to send to the server
    url=url+"?m_cde ="+str; //Adds a parameter (q) to the url with the content of the dropdown box
    url=url+"&sid=" +Math.random(); //Adds a random number to prevent the server from using a cached file
    xmlHttp.onready statechange=sta teChanged1 ; //Call stateChanged when a change is triggered
    xmlHttp.open("G ET",url,true) ; //Opens the XMLHTTP object with the given url.
    xmlHttp.send(nu ll); //Sends an HTTP request to the server
    alert(url);
    }
    function stateChanged()
    {
    if (xmlHttp.readyS tate==4 || xmlHttp.readySt ate=="complete" )
    {

    var ar=xmlHttp.resp onseText.split( "|");

    document.getEle mentById("p_nam e").value=ar[0] ;
    document.getEle mentById("p_pck unit").value=ar[1] ;


    }
    }

    function stateChanged1()
    {
    if (xmlHttp.readyS tate==4 || xmlHttp.readySt ate=="complete" )
    {
    var ar=xmlHttp.resp onseText.split( "|");
    document.getEle mentById("m_nam e").value=ar[0] ;
    document.getEle mentById("um"). value=ar[1] ;
    }
    }
    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;
    }



    //FUNCTION FOR DYNAMIC ROW

    j=0;
    function add_rows(obj){

    //tabObj = document.create Element("table" );
    //tbodyObj = document.create Element("tbody" );

    tabCols = new init_table();
    trObj = document.create Element("tr")
    col_names = new Array("chk","m_ cde","m_name"," um","qty","over ages");
    for(i=0;i<tabCo ls.length;i++){
    tdObj = document.create Element("td");
    /*
    if(create_objec t(tabCols[i])=="select")
    {
    mselect=create_ object(tabCols[i],col_names[i]+'['+j+']')
    mselect.onChang e=showmcode(col _names[i]+'['+j+']');
    tdObj.appendChi ld(mselect));
    }*/

    tdObj.appendChi ld(create_objec t(tabCols[i],col_names[i]+'['+j+']'));

    //added on 04/09/2007 for onchage event on select box
    /* if(tabCols[i]=="select"){
    alert("hi");
    col_names[i]+'['+j+']'="fieldevent(' "+fieldname+"') ";
    var showmcode=new Function(col_na mes[i]+'['+j+']'.onchange);
    if(col_names[i]+'['+j+']'.addEventListe ner){
    col_names[i]+'['+j+']'.addEventListe ner('change',sh owmcode,false);
    else if(col_names[i]+'['+j+']'.attachEvent){
    col_names[i]+'['+j+']'.attachEvent(' onchange',showm code);}
    }
    /* this is a sample
    sfield.onchange = "fieldevent ('" + fieldname + "')";
    var onChangeHandler = new Function(sfield .onchange);
    if (sfield.addEven tListener) {
    sfield.addEvent Listener('chang e', onChangeHandler , false );
    } else if (sfield.attachE vent) {
    sfield.attachEv ent('onchange', onChangeHandler );
    }
    */
    trObj.appendChi ld(tdObj);

    }
    obj.firstChild. appendChild(trO bj);


    j++;

    }

    function fieldevent(fnam e){

    alert (fname);
    }



    function init_table(){
    tableProp = new Array();

    tableProp[0] = "checkbox";
    tableProp[1] = "select"; //m_cde
    tableProp[2] = "text"; //m_name
    tableProp[3] = "text"; //um
    tableProp[4] = "text"; //qty
    tableProp[5] = "text"; //overages
    //tableProp[6] = "checkbox";

    return tableProp;
    }

    function create_object(o bjType,nm){
    if(objType == 'select'){
    return getSelectBoxDOM (select_opt,nm) ;
    }

    obj = document.create Element("input" );
    obj.setAttribut e("type",objTyp e);
    obj.setAttribut e("name",nm);


    return obj;
    }

    function getSelectBoxDOM (options,nm) {
    selectBox =document.creat eElement('selec t');
    for (x=0; x < options.length; x++) {
    optionItem =document.creat eElement('optio n');
    optionItem.appe ndChild(documen t.createTextNod e(options[x]));
    selectBox.appen dChild(optionIt em);


    }
    selectBox.setAt tribute("name", nm);


    return selectBox;

    }[/CODE]



    [CODE=php]testget.php
    ----------------


    <?php
    if($_GET)
    {

    $p_cde=$_GET['p_cde'];


    $con = mysql_connect(' localhost', 'localhost', ''); //PHP opens a connection to a MySQL server

    if (!$con)
    {
    die('Could not connect: ' . mysql_error());
    }
    mysql_select_db ("erpmfg", $con);
    $sql="select * from fgmaster where p_cde = '".$p_cde."' ";
    $result = mysql_query($sq l);
    while($row = mysql_fetch_arr ay($result)){
    $p_name=$row['p_name'];
    $p_pckunit=$row['p_pckunit'];
    echo $p_name."|".$p_ pckunit;
    }
    }

    if ($_GET)
    {

    $m_cde=$_GET['m_cde'];

    $sqlmr="select * from materialmaster where m_cde = '".$m_cde."' ";
    $result1 = mysql_query($sq lmr);

    while($row = mysql_fetch_arr ay($result1)){
    $m_name=$row['m_name'];
    $um=$row['um'];

    echo $m_name."|".$um ;
    }
    }


    mysql_close($co n);
    ?>[/CODE]
    Last edited by acoder; Sep 5 '07, 07:29 AM. Reason: Added languages to code tags
  • dmjpro
    Top Contributor
    • Jan 2007
    • 2476

    #2
    Please use Code tags then it will be easy to Solve your Problem.

    Kind regards,
    Dmjpro.

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      Leena, welcome to TSDN!

      Did you know that you can specify languages in the code tags, e.g. [code=javascript]...[/code.] (remove the dot).

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        Give your dynamically created elements ids. For your select, add the onchange when you create the element.

        Comment

        • Leena P
          New Member
          • Mar 2007
          • 11

          #5
          [code=javascript]j=1;
          function add_rows(obj){

          tabCols = new init_table();
          trObj = document.create Element("tr")
          col_names = new Array("chk","m_ cde","m_name"," um","qty","over ages");
          for(i=0;i<tabCo ls.length;i++){
          tdObj = document.create Element("td");
          /* if(create_objec t(tabCols[i])=="select")
          {
          mselect=create_ object(tabCols[i],col_names[i]+'['+j+']')
          mselect.onChang e=showmcode(col _names[i]+'['+j+']');
          tdObj.appendChi ld(mselect));
          }*/

          tdObj.appendChi ld(create_objec t(tabCols[i],col_names[i]+'['+j+']'));[/CODE]



          i was trying the above commented line in add_rows function while creating a select box using createElement function for onchange where am i going wrong
          Last edited by acoder; Sep 5 '07, 09:27 AM. Reason: Added opening code tag

          Comment

          • acoder
            Recognized Expert MVP
            • Nov 2006
            • 16032

            #6
            Originally posted by Leena P
            i was trying the above commented line in add_rows function while creating a select box using createElement function for onchange where am i going wrong
            Use onchange (lower case "c").

            Comment

            • Leena P
              New Member
              • Mar 2007
              • 11

              #7
              i tried that but then my add rows button does not create new row some error
              but if comment that part then it works
              how to give onchage event when the select box is created

              [CODE=javascript]function getSelectBoxDOM (options,nm) {
              selectBox =document.creat eElement('selec t');
              for (x=0; x < options.length; x++) {
              optionItem =document.creat eElement('optio n');
              optionItem.appe ndChild(documen t.createTextNod e(options[x]));
              selectBox.appen dChild(optionIt em);


              }
              selectBox.setAt tribute("name", nm);
              selectBox.setAt tribute("id",nm );
              //after this say selectBox.oncha nge=showmcode(n m.value)....... . ??????
              where nm is the name of the selectbox
              return selectBox;
              }
              [/CODE]
              i tried this bt giving error property not supported

              thanks.
              Last edited by acoder; Sep 5 '07, 09:48 AM. Reason: Added code tags

              Comment

              • acoder
                Recognized Expert MVP
                • Nov 2006
                • 16032

                #8
                Please use code tags when posting code. Thanks!

                You need to assign a function object to the onchange, not the result of the function. See this article.

                Try:[CODE=javascript]selectBox.oncha nge = function() {
                showmcode(selec tBox.value);
                }[/CODE]

                Comment

                • Leena P
                  New Member
                  • Mar 2007
                  • 11

                  #9
                  i tried that but then my add rows button does not create new row some error
                  but if comment that part then it works
                  how to give onchage event when the select box is created

                  [CODE=javascript]function getSelectBoxDOM (options,nm) {
                  selectBox =document.creat eElement('selec t');
                  for (x=0; x < options.length; x++) {
                  optionItem =document.creat eElement('optio n');
                  optionItem.appe ndChild(documen t.createTextNod e(options[x]));
                  selectBox.appen dChild(optionIt em);


                  }
                  selectBox.setAt tribute("name", nm);
                  selectBox.setAt tribute("id",nm );
                  //after this say selectBox.oncha nge=showmcode(n m.value)....... . ??????
                  where nm is the name of the selectbox
                  return selectBox;
                  }

                  [/CODE]i tried this bt giving error property not supported

                  thanks.
                  Last edited by acoder; Sep 5 '07, 11:23 AM. Reason: Added code tags

                  Comment

                  • acoder
                    Recognized Expert MVP
                    • Nov 2006
                    • 16032

                    #10
                    Make sure you use code tags. This is the final friendly request. The last post seems like a repeat of your previous comment.

                    Comment

                    • Leena P
                      New Member
                      • Mar 2007
                      • 11

                      #11
                      [CODE=javascript]selectBox.oncha nge = function() {
                      showmcode(selec tBox.value);
                      }[/CODE]


                      i did this but now it add a record but once i select value from dynamically added select box the value of m_name is not shown in corresponding text box there and my static rows um and m_name disappears which i had selected and where onchange event it had executed ajax script to display m_name and um


                      thanks

                      Comment

                      • acoder
                        Recognized Expert MVP
                        • Nov 2006
                        • 16032

                        #12
                        Try[CODE=javascript]selectBox.oncha nge = function() {
                        showmcode(this. value);
                        }[/CODE]Don't forget to set the values of the option elements.

                        Comment

                        • Leena P
                          New Member
                          • Mar 2007
                          • 11

                          #13
                          same problem i changes it to this.value

                          i'm setting the options in the getselectbox function
                          and then actual database values are passed in test.php program

                          can't understand what is wrong with my code



                          thanks

                          Comment

                          • markrawlingson
                            Recognized Expert Contributor
                            • Aug 2007
                            • 346

                            #14
                            Try..

                            [CODE=javascript]
                            selectBox.oncha nge = function() {
                            showmcode(this. options[this.selectedIn dex].value);
                            }
                            [/CODE]

                            Comment

                            • acoder
                              Recognized Expert MVP
                              • Nov 2006
                              • 16032

                              #15
                              Originally posted by Leena P
                              same problem i changes it to this.value

                              i'm setting the options in the getselectbox function
                              and then actual database values are passed in test.php program

                              can't understand what is wrong with my code
                              You're not setting the value of the options. Set the value by using .value or setAttribute, e.g.[CODE=javascript]optionItem.valu e = 'someval';[/CODE]

                              Comment

                              Working...