Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 30
  1. #1
    New Coder
    Join Date
    Mar 2012
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Dynamically add select boxes based on selection

    Hello guys,

    I have created an interface through which you can add fields and their respective options, the structure is below:

    Code:
    CREATE TABLE fields (
      `id` int(8) NOT NULL auto_increment,
      `name` varchar(150) default '0',
      `desc` varchar(150) default '0',
      PRIMARY KEY  (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1
    
    CREATE TABLE options (
      `optionid` int(8) NOT NULL auto_increment,
      `fieldid` int(8) default '0',
      `value` varchar(150) default '',
      `assignfield` varchar(90) default '0',
      `assigngroup` int(8) default '0',
      PRIMARY KEY  (`optionid`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1
    There is a an option where the user can select the main field, that means the field that gets displayed first and based on what option you select (if it has an assigned field) it should get the select box via ajax and add it into the form. The user can then select an option from that field which would call another field and so on....it's not limited.

    Here is the ajax php code:

    Code:
    if (isset($_POST['col']) && isset($_POST['wval']))
    {
    $vbulletin->input->clean_array_gpc('p', array(
            'col'   => TYPE_STR,
            'wval'   => TYPE_STR
    	));
        
        $col = trim(strip_tags($_POST['col']));
        $wval = "'" . trim(strip_tags($_POST['wval'])) . "'";
        
    $optionid = $vbulletin->db->query_first("SELECT assignfield AS fieldid
        FROM " . TABLE_PREFIX . "ziki_franco_option
        WHERE optionid = '". $col ."'");
        
    $subfield = $vbulletin->db->query_first("SELECT *
        FROM " . TABLE_PREFIX . "ziki_franco_field
        WHERE id = '". $optionid['fieldid'] ."'");
    $suboptions = $vbulletin->db->query_read("SELECT *
        FROM " . TABLE_PREFIX . "ziki_franco_option
        WHERE fieldid = '". $optionid['fieldid'] ."'");
    while ($suboption = $vbulletin->db->fetch_array($suboptions))
    {
    $subfieldbits .= '<option value="' . $suboption['optionid'] . '" onchange="ajaxReq('. $suboption['assignfield'] .', this.value);">' . $suboption['value'] . '</option>';
    }
    
    $templater = vB_Template::create('ziki_franco_subfield');
    				$templater->register('subfield', $subfield);
    				$templater->register('subfieldbits', $subfieldbits);
    				$templater->register('nextfield', $nextfield);
                    $templater->render();
    }
    the template contains the html code below:

    Code:
    <div class="blockrow" id="zfieldblock">
    	<label>{vb:raw mainfield.name}:</label>
    	<div class="rightcol" id="zfieldname>
    <select class="primary" name="{vb:raw mainfield.name}" id="zfield_{vb:raw mainfield.id}" tabindex="1">
    	<option value="0" selected="selected"></option>
    		{vb:raw mainfieldbits}
    </select>
    <input type="hidden" name="{vb:raw mainfield.name}" value="1" />
    <p class="description">{vb:raw mainfield.desc}</p>
    	</div>
    {vb:raw nextfield}
    </div>
    the code in the main php file (which is the one the user loads) is pretty much the same. The Javascript code I use in the main file is:

    Code:
     <script type="text/javascript">
    
    function get_XmlHttp() {
      var xmlHttp = null;
    
      if(window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } 
      else if(window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
    
      return xmlHttp;
    }
    
    function removeLists(colid) {
      var z = 0;
      for(var i=1; i<ar_cols.length; i++) {
        if(ar_cols[i]==null) continue;
        if(ar_cols[i]==colid) z = 1;
        if(z==1) document.getElementById(preid+ar_cols[i]).innerHTML = '';
      }
    }
    
    // sends data to a php file, via POST, and displays the received answer
    function ajaxReq(col, wval) {
     // removeLists(col);      
    
    
      if(wval!='- - -' && wval!='') {
        var request =  get_XmlHttp();		      
        var php_file = 'ajax.php'; 
        var  getfields = 'yes';
        var  data_send = 'col='+col+'&wval='+wval+';
    
        request.open("POST", php_file, true)
        document.getElementById(preid+col).innerHTML = '<img src="./images/misc/progress.gif alt="Loading..." />';
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        request.send(data_send);
    
        request.onreadystatechange = function() {
          if (request.readyState==4) {
            document.getElementById(preid+col).innerHTML = request.responseText;
          }
        }
      }
    }
            </script>
    Since I am very poor with AJAX, this does not work.Could someone refer me to an working example or help me out with it? I am willing to donate some money.

    Thank you!
    Last edited by komplexbs; 03-20-2012 at 03:43 PM.

  • #2
    New Coder
    Join Date
    Mar 2012
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts
    I forgot to mention, that this is a vBulletin plugin (hence the {vb:raw varname} instead of $varname), but it should work the same

  • #3
    New Coder
    Join Date
    Mar 2012
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Just realized that the ajax php code is not correct, it should first get the assigned field id of the selected option.

  • #4
    New Coder
    Join Date
    Mar 2012
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts
    I have updated the code in the first post with what I have now but it still doesn't work. Please I really need this, I am willing to donate 30$ to anyone who can help me get this working.

  • #5
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,391
    Thanks
    11
    Thanked 568 Times in 561 Posts
    One important thing, right from the start

    You should get used to using .encodeURIComponent() to ensure proper URI conform encoding of the parameter string. Maybe this is the solution, maybe not :-)

    Second, and even more important: There was an error in this line. The trailing ' quote has to be omitted
    Code:
    var  data_send = 'col='+col+'&wval='+encodeURIComponent(wval);
    One more thing, though less important: Since IE7 you don't need a browser switch any more. It's simply
    Code:
    var request =  new XMLHttpRequest();
    to create a new request object instance. No more silly ActiveXObject stuff any more :-)

    And finally: The onreadystatechange assignment should be after .open() but before .send(). Otherwise it could be possible that certain state changes will not trigger the event handler.
    Code:
        request.open("POST", php_file, true)
        request.onreadystatechange = function() {
          if (request.readyState==4) {
            document.getElementById(preid+col).innerHTML = request.responseText;
          }
        }
        document.getElementById(preid+col).innerHTML = '<img src="./images/misc/progress.gif alt="Loading..." />';
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        request.send(data_send);
    Last edited by devnull69; 03-20-2012 at 04:06 PM.

  • #6
    New Coder
    Join Date
    Mar 2012
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by devnull69 View Post
    One important thing, right from the start

    You should get used to using .encodeURIComponent() to ensure proper URI conform encoding of the parameter string. Maybe this is the solution, maybe not :-)

    Second, and even more important: There was an error in this line. The trailing ' quote has to be omitted
    Code:
    var  data_send = 'col='+col+'&wval='+encodeURIComponent(wval);
    One more thing, though less important: Since IE7 you don't need a browser switch any more. It's simply
    Code:
    var request =  new XMLHttpRequest();
    to create a new request object instance. No more silly ActiveXObject stuff any more :-)
    Thank you very much! I updated my code with your advice but the problem still persists. After selecting an option, the second select box does not appear

  • #7
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,391
    Thanks
    11
    Thanked 568 Times in 561 Posts
    Either it's time to start debugging or you need to provide us with more information, preferrably in the form of a testable URL.

    Hints for debugging: What browser do you use?

    Firefox: Intall the Firebug plug-in
    Chrome, IE, Opera: Use the built-in developer tools
    Safari: Don't know :-)

    By pressing F12 you'll see the developer tools, where you can observe the script (on the Scripts tab) and the Ajax requests (on the Net tab). You'll be able to see, which information is sent and received and you'll get a general status of your application.

  • #8
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,391
    Thanks
    11
    Thanked 568 Times in 561 Posts
    One more thing:

    You are using the variable "preid" everywhere in your code, but it doesn't seem to be defined or set anywhere. What is it?

  • #9
    New Coder
    Join Date
    Mar 2012
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by devnull69 View Post
    Either it's time to start debugging or you need to provide us with more information, preferrably in the form of a testable URL.

    Hints for debugging: What browser do you use?

    Firefox: Intall the Firebug plug-in
    Chrome, IE, Opera: Use the built-in developer tools
    Safari: Don't know :-)

    By pressing F12 you'll see the developer tools, where you can observe the script (on the Scripts tab) and the Ajax requests (on the Net tab). You'll be able to see, which information is sent and received and you'll get a general status of your application.
    I use firefox and have firebug installed but I have no idea how to debug ajax or javascript. I am mainly a php coder but I am completely new to javascript and ajax :-/

    Quote Originally Posted by devnull69 View Post
    One more thing:

    You are using the variable "preid" everywhere in your code, but it doesn't seem to be defined or set anywhere. What is it?
    It is the prefix each of the fields has (in this case zfield). I'm pretty sure the AJAX code is wrong, because I'm not familiar with it and it's something I put together from several JS examples.
    Last edited by komplexbs; 03-20-2012 at 07:37 PM.

  • #10
    New Coder
    Join Date
    Mar 2012
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Ok, I tested it with firebug and no ajax requests is being made.

  • #11
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,391
    Thanks
    11
    Thanked 568 Times in 561 Posts
    Did you try to go into full debug mode? Step-by-step execution? Watch expressions? Somehow you need to track down the problem, because the Ajax code itself seems to be quite okay. If you don't give us access to a live URL (maybe even a reduced version) we cannot help you with that.

  • #12
    New Coder
    Join Date
    Mar 2012
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by devnull69 View Post
    Did you try to go into full debug mode? Step-by-step execution? Watch expressions? Somehow you need to track down the problem, because the Ajax code itself seems to be quite okay. If you don't give us access to a live URL (maybe even a reduced version) we cannot help you with that.
    Sorry, I don't have a live forum for this, I'm only doing it on my localhost. How do I enable debug mode?

  • #13
    New Coder
    Join Date
    Mar 2012
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts
    I tried putting window.alert('test'); into ajaxReq, but upon option change, no message appears.

  • #14
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,391
    Thanks
    11
    Thanked 568 Times in 561 Posts
    It's really hard to tell where the problem is without access to the application....

    Nevertheless, you can activate full debug mode by adding a breakpoint to a line of code that you expect to be executed during your test. Once you start another action or refresh the page the program flow will eventually reach that line and stop. From that point forward you can step through your code (using F10 for step-over and F11 for step-into), observe variables on the "Watch" tab, see messages and/or errors on the Console and net activity on the "Net" tab.

    Btw, you set a breakpoint in almost every available developer tool by clicking on the line number in the script view.

    With a right mouse click you can turn the breakpoint into a conditional breakpoint, so you can state a condition under which the breakpoint will stop the program at the current line.

  • #15
    Senior Coder Rowsdower!'s Avatar
    Join Date
    Oct 2008
    Location
    Some say it's everything.
    Posts
    2,027
    Thanks
    5
    Thanked 397 Times in 390 Posts
    As an alternative to the above (if you are not comfortable with the Firebug debugging tools) you can add the Web Developer plugin to your installation of Firefox:

    https://addons.mozilla.org/en-US/fir...web-developer/

    This will give you (among many other useful things) three little circles in your plugin bar at the top right of your browser and when a page loads those circles will turn into green check marks or red X's to indicate whether or not there are javascript or CSS problems with the page being viewed. When javascript errors occur in the page (as in your case) and you click on those three icons it will open the error log and give you a javascript line number and a description of the error to point out exactly where things went wrong.

    If you won't publish a sample page for us to debug then at least having this information would speed up your debugging process significantly...
    The object of opening the mind, as of opening the mouth, is to shut it again on something solid. –G.K. Chesterton
    See Mediocrity in its Infancy
    It's usually a good idea to start out with this at the VERY TOP of your CSS: * {border:0;margin:0;padding:0;}
    Seek and you shall find... basically:
    validate your markup | view your page cross-browser/cross-platform | free web tutorials | free hosting


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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