CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Ajax and Design (http://www.codingforums.com/forumdisplay.php?f=55)
-   -   Dynamically add select boxes based on selection (http://www.codingforums.com/showthread.php?t=254641)

komplexbs 03-20-2012 11:33 AM

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!

komplexbs 03-20-2012 11:34 AM

I forgot to mention, that this is a vBulletin plugin (hence the {vb:raw varname} instead of $varname), but it should work the same

komplexbs 03-20-2012 11:59 AM

Just realized that the ajax php code is not correct, it should first get the assigned field id of the selected option.

komplexbs 03-20-2012 03:43 PM

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.

devnull69 03-20-2012 03:59 PM

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);


komplexbs 03-20-2012 04:05 PM

Quote:

Originally Posted by devnull69 (Post 1206452)
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

devnull69 03-20-2012 04:10 PM

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.

devnull69 03-20-2012 04:28 PM

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?

komplexbs 03-20-2012 07:13 PM

Quote:

Originally Posted by devnull69 (Post 1206459)
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 (Post 1206468)
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.

komplexbs 03-20-2012 07:32 PM

Ok, I tested it with firebug and no ajax requests is being made.

devnull69 03-20-2012 07:37 PM

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.

komplexbs 03-20-2012 07:42 PM

Quote:

Originally Posted by devnull69 (Post 1206539)
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?

komplexbs 03-20-2012 07:45 PM

I tried putting window.alert('test'); into ajaxReq, but upon option change, no message appears.

devnull69 03-21-2012 09:14 AM

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.

Rowsdower! 03-21-2012 01:11 PM

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


All times are GMT +1. The time now is 10:46 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.