-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

2
  • Works fine, are you sure they are spelled the same and have the [] ? Commented May 20, 2014 at 19:51
  • @AbraCadaver : I have added more details to my question. I am submitting the page through AJAX request. Commented May 20, 2014 at 19:53

2 Answers 2

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"
  }
}
Sign up to request clarification or add additional context in comments.

6 Comments

I have added more details to my question. I am submitting the page through AJAX request
Edited it. However i always use JQuery as it's ways easier this in my opinion. Hope this still helps.
If you see a snapshot given in question, it sends two values properly but PHP is not able to recognize it.
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.
var_dump $_POST only returns 1 record. the second one is not coming though the Chrome page tells it sent two of the values
|
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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.