Jump to content


Photo

passing php variable to javascript **SOLVED**


  • Please log in to reply
19 replies to this topic

#1 scottybwoy

scottybwoy
  • Members
  • PipPipPip
  • Advanced Member
  • 532 posts
  • LocationUK

Posted 12 October 2006 - 09:16 AM

Hi ppl,

I'm trying to get a script to return an array ready for Ajax to pick it up, but at the mo it's not filling in an array at all, think it's got something to do with my foreach func.  Here's the code :
<?php
   	function company_col()
   	{
   		$sql = "SELECT company FROM customers";
    	$result = mssql_query($sql) or die("SQL Error selecting customers");

    	while ($row = mssql_fetch_row($result))
    	{
        	$companies = array();
        	foreach ($row as $value)
        	{
            	$companies[] = '"'.addslashes($value).'"';
        	}

	        $companies[] = "\t[".implode(",", $row)."]";
    	}

    	echo "$companies";
   }

company_col();

?>
Where am I going wrong? Cheers

#2 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 12 October 2006 - 10:52 AM

You're selecting one column from a table, so what exactly do you want in the array, the company keyed on a numeric index, so the equivilent of:

<?php
$companies = array('Apple', 'Dell', 'Mesh', 'Microsoft');
echo $companies[2]; // echos Mesh
?>

Or do you want to company as the key, if so, what do you want as the value?

It looks as though what you're trying to do is get all the companies into an array and then output them as a single string seperated by commas, is this correct?

If the above is correct then this isn't really a situation for foreach...

Try this:

<?php
function company_col(){
   $sql = "SELECT company FROM customers";
   $result = mssql_query($sql) or die("SQL Error selecting customers");
   $companies = array();
   while ($row = mssql_fetch_row($result)){
      $companies[] = '"'.addslashes($row['company']).'"';
   }
   $companylist = "\t[".implode(",", $row)."]";
   echo "$companylist";
}
company_col();

// Will return "     [Apple,Dell,Mesh,Microsoft]" (without the double quotes)
?>

Regards
Huggie
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#3 scottybwoy

scottybwoy
  • Members
  • PipPipPip
  • Advanced Member
  • 532 posts
  • LocationUK

Posted 12 October 2006 - 11:26 AM

Yeah, thats great, cheers.  I realised that I did not need the for each so wrote it again similar to what you have done.

What I am trying to do is create an array that is ready for javascript to come and collect in an AJAX fashion.  Do you know how javascript can read data for an array?  Am I on the right track, cheers for your help huggie

#4 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 12 October 2006 - 11:32 AM

I'm afraid that I've never done much with JavaScript and I've only created a few simple applications with AJAX.

You're not passing an array to JavaScript though, you're passing it a string.  If you wanted to pass it an array you could do away with the implode() function and just return $companies.

Regards
Huggie
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#5 scottybwoy

scottybwoy
  • Members
  • PipPipPip
  • Advanced Member
  • 532 posts
  • LocationUK

Posted 12 October 2006 - 11:55 AM

Yeah thats what I meant, do you know if Java Script can read the array or does it need the string?

#6 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 12 October 2006 - 11:57 AM

I guess it's possible... Maybe give us a bigger overview of what you're doing and we'll see if we can come up with something without re-inventing the wheel.

Regards
Huggie


Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#7 scottybwoy

scottybwoy
  • Members
  • PipPipPip
  • Advanced Member
  • 532 posts
  • LocationUK

Posted 12 October 2006 - 01:30 PM

Right OK, well we have the php working so I won't bother posting that again.
I have a text field and a submit, when a user starts entering details it will bring up a dropdown list to select the company name to bring up the details. like in the example here : http://www.codeproje...actb.asp?df=100 but the array used in this is predefined so I wanted it to dynamically retrieve the data to be used form the database for the list.  So I think we are halfway there.  Here's my code so far (it's a bit messy and won't work yet, cos I was sorting out the php first) :
//	Browser Support code
	function ajaxFunction()
	{
		var ajaxRequest;  // The variable that makes Ajax possible!

		try {
			// Opera 8.0+, Firefox, Safari
			ajaxRequest = new XMLHttpRequest();
		} catch (e){
			// Internet Explorer Browsers
			try {
				ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e){
					// Something went wrong
					alert("Your browser broke!");
					return false;
				}
			}
		}

		// Create a function that will receive data sent from the server
		ajaxRequest.onreadystatechange = function(){
			if(ajaxRequest.readyState == 4){
				var ajaxDisplay = document.getElementById('ajaxDiv');
				ajaxDisplay.innerHTML = ajaxRequest.responseText;
				customarray = <?= company_col($dataset) ?>;  //need to put something else here
			}
		}

		var customer = document.getElementById('customer').value;
		var queryString = "?customer=" + customer;
		ajaxRequest.open("GET", "ajaxCust.php" + queryString, true);
		ajaxRequest.send(null); 

	}

		actb(document.getElementById('customer'),ajaxDisplay);

Thanks Huggie, your very helpfull

#8 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 12 October 2006 - 01:57 PM

You need to use the arguments property...

Go back to using the implode() function with commas, so your list looks something like this:
[pre]Apple, Dell, Mesh, Microsoft[/pre]Then within your javascript function, use the arguments property.  So where they have the code looking like this:

