Jump to content

passing php variable to javascript **SOLVED**


scottybwoy

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.