-1

I have a form with 2 inputs as below. I am sending POST request through ajax

<input name="item_name[]" value="Monthly" id="i1"/>
<input name="item_name[]" value="Weekly"  id="i2" />

xmlhttp.open("POST","validation.php",true);
var params = "item_name="+document.getElementById('i1').value+"item_name="+document.getElementById('i2').value;
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);

When i submit the page in php, i am not able to read both values. The array shows only one character of the first value.

echo '1.'.$_POST['item_name'][0].' 2.'.$_POST['item_name'][1];

Output is : 1.M 2.o

Expected output is 1.Monthly 2.Weekly

Even , i tried printing $_POST['item_name'] , it shows Monthly only.

Chrome --> Developer Tools --> Gives proper output as well. I dont know where the problem is ?

enter image description here

logan
  • 7,946
  • 36
  • 114
  • 185

2 Answers2

2

Edit: (now with Ajax. I use JQuery here but the concept should stay similar)

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
    var myData = new Array();
    myData[0]="one";
    myData[1]="two";

    $.ajax({ 
        type: "POST",
        url: 'test2.php',
        data: {'data':myData},
        success: function(output) {
            //do something
            }
        }
    });
</script>

result in PHP (var_dump($_POST))

array(1) {
  ["data"]=>
  array(2) {
    [0]=>
    string(4) "one"
    [1]=>
    string(3) "two"
  }
}
newBee
  • 1,289
  • 1
  • 14
  • 31
  • I have added more details to my question. I am submitting the page through AJAX request – logan May 20 '14 at 19:53
  • Edited it. However i always use JQuery as it's ways easier this in my opinion. Hope this still helps. – newBee May 20 '14 at 20:05
  • If you see a snapshot given in question, it sends two values properly but PHP is not able to recognize it. – logan May 20 '14 at 20:10
  • If you var_dump $_POST and the values are not displayed correctly you have an error in your ajax-request/JS and not in PHP. So you might be searching at the wrong place. – newBee May 20 '14 at 20:13
  • var_dump $_POST only returns 1 record. the second one is not coming though the Chrome page tells it sent two of the values – logan May 20 '14 at 20:53
  • see my working answer – logan May 21 '14 at 12:20
1

Found answer myself.. Need to add [] symbol in the javascript code. Its working fine now..

var params = "item_name[]="+document.getElementById('i1').value+"item_name[]="+document.getElementById('i2').value;
logan
  • 7,946
  • 36
  • 114
  • 185