How to carry an array value from javascript to php?
Explanation
The javascript array values can be passed to a php file using the following method
Step 1:
Let us consider we have a js array as
<script language=javascript>
scriptAr = new Array();
scriptAr[0] = "one";
scriptAr[1] = "two";
scriptAr[2] = "three";
<script>
Step 2:
Now we will create a hidden form field as follows
<form action="phpArrayTest.php" method=post name=test onSubmit=setValue()>
<input name=arv type=hidden>
<input type=submit>
</form>
Here what we have done is, when the submit is called we first do some work ("onSubmit=setValue()")
by using the onSubmit method. The onSubmit method will invoke setValue() function defined by us.
After that the action will take place and stringTokens.php will be called.
Step 3:
Here we define the setValue method. The method will convert the array periviously defined in to a string
and then set it to the hidden field.
<script language=javascript>
function setValue()
{
var arv = scriptAr.toString(); // This line converts js array to String
document.test.arv.value=arv; // This sets the string to the hidden form field.
}
</script>
Step 4:
In the php file the string will be split back into array.
A Note
Learn PHP programming language tutorial with simple and neat example. Hope you enjoy this free tutorial.
Do give us your valuable feedback and suggestions on this online tutorial. This is a Copyright Content.