Forum Moderators: coopster

Message Too Old, No Replies

PHP AJAX Variable Question

         

morc

6:37 pm on Feb 17, 2010 (gmt 0)

10+ Year Member



Hi,

Im not very experienced with PHP or AJAX but I am trying to create multiple dynamic dropdown boxes that take there values from a database and use the value selected as arguements for the query.

I've got it to work with two dropdowns. However when I add the third I start to have problems.

My problem is retaining the values of the files selected. I want to store them in variables so that they can easily be called for additonal queries.

Their are 2 files. One is local_dropdown.php which contains the javascript code and then there is state.php which contains more of the php.

this is local_dropdown.php

<?
echo "<form name=sel>\n";

echo "Type : <font id=type><select>\n";
echo "<option value=''>============</option> \n" ;
echo "</select></font>\n";

echo "Quality : <font id=quality><select>\n";
echo "<option value=''>=== none ===</option> \n" ;
echo "</select></font>\n";

echo "Count : <font id=count><select>\n";
echo "<option value=''>=== none ===</option> \n" ;
echo "</select></font>\n";
?>

<script language=Javascript>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};

function dochange(src, val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById(src).innerHTML=req.responseText; //retuen value
}
}
};
req.open("GET", "state.php?data="+src+"&val="+val); //make connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
}

window.onLoad=dochange('type', -1); // value in first dropdown
</script>


and this is state.php



<?

$data=$_GET['data'];
$val=$_GET['val'];
$vType = " ";
$vQuality = " ";

//set database
include("dbinfo.inc.php");
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

// first dropdown
switch($data){
case 'type':
echo "<select name='type' onChange=\"dochange('quality', this.value)\">\n";
echo "<option value=''>==== choose type ====</option>\n";
$result=mysql_db_query($database,"SELECT DISTINCT type FROM prod");
while(list($type)=mysql_fetch_array($result)){
echo "<option value=\"$type\" >$type</option> \n" ;
}
break;
// second dropdown
case 'quality':
echo "<select name='quality' onChange=\"dochange('count', this.value)\" >\n";
echo "<option value=''>====choose quality ====</option>\n";

$vType= $val;
$result=mysql_db_query($database,"SELECT DISTINCT quality FROM prod WHERE type='".$vType."'");
while(list($quality)=mysql_fetch_array($result)){
echo "<option value=\"$quality\" >$quality</option> \n" ;
}
break;
// third dropdown
case 'count':
echo "<select name='count' >\n";
echo "<option value=''>====choose count ====</option>\n";

$vQuality = $val;
$result=mysql_db_query($database,"SELECT DISTINCT count FROM prod WHERE type = '".$vType."' AND quality = '".$vQuality."'");

while(list($count)=mysql_fetch_array($result)){
echo "<option value=\"$count\" >$count</option> \n" ;
}
break;
}
echo "</select>\n";
?>



The issue im having is with the third dropdown. The query isn't returning anything because i don't believe the variables are retaining the values I want them to.

Can somebody please point me in the right direction? I dont know javascript and have a mild knowledge with php so i basicaly took and example i found on google and edited it. But I am now stuck.

THanks in advance any and all help is appreciated!

-Marc

Matthew1980

7:15 pm on Feb 17, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



HI there Morc,

Welcome to the forum ;-)

The switch that you are using only needs the braces to open and close:-



switch($data)
{
case "type":
//code here
break;

case "quality":
//code here
break;

case "count":
//code here
break;
}


And make sure that the opening <? always has the <?php there as short tags are not always turned on in most installations, and its good practice to use the full tags.

Other than that the only thing i can see is the word count as I think it could be a reserved word - I'm probably wrong though *Please correct me if I am wrong*

And as for the values not being populated, it looks like you will have to reassign it like you have in the case before, as for the count case, the var $vType isnt set ie: the case that has it assigned isnt active. Just my thoughts there.

Good luck,

MRb

morc

8:39 pm on Feb 17, 2010 (gmt 0)

10+ Year Member



Thanks for the welcome.

This code above works except for third dropdown box.

It hits the case(count) and goes through the code. The problem is the var $vType doesnt retain its value ( first dropbox value)

Im wondering if anyone see the solution to it. Ive read a mention of global variables and am wondering if this would work in my case and if so how?

Matthew1980

