Jump to content

Archived

This topic is now archived and is closed to further replies.

scottybwoy

passing php variable to javascript **SOLVED**

Recommended Posts

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 :
[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();

?>
[/code]
Where am I going wrong? Cheers

Share this post


Link to post
Share on other sites
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:

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

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:

[code]<?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)
?>[/code]

Regards
Huggie

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Yeah thats what I meant, do you know if Java Script can read the array or does it need the string?

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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 : [url=http://www.codeproject.com/jscript/jsactb.asp?df=100]http://www.codeproject.com/jscript/jsactb.asp?df=100[/url] 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) :
[code]
// 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);
[/code]

Thanks Huggie, your very helpfull

Share this post


Link to post
Share on other sites
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:

[code]
actb(document.getElementById('textbox_id'),customarray);
[/code]

Use this:
[code]
actb(document.getElementById('textbox_id'),arguments);
[/code]

Regards
Huggie

Share this post


Link to post
Share on other sites
If you can't get it to work, then can you attach the [url=http://www.codeproject.com/jscript/jsactb/actb.zip]complete source[/url] 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

Share this post


Link to post
Share on other sites
You can also look at using [url=http://www.json.org/]JSON[/url] to convert your array into something that Javascript can use.

Ken

Share this post


Link to post
Share on other sites
Hi Huggie, yeah I have already downloaded the source and added it like so :
[code]
//phpfreaks does not like this <script type="text/javascript/" language="javascript" src="actb.js">
[/code]
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 :
[code]
<input type='text' id='customer' onChange="actb(document.getElementById('customer'),customarray);">
[/code]
However I thaught that it would be something to do with this bit of code here :
[code]
customarray = <?= company_col() ?>;
[/code]
But I'm not really sure what to do with it.  The tutorial uses this :
[code]
customarray = new Array('apple','pear','mango','pineapple',
        'orange','banana','durian', 'jackfruit','etc');
[/code]
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

Share this post


Link to post
Share on other sites
Can you attach the zip file you got from the site link that you posted?

Regards
Huggie

Share this post


Link to post
Share on other sites
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 :
[code]
<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);

}
[/code]
The php :
[code]
<?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;
  }
?>
[/code]
And the html bit :
[code]
<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>
[/code]

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!

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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 ;)

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.