actb(document.getElementById('textbox_id'),customarray);

Use this:
actb(document.getElementById('textbox_id'),arguments);

Regards
Huggie
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#9 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 12 October 2006 - 02:11 PM

If you can't get it to work, then can you attach the complete source as I'm assuming you're a member of the site, and I'll take a look, I think I know how to solve it.

Regards
Huggie


Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#10 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 12 October 2006 - 02:51 PM

You can also look at using JSON to convert your array into something that Javascript can use.

Ken

#11 scottybwoy

scottybwoy
  • Members
  • PipPipPip
  • Advanced Member
  • 532 posts
  • LocationUK

Posted 12 October 2006 - 03:31 PM

Hi Huggie, yeah I have already downloaded the source and added it like so :
//phpfreaks does not like this <script type="text/javascript/" language="javascript" src="actb.js">
I was a little unclear on where to put the widget so I put it in both the script section and under the text field, like so :
<input type='text' id='customer' onChange="actb(document.getElementById('customer'),customarray);">
However I thaught that it would be something to do with this bit of code here :
customarray = <?= company_col() ?>;
But I'm not really sure what to do with it.  The tutorial uses this :
customarray = new Array('apple','pear','mango','pineapple', 
         'orange','banana','durian', 'jackfruit','etc');
And I think some of my other code posted befor doesn't need to be in there now it's a bit messy, Thanks for your time

#12 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 12 October 2006 - 03:47 PM

Can you attach the zip file you got from the site link that you posted?

Regards
Huggie
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#13 scottybwoy

scottybwoy
  • Members
  • PipPipPip
  • Advanced Member
  • 532 posts
  • LocationUK

Posted 12 October 2006 - 03:59 PM

http://www.codeproje...jsactb/actb.zip

#14 scottybwoy

scottybwoy
  • Members
  • PipPipPip
  • Advanced Member
  • 532 posts
  • LocationUK

Posted 13 October 2006 - 11:11 AM

OK, here's where I have go upto, just not sure on how to include my php file think it's set up to read the string to put into the javascript array.  Here's the java :
<src=common.js + actb.js/> // Provided by the tutorial site
//	Browser Support code
	function ajaxFunction()
	{
		var ajaxRequest;  // The variable that makes Ajax possible!

		try {
			// Opera 8.0+, Firefox, Safari
			ajaxRequest = new XMLHttpRequest();
		} catch (e){
			// Internet Explorer Browsers
			try {
				ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e){
					// Something went wrong
					alert("Your browser broke!");
					return false;
				}
			}
		}

		// Create a function that will receive data sent from the server
		ajaxRequest.onreadystatechange = custLookup(v,custArray){
			if(ajaxRequest.readyState == 4){
				var custArray = new Array(ajaxRequest.responseText);
			}
		}

		ajaxRequest.open("GET", "ajaxCust.php", true);
		ajaxRequest.send(null); 

	}
The php :
<?php

   	function company_col()
   	{
   		$sql = "SELECT company FROM customers";
    	$result = mssql_query($sql) or die("SQL Error selecting customers");
    	$companies = array();
    	while ($row = mssql_fetch_assoc($result)){
      		$companies[] = '"'.addslashes($row['company']).'"';
   		}

	    $companylist = implode(",", $companies);
    	return $companylist;
   }
?>
And the html bit :
	<form name="headmenu" method="POST">
		<input type='text' id='customer' backspace='false'>
	//	<cript> phpfreaks doesn't like scripts
			var obj = actb(document.getElementById('customer'),custArray);
		</cript>
        </form>

It's still not working so i think it's the way the file is included, or maybe I shouldn't use return for the php, i tried echo -> no joy.  Any suggestions?  It should work like google suggest!

#15 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 13 October 2006 - 12:12 PM

You provided the link to the .zip file, but as already stated, I'm not a member at codeproject.com

If you provide me with the zip file that you downloaded from that site, I'll set it up.

Regards
Huggie
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#16 scottybwoy

scottybwoy
  • Members
  • PipPipPip
  • Advanced Member
  • 532 posts
  • LocationUK

Posted 13 October 2006 - 12:38 PM

Sorry huggie, here it is : http://www.mri.co.uk/bin/actb.zip

#17 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 13 October 2006 - 01:16 PM

Perfect, I'll take a look at this a little later.  A brief look would indicate that it's not going to be too difficult.

Regards
Huggie
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#18 scottybwoy

scottybwoy
  • Members
  • PipPipPip
  • Advanced Member
  • 532 posts
  • LocationUK

Posted 17 October 2006 - 10:57 AM

Yo Huggie did u work it out?

#19 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 17 October 2006 - 11:01 AM

Sorry, got bogged down with my own project at the minute :(

I'll take a look soon though, I've done something similar before, so it shouldn't be too hard to adapt the code.

Huggie
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#20 scottybwoy

scottybwoy
  • Members
  • PipPipPip
  • Advanced Member
  • 532 posts
  • LocationUK

Posted 23 October 2006 - 01:38 PM

Got it working using this tutorial here [link]http://www.dhtmlgoodies.com/index.html?whichScript=ajax-dynamic-list[/link] I think it may take a little longer to load than the other and doesn't look as good, but that can all be tweaked ;)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users