Forum Moderators: coopster

Message Too Old, No Replies

Accessing my PHP inside the Javascript

         

dainstructor

4:38 pm on Jan 31, 2007 (gmt 0)

10+ Year Member



I am having trouble accessing an array that I created im not sure what I'm doing incorrectly.

Here's the array:


$i=0;
do{
$arrayAssignments[$i] = " " .$row_getAssignment['empNo'] ."-" .$row_getAssignment['projectID'];
$i++;
}
while ($row_getAssignment = mysql_fetch_assoc($getAssignment));

I am then trying to access it later inside of javascript here:


for (i=0;i<=50;i++)
{
if(<?php $arrayAssignments[$i]?> == document.form3.empNo.value+"- "+document.form3.projectID.value )
{
alert('The resource you selected is already assigned to this project');
return false;
}
}

Does anyone know what I'm doing wrong?
Thanks guys

topr8

4:44 pm on Jan 31, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



is not php processed server side and then javascript processed client side, thus the javascript has no access to a php array.

cameraman

7:21 pm on Jan 31, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You could do it by echoing the php array inside the script tag to 'create' the javascript array. I don't know the javascript syntax so modify to suit:
<script type="text/javascript">
var assignments = array(<?php echo implode(',',$arrayAssignments);?>)
.
.

dainstructor

9:13 pm on Jan 31, 2007 (gmt 0)

10+ Year Member



Thanks for the advice cameraman but I'm have a bit of trouble following. If I create the javascript array with the aforementioned code, are the indexes the same? Meaning will it now contain the contents of the php array so that I can loop through and compare?

cameraman

10:54 pm on Jan 31, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes, unless javascript starts its arrays at 1.
The php code puts a line in the document sent to the browser something like this:
var assignments = array(17,13,26,65)

So basically it's like you getting the output and typing it in by hand. That would work for numerics but strings aren't much more difficult.
I just looked in my big javascript book and it's talking about declaring an array using a "streamlined syntax" that looks like this:
aryvbl = ["apple","grape","blueberry"]

You can make php mimic that with implode. If you have a php array that functionally has the content above:
$arystring = implode('","',$aryvbl);
gets you this:
$arystring = apple","grape","blueberry
That's really close to what you want, but you need some quotes on the ends as well as the brackets:
$arystring = '["' . implode('","',$aryvbl) . '"]';

Now
$arystring = ["apple","grape","blueberry"]

and make it part of the document:
echo 'var arystring=' . $arystring;

Then in the other part of your javascript, you'll use
if(arystring[i] == document.form3.empNo.value+"- "+document.form3.projectID.value )