Simple pulldown script with redirect

Hi Guys,

I am a desperate noob with PHP, usually I get where I need to be with creative copy pasting and reading other peoples post. But i’ve been working on this specific piece of code for more then 14 hours now and I still can’t get it to do what I want!

So the idea is very basic, the script should query some info from the SQL database and dynamicly create some boxes as an output. The last output however (output 4) should output an url and redirect the user to this URL. The idea for this code is to create a product finder with links to the desired product.

However I tried using the ‘header’ PHP function to redirect the user, but for some reason this doesn’t get executed, if it does something at all it will only work when I send it a non url like ‘test’. If I feed it ‘http://www.test.nl’ nothing happens at all. Then I tried outputting Javascript to redirect, but it seems if you insert Javascript into an already loaded page it doesn’t execute anymore.

The index.php code:

<?php include 'select_list.php'; ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Triple Select drop down list with Ajax</title>
<script src="ajax_select.js" type="text/javascript"></script>
</head>
<body>


<form action="" method="post">
Kies uw adapter : <?php echo $re_html; ?>
</form>

</body>
</html>

The select_list.php :
I’ve commented out ‘//’ some of my attempts with my findings…

<?php
// Multiple select lists - www.coursesweb.net/ajax/
if(!isset($_SESSION)) session_start();

// Here add your own data for connecting to MySQL database
$server = 'localhost';
$user = 'root';
$pass = '';
$dbase = 'budgetadapter_selector';

// Here add the name of the table and columns that will be used for select lists, in their order
// Add null for 'col_description' if you don`t want to display their data too
$table = 'adapters';
$ar_cols = array('Merk', 'Model', 'Type', 'Link');

$preid = 'slo_';        // a prefix used for element's ID, in which Ajax will add <select>
$col = $ar_cols[0];     // the variable used for the column that wil be selected
$re_html = '';          // will store the returned html code

// if there is data sent via POST, with index 'col' and 'wval'
if(isset($_POST['col']) && isset($_POST['wval'])) {
  // set the $col that will be selected and the value for WHERE (delete tags and external spaces in $_POST)
  $col = trim(strip_tags($_POST['col']));
  $wval = "'".trim(strip_tags($_POST['wval']))."'";
}

$key = array_search($col, $ar_cols);            // get the key associated with the value of $col in $ar_cols
$wcol = $key===0 ? $col : $ar_cols[$key-1];     // gets the column for the WHERE clause
$_SESSION['ar_cols'][$wcol] = isset($wval) ? $wval : $wcol;    // store in SESSION the column and its value for WHERE
  
// gets the next element in $ar_cols (needed in the onchange() function in <select> tag)
$last_key = count($ar_cols)-1;
$next_col = $key<$last_key ? $ar_cols[$key+1] : '';

$conn = new mysqli($server, $user, $pass, $dbase);     // connect to the MySQL database

if (mysqli_connect_errno()) { exit('Connect failed: '. mysqli_connect_error()); }     // check connection

// sets an array with data of the WHERE condition (column=value) for SELECT query
for($i=1; $i<=$key; $i++) {
  $ar_where[] = '`'.$ar_cols[$i-1].'`='.$_SESSION['ar_cols'][$ar_cols[$i-1]];
}

// define a string with the WHERE condition, and then the SELECT query
$where = isset($ar_where) ? ' WHERE '. implode($ar_where, ' AND ') : '';
$sql = "SELECT DISTINCT `$col` FROM `$table`".$where;

$result = $conn->query($sql);       // perform the query and store the result

// if the $result contains at least one row
if ($result->num_rows == 0 || $result->num_rows == 1 || $result->num_rows == 2) {
  // sets the "onchange" event, which is added in <select> tag
  $onchg = $next_col!==null ? " onchange=\"ajaxReq('$next_col', this.value);\"" : '';
//  $onchg = $next_col!==null ? " onchange=\"location.href='http://' + this.options[this.selectedIndex].value;\"" : '';

  // sets the select tag list (and the first <option>), if it's not the last column
 // if($col!=$ar_cols[$last_key]) $re_html = $col. ': <select name="'. $col. '"'. $onchg. '><option>Merk</option>';
  if($col==$ar_cols[0]) $re_html = '<select name="'. $col. '"'. $onchg. '><option>Kies uw Merk</option>';
  if($col==$ar_cols[1]) $re_html = '<select name="'. $col. '"'. $onchg. '><option>Kies uw Model</option>';
  if($col==$ar_cols[2]) $re_html = '<select name="'. $col. '"'. $onchg. '><option>Kies uw Type</option>';
  
 // if($col!=$ar_cols[$last_key]) { header("HTTP/1.0 302 Moved Temporarily"); header ("Location: test"); }

  while($row = $result->fetch_assoc()) {
    // if its the last column, reurns its data, else, adds data in OPTION tags
	// if($col==$ar_cols[$last_key]) $re_html .= '<br/><script type="text/javascript">window.location="'. $row[$col]. '"; </script>'; // this doesnt work because the JS doesnt execute?
	if($col==$ar_cols[$last_key]) $re_html .= $row[$col]; // print for debug reasons
	if($col==$ar_cols[$last_key]) { header ("Location: $row[$col]");  exit; }// doesn't work for unknown reason?
	
    else $re_html .= '<option value="'. $row[$col]. '">'. $row[$col]. '</option>'; 
  }

  if($col!=$ar_cols[$last_key]) $re_html .= '</select> ';        // ends the Select list
 // if($col==$ar_cols[$last_key]) { header("HTTP/1.0 302 Moved Temporarily"); header ("Location: test"); } 
}
else { $re_html = '0 results'; }

$conn->close();

// if the selected column, $col, is the first column in $ar_cols
if($col==$ar_cols[0]) {
  // adds html code with SPAN (or DIV for last item) where Ajax will add the select dropdown lists
  // with ID in each SPAN, according to the columns added in $ar_cols
  for($i=1; $i<count($ar_cols); $i++) {
    if($ar_cols[$i]===null) continue;
    if($i==$last_key) $re_html .= '<div id="'. $preid.$ar_cols[$i]. '"> </div>';
 else $re_html .= '</span></br><span id="'. $preid.$ar_cols[$i]. '"> </span>';
 
  }

  // adds the columns in JS (used in removeLists() to remove the next displayed lists when makes other selects)
  $re_html .= '<script type="text/javascript">var ar_cols = '.json_encode($ar_cols).'; var preid = "'. $preid. '";</script>';
}
else echo $re_html;
?>

And the javascript ajax_select.js

[code]// Multiple select lists - www.coursesweb.net/ajax/

// function used to remove the next lists already displayed when it chooses other options
function removeLists(colid) {
var z = 0;
// removes data in elements with the id stored in the “ar_cols” variable
// starting with the element with the id value passed in colid
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 = ‘’;
}
}

// create the XMLHttpRequest object, according browser
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;

if(window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } // for Forefox, IE7+, Opera, Safari
else if(window.ActiveXObject) { xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”); } // IE5 or 6

return xmlHttp;
}

// sends data to a php file, via POST, and displays the received answer
function ajaxReq(col, wval) {
removeLists(col); // removes the already next selects displayed

// if the value of wval is not ‘- - -’ and ‘’ (the first option)
if(wval!=’- - -’ && wval!=’’) {
var request = get_XmlHttp(); // call the function with the XMLHttpRequest instance
var php_file = ‘http://localhost/budgetadapter/modules/cyberselector/select_list.php’; // path and name of the php file

// create pairs index=value with data that must be sent to server
var  data_send = 'col='+col+'&wval='+wval;

request.open("POST", php_file, true);			// set the request

document.getElementById(preid+col).innerHTML = 'Loading...';   // display a loading notification

// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data_send);	      	// calls the send() method with data_send

// Check request status
// If the response is received completely, will be added into the tag with id value of "col"
request.onreadystatechange = function() {
  if (request.readyState==4) {
    document.getElementById(preid+col).innerHTML = request.responseText;
  }
}

}
}
[/code]

I am out of ideas and I cannot find a generic answer on any forum. If any of you guys has a suggestion I would be really really grateful! I’ve attached a .zip file with all the scripts including my used SQL database (very tiny for testing).

