...

View Full Version : Use javascript variable to increment php array



sirsaula
07-18-2012, 10:15 PM
I am in need of incrementing through a php array with the javascript variable "i" instead of where i have 0 in the $members array call


var i = 0;
while (i<5)
{
if (<?php echo json_encode($members[0]['department']); ?> == "CHE"){
contacts.push({"NAME":"Sir Saula","TITLE":"John","CONTACT":"bab","RESEARCH":"Ph.D."});
}
i++;

}

WolfShade
07-18-2012, 10:24 PM
How about looping in PHP (inside <script type="text/javascript"> tags) instead of JavaScript, and include JS code as needed?

Then, again.. this is not tested, but..



if (<?php echo json_encode($members[?>i<?php]['department']); ?> == "CHE"){

Old Pedant
07-18-2012, 10:24 PM
You can't.

PHP code can *NOT* see any JavaScript variables. Period.

The only ways to send a javascript variable (or any client-side value) to PHP are:
-- post a <form>
-- use a querystring with a php URL
-- use AJAX

DrDOS
07-19-2012, 12:47 AM
The only way you can really do that is to have php rewrite the array in javascript, and then let javascript use it. The best way to do that is have javascript declare an array and then write code for php to use javascript 'push' to add elements to the array, because it prevents confusion in the case of mixed data types.
myarray =[];
loop over this;
{
echo 'myarray.push('.$data[i].');';
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum