Aditya Kumar
Aditya Kumar

Reputation: 793

Passing JS array to PHP page

i am capturing the value of changed fields via JS Event and capturing that data into temp1 array, say, if u change field name "name", then it will get the field name "id" and will store it into temp1. but the main problem is how can i pass this array to a php form processing page, where i can get the value of this temp1.

i tried using JSON but it's not helping me out.

the code which i tried was: $.post('/somepage.php', temp1); but it didnt work.

please help me out with this.

and i included jquery.js lib in the page.

  <script type="text/javascript">
  var temp1 = new Array();

  function onChangeTest(changeVal)
  {    
 //alert("Field u changed was: " + changeVal.id) 

 temp1.push(changeVal.id);

 tmsg = "Fields u changed so far are:"
 for(var i=0;i<temp1.length;i++)
 {
 //document.write("<b>temp1["+i+"] is </b>=>"+temp1[i]+"<br>");
 tmsg = tmsg + " " + temp1[i];
 }
 alert(tmsg);
 }
 //$.post('/somepage.php', temp1);
 </script>

Upvotes: 0

Views: 170

Answers (3)

Rahul
Rahul

Reputation: 26

The problem looks quite simple to me , try below code and let me know the outcome..

function onChangeTest(changeVal)
{
    //alert("Field u changed was: " + changeVal.id)
    var temp1 = new Array();
    temp1.push(changeVal);

    tmsg = "Fields u changed so far are:"
    for(var i=0;i<temp1.length;i++){
        //document.write("<b>temp1["+i+"] is </b>=>"+temp1[i]+"<br>");
        //tmsg = tmsg + " " + temp1[i];
        var newHidInp = document.createElement('input');
        newHidInp.type  = 'hidden';
        newHidInp.name  = 'outArray[]';
        newHidInp.value = temp1[i];
        document.frm.appendChild(newHidInp);
    }
    return false;
}

HTML:

 <form name="frm" action="" method="POST" >
  <tr>
<td><font color="red">*</font>Name:<input type="text" name="name" id="name" size="25" onkeyup="onChangeTest('name')" /></td>
<td><font color="red">*</font>Age<input type="text" name="age" id="age" size="25" onkeyup="onChangeTest('age')" />
<input type="submit" name="submit" value="SUBMIT">
</td>
</form>
 </body>
</html>

PHP:

<?php
print("<pre>");
print_r(array_unique($_POST['outArray']));

?> 

Upvotes: 1

Christoph Winkler
Christoph Winkler

Reputation: 6408

Change the way you store the changes. If you store the Field IDs as Object Keys (e.g. temp1["username"] = true) you can easily use $.post("/somepage.php", temp1) and read the values via $_POST["username"] etc. in PHP.

Upvotes: 0

Shadow Wizard
Shadow Wizard

Reputation: 66389

What you need is:

$.post("/somepage.php", { 'temp1[]': temp1 });

See here in the official documentation as well, there are examples with all kinds of data.

Upvotes: 1

Related Questions