Thanks a lot in advance everyone!!
Bosti

Hmmm, you have a lot of various types of code. HTML, PHP, Javascript, SQL and Ajax. Therefore, I can see how this is complicated…

First, you can NOT have multiple headers in a HTML page. SO, if you are viewing a page, you can not create a new header. So, changing a page by changing a header can only be done on a page without headers. Sooo, use a PHP file. Start the page with <?PHP and end it with the header relocation then ?>

In Javascript, there is a command which sort-of works. It sometimes causes errors if going cross-domain:
window.location = ‘http://www.newpagetogoto.com’;

Normally, in PHP, you use: header(“Location: newpagetogoto.php”); to reidirect to a new page.
The new page can be a URL, PHP, HTML, etc. You can even use arguments and pass options like this:
header(“Location: newpagetogoto.php?optionpassed1=‘something’”);

BUT, this code must be done on the SERVER-SIDE. I usually have a small PHP file used for redirection that is passed an address. One way is to add a secret value to each of the drop-down values. How I do this is in the SELECT creation area. When you create the drop-down, add a VALUE to it which will be the actual URL.
Then, when it is selected, send it to a PHP file that reads the VALUE of the drop-down and uses it in the header-redirect.

Lots of ideas here, hope it helps and does not confuse. Let us know if any of this solves it for you.

Hi Ernie,

Thanks for the reply. I understand most of your reply, I think :-). Eventually this script is going to be integrated into a module for Prestashop. I actually already did this (because I figured I would get it working in no time), but ofcourse the functionality is as bad.

Is there an alternative to using Ajax/JS by using 100% PHP/HTML/SQL? this would have my preference. I understand loading times will be a bit higher but the code will be simpler which would be good in my case.

What I would like is a PHP script that loads from 4 tables

  1. Brand
  2. Model
  3. Type
  4. Destination URL

And the thing should be CSS-able as well, which is (I found out) a big pain when using boxes.

I’ve already customized quite a bit in Prestashop in it’s PHP and all goes pretty smooth, but I severly underestimated this task… (It’s my own shop, so luckily I only have to report to myself)

If you could help me with a basic setup for something like this, that would be great.

Thanks,
Floor

I love the 100% HTML/PHP/MySQL/CSS version. Yes, you can do CSS with SELECT’s. It’s easier than you know at this point. I have never used Prestashop. It would take some time to review it good enough to alter it for your use. If you want I can look into it more (just downloaded it.) But, I will have to set it up, create a test site. I guess I am saying it will take some time.

First, lets get some simple questions out of the way. I assume you are planning on selling something when completed. Also, if you are selling something, why redirect to someone else;s site? You did mention you wanted to create a “Product Finder”. So, is your site going to sell something and locate products for others?
Why I am curious about more details on your project is that laying out the project early in the process makes it so very very much easier later on. To put products into a database is easy. To list them in a SELECT with CSS is easy. To redirect via PHP is easy. To do all this INSIDE someone else’s code can be hard to do.

So, send a little more info and we can set you up with some redirection code to fit your use. In the meantime, when you create a drop-down, you can do this in just a few lines and add a URL as the last one with very little code. Here is the code I use for drop-downs. It loads product names and adds a NEW-PRODUCT at the end. THis can be changed to handle URL’s. Or, you could add url’s to each dropdown. Depends on what you need.

PHP code:
[php]

<?php print "Select Product Name:"; // connect to your database, get products data $dbLinkID = mysql_connect( $hostname, $username, $password ); @mysql_select_db($dbname); $query="SELECT * FROM Products"; $dbResID = mysql_query ( $query, $dbLinkID); // loop through the results, creating an option list while( $row = mysql_fetch_row($dbResID) ) print "" . $row[1] . "\n"; //$row[1] is product name in DB print "Create New Product\n"; print ""; mysql_close($dbLinkID); ?>

[/php]

In the POST code when a user select a UPDATE or SUBMIT, then, the PHP code that is called can check for a new product selected in the option list. If selected, different code is processed. Fairly simple to do with forms and PHP. Use the CSS to make it “Pretty”. I’m don’t use CSS enough, but, I have someone else on this list that will help with that.

More after I understand your requirements better…

Hi Ernie,

Thanks again for your help! It is indeed tricky to integrate this product finder 100% into Prestashop. You would have to output a correct product ID instead of an URl to make a very neat. I believe prestashop has variables to link to CMS pages like ‘getPageLink’ and ‘cmsLink’. I know they work in the TPL files (Smarty templates) not sure how to use them inside the PHP file though.

You do not HAVE to use the TPL files for the modules though, again it is more conform to their philosophy, but then again, we are not making a module to be packages with presta :wink: And to go even further on this, you could even choose to use the product URL’s instead of the correct productid variable link. I understand that if your product link changes your database URLs break. But we only have about 25 products and they are easy searched & replaced for now.

So a simple product finder should do without paying to much attention to the Prestashop limitations. The finder is for searching the correct adapter for a product. People find it hard finding it by just using the Search box, so that is why i want to make this Block/Module to display where I need it.

Anything non prestashop specific would do I believe. If you do want more info on the specifics for prestashop modules, here is a link: www.ecartservice.net/17072009/writing-your-own-prestashop-module-part-1

Thanks again!
Floor

Perhaps I do not understand what you are asking help for. Is it for Prestashop or PHP? Please repost exactly what you are asking for. Your last note talked about your program but did not ask an actual question…

originally, I thought it was how to select a drop-down list for the product-finder and handle the results. Now, it sounds more like an add-in for Prestashp. Just not clear on what you are asking…

But, we are here, ask away…

Hi Ernie,

Sorry for the confusion, I am thinking out loud what I need to make instead of clearly vocalizing the question.

So my question is non Prestashop specific, it seems like I have a good grip on implementing it into Prestashop. My current goal is to create a 4 column selector that query’s mySQL in a PHP script outputting (X)HTML preferably without Javascript.

So the database structure is like this BRAND — MODEL – TYPE – OUTPUT-URL
I would need 3 pulldowns that would be fed data. So first pulldown fetches all the Brands without fetching the Models. Once Brand is fetched it needs to fetch the Models etc. Then when the Type is selected it should either directly Redirect you to this URL or create a GO button that will Submit your redirect.

I would prefer code that has not too many IF WHILE ELSE loops, because I find them a bit confusion when I adjust them, like a plain insert would be harder to make (for a noob). My ideal would be code for each Row seperatly, so execution code for Brand, for Model, type seperate. For me it would be easier to adjust that why, say I would need to add another column.

Thanks again for the help!
Floor

Floor,

Thanks for explaining… First, I can quickly think of two ways to do this.

The first is very simple, uses PHP and HTML only, but does refresh the page after each selection. This way is simple, you can do it, but really depends on the page that is doing the selections. If it is a fancy complicated display, you may not want it to refresh when a dropdown is selected.

The second is dynamic, the page does not refresh, but, this involves hidden frames and Javascipt to change the data on the screen.

Let’s look at the first way. The PHP that loads your first dropdown will be a DB query something like
“SELECT * FROM Brands”. This would load all of the entries in the brands table and placed into the dropdown. Since the other two dropdowns should not be available, they would both be DISABLED. This page would simply load the database info based on the forms dropdown values.
Once the first dropdown has been selected, the FORM on the page would refresh the page ENABLING the section dropdown. Same on the last dropdown. How is this done? Well, when the HTML FORM page is loaded, check the $_POST info and see if the first dropdown has data. If it does, then, it has been selected. If selected, then set this dropdown to the selected value and query the second dropdown with the data needed using the first dropdown’s value. And, same for the third. To update one after the other, simply post to your PHP file which create the page with the required data in place.
This problem doesn’t make sense when read. It is hard to describe the function and code of a page you are imagining. But, I think you get the idea. If you need some code as am example, I can work some up for you.