9:25 pm on Feb 17, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there Morc,

Global variables are used if you want to call a variable from within a function that's already declared somewhere else in the script, or is referenced though an include:-

function some_func()
{
//call var set from parent file
global $someVar;
//php will then search for a var with the name $someVar within the script, even checking files referenced in any include paths
}


Have you tried echoing the query to see exactly what gets set, also to see if there are any hidden errors being thrown, set the error_reporting(E_ALL); at the very top of the script, this will then reveal any errors to you.

On the database call, alter this:-

mysql_connect(localhost,$username,$password);

to:-

mysql_connect("localhost",$username,$password);


Also, on the end of your queries, add:-


$result=mysql_db_query($database,"SELECT DISTINCT type FROM prod")or die(mysql_error());


to see if there is anything wrong with the query being sent.


$result=mysql_db_query($database,"SELECT DISTINCT type FROM prod");
if($result){
while(list($type)=mysql_fetch_array($result)){
echo "<option value=\"$type\" >$type</option> \n" ;
}
}else{
echo "No results returned!";
exit;
}


Add the $result to an if clause to see if the query returns true, if it doesnt, then you will get "no results returned", if its true, the while loop will kick in an carry out what you were asking.

Other than that the only thing I advise is that the mysql_db_query(), as told on the php.net website is now depricated and they advise against using it as of PHP 5.3.0, so try:-


$conn = mysql_connect("host", "username","pass") or die(mysql_error());
mysql_select_db("db_name", $conn) or die(mysql_error());


Then, reference mysql_query("SELECT * FROM `whatever`", $conn) or die(mysql_error());

Have a play with that, I have more than likely I have missed something, hopefully not though! ;-p

Cheers,

MRb

morc

7:31 pm on Feb 19, 2010 (gmt 0)

10+ Year Member



hmm do you think it would be possible for me create a function that would allow me to retain the value of $vType and $vQuality so that i may call them at any time?

The problem Im having is that the variables dont keep their values for the next time the page state.php is called.

Matthew1980

4:53 pm on Feb 21, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there Morc,

The easiest way I should think would be to store them in a session or a cookie, then they would be accessible through out the script. Obviously though, the session would only be retrievable whilst the browser is open, so cookie would be best if the user should happen to close the browser, there are a few options to play with.

Cheers,

MRb

morc

5:36 pm on Feb 22, 2010 (gmt 0)

10+ Year Member



Hi Matt,

Thanks for the response, I wouldn't need the value to be contained after the browser closed so a session variable sounds like that might be what I need.

I put session_start(); at the top of state.php but it says that it cannot start session cookie because header was already sent? How do i place it in my code properly?

Matthew1980

6:11 pm on Feb 22, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there Morc,

Example:- (index.php) the very top thing to declare

<?php
//Session start
session_start();

//Set error reporting for dev use...
error_reporting(E_ALL);
....then the rest of your code


If you have:-

<html>
<head>
<title>My PHP script
</title>
</head>
<body>
<?php
session_start();
//this wont work as headers have been sent
?>
<p>My content</p>


But this would:-



<?php
//start session
session_start();
//Error reporting
error_reporting(E_ALL);

//this will as php is the first thing on the document
?>
<html>
<head>
<title>My PHP script
</title>
</head>
<body>
<p>My content</p>


Anyway, have a play around with the sessions, see what you come up with, and if your stuck with anything, there is always someone on this forum with an answer, even if it takes a while to get a response ;-p

Cheers,

MRb

morc

5:05 pm on Feb 23, 2010 (gmt 0)

10+ Year Member



Everytime and everywhere I put it, I get this error. Can someone look at my code from the first post and tell me where I should put it? Help with this would be GREATLY appreciated.



Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\Inetpub\vhosts\accofinance.com\httpdocs\testfinal\state.php:3) in C:\Inetpub\vhosts\accofinance.com\httpdocs\testfinal\state.php on line 4

Matthew1980

8:01 pm on Feb 23, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there morc,

The code that I posted before needs to be placed at the top of the main index.php file that is either the front of the site, or the index.php used in the admin if you have one, but the best place to put the code will be in the start of the main index.php file, then the whole domain will be under the session_start(); umbrella.. ie: all files, not selected ones..

It should be the first thing that the php parser finds in the index file when the user first access' the site.

Cheers,
MRb