Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Pass PHP Array to JAVAscript

Posted on 2008-10-08
8
Medium Priority
?
1,592 Views
Last Modified: 2012-05-05
I need to pass the array key/value pair that was created in PHP over to a JAVASCRIPT array.  My purpose is much more complex than what I'm showing below, but getting this to work will allow me to build the more complex script.  Here is the simplified version of the code:

First, the php array

$dynamicArray = array("first" => "First Element", "second" => "Second Element", "third => "Third Element");

Now the Form where I pass the value of this array ($dynamicArray) as the second part of my onSubmit statement.

<form name="actionForm" onSubmit="return submitIt(this, <?=$dynamicArray?>)" action="actNow.php" method="post">
   <input type="submit" name="action" value="Start">
 </form>

Here is my JavaScript where I want to simply display the get the values of the array.

<SCRIPT LANGUAGE=Javascript type="text/javascript">
   <!-- Hide script from older browsersr

   function submitIt(p_form, arrayVals) {
     // this script simply displays the key and value in three separate alert boxes
   // I need help for how to get this array elements.  I assume it needs to be a loop of some type
      var firstKey = ???   this should be "first"
      var firstValue = ???  this should be "First Element"
      var secondKey = ???   this should be "second"
      var secondValue = ???  this should be "second Element"
      var thirdKey = ???   this should be "third"
      var thirdValue = ???  this should be "Third Element"

    alert ("The first element pair is: key = [" + firstKey + "] and value of [" +firstValue + "])
    alert ("The second element pair is: key = [" + secondKey + "] and value of [" + secondValue + "])
    alert ("The first element pair is: key = [" + thirdKey + "] and value of [" + thirdValue + "])

  }
 -->
</SCRIPT>

Bottom line is how do I do the loop in the JavaScript that creates a pair of the key and value.

0
Comment
Question by:Paul Konstanski
  • 4
  • 2
  • 2
8 Comments
 
LVL 3

Expert Comment

by:DerkArts
ID: 22667972
Try this

Not sure why you would want to do this, cuz its doensnt look very efficient

foreach($dynamicArray as $key=>$var){
echo "var ".$key."Key =".$key. ";";
echo "var ".$key."Value=".$var. ";";
}

Open in new window

0
 

Author Comment

by:Paul Konstanski
ID: 22668748
DerkArts has provided a way to display PHP variables.  That's not what I'm looking for.  I want to get the array into JAVASCRIPT and then have the array variables and their key appear in an alert box.  For simplicity, I'm opting to have it simply show as an alert...the actual application is MUCH MORE COMPLEX but I've simplified to get at the core of what I need.  The bottom line is I need a phpArray value parsed and available as a key/value pair within Javascript so I can manipulate/use it from within Javascript.
0
 
LVL 3

Assisted Solution

by:DerkArts
DerkArts earned 200 total points
ID: 22668804
Then you would need this script. Generating an object, or associative array is you like.

this would produce:
assocArray.first = 'FirstValue';

etc

you could now use: alert(assocArray.first); etc. is this what you meant?
echo "var assocArray = new Object;";
foreach($dynamicArray as $key=>$var){
echo "assocArray.".$key."='".$var. "';";
}

Open in new window

0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 3

Expert Comment

by:wktang83
ID: 22669830
0
 

Author Comment

by:Paul Konstanski
ID: 22672639
Okay, I'm giving it my best shot and here's what I'm getting.

in the php portion, my normal array plus one other variable:
$dynamicArray = array("first" => "First Element", "second" => "Second Element", "third => "Third Element");
$otherVar = "showOther";

Then in the JavaScript I have these two alert sections.  The first one works, but the second doesn't.  What do I need to do to get it to read one of the array values?

var otherVar = "<?php echo $otherVar; ?>";
alert ('the Language is [ ' + otherVar + '].')

var arr = "<?php echo $dynamicArray['first']; ?>";
alert ('the Array element is [ ' + arr + '].')



0
 
LVL 3

Accepted Solution

by:
wktang83 earned 300 total points
ID: 22673146
You cannot just assign the php array directly to the javascript variable.

Hopefully, the code snippet below will do what you want.
<?php
   $dynamicArray = array();
   $dynamicArray[] = "Test";
   $dynamicArray[] = "yes";
   $dynamicArray[] = "no";
?>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var arr = new Array();
<?php
for ($i = 0; $i < count($dynamicArray); $i++)
{
   echo 'arr[' . $i . '] = "' . $dynamicArray[$i] . '";';
}
?>
 
for (i = 0; i < arr.length; i++)
{
   alert(arr[i]);
}
</script>
</body>
</html>

Open in new window

0
 

Author Comment

by:Paul Konstanski
ID: 22673407
I just realized that part of the reason that one of my code snippet above didn't work is that I declared the array after I had called the code in a php include statment.  Once I rearranged the order the following worked as desired.  

var arr = "<?php echo $dynamicArray['first']; ?>";
alert ('the Array element is [ ' + arr + '].')

So this process of getting your input really helped.  Thanks.

0
 

Author Closing Comment

by:Paul Konstanski
ID: 31504171
Thanks for your patience in helping me with this.  My problem for why it I was having problems was because of the order being out of sequence.  
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

571 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question