As far as the second sample goes… This would have all three dropdowns and all of the available data for each would have to be access somehow. Two ways to do this. First, you can use SERVER-SIDE-Javascipt which is tricky, but is becoming well used. The other is to simply create a hidden iFrame and load your PHP called page into that frame. Once in the hidden iFrame, you can access the data with Javascript’s DOM (easy) and move the data into the next dropdown. The pros for this way is that the page alters the dropdown’s dynamically so there is no refreshes going on. The cons are you have to do more programming and use more routines.

Soooo, there are a few ideas for you to start with. Hope this all helps… If you need some samples after you decide on which way to go, let us know…

Hi Ernie,

Thanks for being elaborate again :slight_smile:

First of my idea was to keep it simple, but on second thought the Java idea would be the tidiest way to do it I suppose. The first code I posted uses java and I’ve spend lot of time tweaking it. But the mix with Java confuses me because when things don’t work it’s harder to debug. Also inserting code dynamically has some disadvantage too. Like using java to redirect wont work because inserted java code doesn’t get evaluated by the browser. And also some company viewers might have Java disabled? Or is this uncommon nowadays?

Would it even be possible to switch to PHp when java is disabled? Going a bit off topic here :slight_smile:

Starting to think out loud again :slight_smile: lets do the simple PHP one! Call it version 1.0 when done. We can always make a 2.0 with Java later?

Another off topic question, my first posted code uses a session-start to create a cookie. Why is this necessary?

if you could help me setup the example code for the pHp only variant that would be great!

Thanks again, Floor.

Bosti/Floor,

I took another look at your original code. It is basically the second approach that I mentioned. What that cold does is dynamically call a page of PHP code that would return the data needed to reload the dropdowns.
It is basically all you need (with a little tweaking) to do the second version of what I discussed.
Later today I will copy it to my server and see what we can do. This version, since it is basically in place already would be easier than switching back to just PHP. I have a job to do at the moment and will respond with some code for you to try in a couple or few hours…
Talk to you more then…

Hi Ernie!

I am attaching the latest code, it shows my attempts as well, commented out. and I also have coments where I have issues… If you could evaluate this code and point out whats wrong, I would be very grateful! So it does exactly what I want, creating a Go box with the link that sends you once pressed, but for some reason it does not insert the correct URL code (creating the redirect button). And then ofcourse some CSS issues to adress later :wink:

code for index.php
[php]

<?php include 'select_list.php'; ?>

<!doctype html>

Triple Select drop down list with Ajax Kies uw adapter : <?php echo $re_html; ?> [/php]

Code for select_list.php
[php]<?php
// Multiple select lists - www.coursesweb.net/ajax/
if(!isset($_SESSION)) session_start();

// Here add your own data for connecting to MySQL database
$server = ‘localhost’;
$user = ‘xxxxxxxxx’;
$pass = ‘xxxxxxxxx’;
$dbase = ‘xxxxxxxxx’;

// Here add the name of the table and columns that will be used for select lists, in their order
// Add null for ‘col_description’ if you don`t want to display their data too
$table = ‘adapters’;
$ar_cols = array(‘Merk’, ‘Model’, ‘Type’, ‘Link’);

$preid = ‘slo_’; // a prefix used for element’s ID, in which Ajax will add
$col = $ar_cols[0]; // the variable used for the column that wil be selected
$re_html = ‘’; // will store the returned html code

// if there is data sent via POST, with index ‘col’ and ‘wval’
if(isset($_POST[‘col’]) && isset($_POST[‘wval’])) {
// set the $col that will be selected and the value for WHERE (delete tags and external spaces in $_POST)
$col = trim(strip_tags($_POST[‘col’]));
$wval = “’”.trim(strip_tags($_POST[‘wval’]))."’";
}

$key = array_search($col, $ar_cols); // get the key associated with the value of $col in $ar_cols
$wcol = $key===0 ? $col : $ar_cols[$key-1]; // gets the column for the WHERE clause
$_SESSION[‘ar_cols’][$wcol] = isset($wval) ? $wval : $wcol; // store in SESSION the column and its value for WHERE

// gets the next element in $ar_cols (needed in the onchange() function in tag)
$last_key = count($ar_cols)-1;
$next_col = $key<$last_key ? $ar_cols[$key+1] : ‘’;

$conn = new mysqli($server, $user, $pass, $dbase); // connect to the MySQL database

if (mysqli_connect_errno()) { exit('Connect failed: '. mysqli_connect_error()); } // check connection

// sets an array with data of the WHERE condition (column=value) for SELECT query
for($i=1; $i<=$key; $i++) {
$ar_where[] = ‘'.$ar_cols[$i-1].'=’.$_SESSION[‘ar_cols’][$ar_cols[$i-1]];
}

// define a string with the WHERE condition, and then the SELECT query
$where = isset($ar_where) ? ’ WHERE '. implode($ar_where, ’ AND ') : ‘’;
$sql = "SELECT DISTINCT $col FROM $table".$where;

$result = $conn->query($sql); // perform the query and store the result

// if the $result contains at least one row
if ($result->num_rows == 0 || $result->num_rows == 1 || $result->num_rows == 2) {
// sets the “onchange” event, which is added in tag
$onchg = $next_col!==null ? " onchange=“ajaxReq(’$next_col’, this.value);”" : ‘’;
// $onchg = $next_col!==null ? " onchange=“location.href=‘http://’ + this.options[this.selectedIndex].value;”" : ‘’;

// sets the select tag list (and the first ), if it’s not the last column
// if($col!=$ar_cols[$last_key]) $re_html = $col. ‘: <select name="’. $col. ‘"’. $onchg. ‘>Merk’;
if($col==$ar_cols[0]) $re_html = ‘<select name="’. $col. ‘"’. $onchg. ‘>Kies uw Merk’;
if($col==$ar_cols[1]) $re_html = ‘<select name="’. $col. ‘"’. $onchg. ‘>Kies uw Model’;
if($col==$ar_cols[2]) $re_html = ‘<select name="’. $col. ‘"’. $onchg. ‘>Kies uw Type’;

// if($col!=$ar_cols[$last_key]) { header(“HTTP/1.0 302 Moved Temporarily”); header (“Location: test”); }

while($row = $result->fetch_assoc()) {
// if its the last column, reurns its data, else, adds data in OPTION tags
// if($col==$ar_cols[$last_key]) $re_html .= ‘
'; // this doesnt work because the JS doesnt execute?
// if($col==$ar_cols[$last_key]) $re_html .= $row[$col]; // print for debug reasons
if($col==$ar_cols[$last_key]) { $re_html .= ‘’; } // use normal html form for submit, but it doesnt show all code in the output??
// if($col==$ar_cols[$last_key]) { header (“Location: $row[$col]”); exit; }// doesn’t work for unknown reason?

else $re_html .= '<option value="'. $row[$col]. '">'. $row[$col]. '</option>'; 

}

if($col!=$ar_cols[$last_key]) $re_html .= ’ '; // ends the Select list
// if($col==$ar_cols[$last_key]) { header(“HTTP/1.0 302 Moved Temporarily”); header (“Location: test”); }
}
else { $re_html = ‘0 results’; }

$conn->close();

// if the selected column, $col, is the first column in $ar_cols
if($col==$ar_cols[0]) {
// adds html code with SPAN (or DIV for last item) where Ajax will add the select dropdown lists
// with ID in each SPAN, according to the columns added in $ar_cols
for($i=1; $i<count($ar_cols); $i++) {
if($ar_cols[$i]===null) continue;
if($i==$last_key) $re_html .= ’

';
else $re_html .= ’ ';

}

// adds the columns in JS (used in removeLists() to remove the next displayed lists when makes other selects)
$re_html .= ‘’;
}
else echo $re_html;
?>[/php]

The ajax_select.js javascript:

[code]// Multiple select lists - www.coursesweb.net/ajax/

// function used to remove the next lists already displayed when it chooses other options
function removeLists(colid) {
var z = 0;
// removes data in elements with the id stored in the “ar_cols” variable
// starting with the element with the id value passed in colid
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 = ‘’;
}
}

// create the XMLHttpRequest object, according browser
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;

if(window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } // for Forefox, IE7+, Opera, Safari
else if(window.ActiveXObject) { xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”); } // IE5 or 6

return xmlHttp;
}

// sends data to a php file, via POST, and displays the received answer
function ajaxReq(col, wval) {
removeLists(col); // removes the already next selects displayed

// if the value of wval is not ‘- - -’ and ‘’ (the first option)
if(wval!=’- - -’ && wval!=’’) {
var request = get_XmlHttp(); // call the function with the XMLHttpRequest instance
// var php_file = ‘select_list.php’; // path and name of the php file (if used in module)
var php_file = ‘select_list.php’; // path and name of the php file (if used as stand-alone)

// create pairs index=value with data that must be sent to server
var  data_send = 'col='+col+'&wval='+wval;

request.open("POST", php_file, true);			// set the request

document.getElementById(preid+col).innerHTML = 'Loading...';   // display a loading notification

// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data_send);	      	// calls the send() method with data_send

// Check request status
// If the response is received completely, will be added into the tag with id value of "col"
request.onreadystatechange = function() {
  if (request.readyState==4) {
    document.getElementById(preid+col).innerHTML = request.responseText;
  }
}

}
}[/code]

I am also expierencing another issue. The code ‘works’ locally on XAMP but when put on my server I get this error:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /public_html/cyberselector/index.php:3) in /public_html/cyberselector/select_list.php on line 3

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /public_html/cyberselector/index.php:3) in /public_html/cyberselector/select_list.php on line 3

Fatal error: Call to a member function fetch_assoc() on a non-object in /public_html/cyberselector/select_list.php on line 64

Thanks again for evaluating the code!
-Floor

I was looking at your code finally. I have a question. You mention at the top of your last post that the code was not working and sending you to the wrong url. Then, at the end of the post, you said it was working correctly when on XAMP and not online.

Is it working correctly on XAMP? If so, I will look at the online issue. If not, then I will look at the code for URL issues… I have three projects I am working on tonight, so don’t want to waste time checking code that works.

Let me know, Thanks…

Hi Ernie!

The code almost works. It goes wrong where it builds the for making the Go button. For some reason it doesn’t echo the full HTML that I am quoting in the PHP. So if that’s fixed the code should work for me locally on XAMP.

Second problem is when I upload the current code online. It doesn’t run at all. It gives me the session_start() error quoted in the previous post. Would it be possible to modify the code to not use seasion_start() at all? Or do I need to change a PHP setting on my online server.

Thanks! And good luck with your projects!
-Floor

Well, you MUST start a session if you are using $_SESSION variables. Not if you do not.
Since you use one session variable (ar-col), you will need to start the session on all PHP code, once per page.

BUT, Remove this line: if(!isset($_SESSION)) session_start();
and replace it with just this: session_start();

You do not have to test for it…

Lastly, your $re-html is created wrong.
Replace this part: ><input value=“Ga” type=“submit
with this part: ><input value=Ga type=submit
Not sure what the value=Ga means. If it is a hard coded value, then no double-quotes.
If it variable I did not see where it was declared. It is your quote/double-quotes. This is always an issue when you try to create a form line inside PHP. You are using quote as your outside parts and double-quotes inside for use in the form line. So, ’ blah"xyz” blah’ is good, ‘blah"xyz"blah"xyz’ is bad. wrong number of quotes/double-quotes. Hope that makes sense…

Hi Ernie,

“Ga” was indeed not a variable, just a text, it means GO in Dutch.

I tried removing all the unneeded “” from the $re_html variables but it actually outputs the same and still doesn’t echo the full string.

So it seems like it’s going wrong somewhere else… :frowning:

Thanks,
Floor

Anyone who could take a look at it, I am willing to pay a no-cure-no-pay fee for the finder of the problem. Paypal, or whatever. I really need to solve it.

Thanks.
-Floor

I have been looking at your project in depth. I have a working routine, but, I came across this site which explains a more formal version. It seems to work well. I think it will solve your project. If not, ask further questions, but, make note of this site if you use it so people can reference where you started from.

http://remysharp.com/2007/09/18/auto-populate-multiple-select-boxes/

Hope it helps…

Sponsor our Newsletter | Privacy Policy | Terms of Service