Sunil Kumar P
Sunil Kumar P

Reputation: 113

Dynamically created form elements value not getting in $_POST in php

I have created some dynamic text boxes and values according to the no. of cart items selected by a user. The no. of cart items are stored in a cookie and I am trying to do the following:

1) Get the no. of cart items from the cookie named cartcounter
2) Create 'cartcounter' no of text boxes with name itemkey_skey where itemkey is the hash key of each items in user cart.
3) Submit the form
4) Get the keys of the selected items in php

Now I can create cartcounter, the number of text boxes with different values.

But the problem is that I can get only the first text box value in $_POST in PHP. I would like to get all the values of the dynamically created form elements.

Code:

$(document).ready(function() {
    if (getCookie("cartcounter") != 0) {
        $("#counter").val(getCookie("cartcounter"));
        for (var i = 1; i <= cartcounter; i++) {

            var ckey = getCookie(i + "_skey");
            var element = document.createElement("input");
            alert("Element=" + element);
            element.setAttribute("type", "text");
            element.setAttribute("value", ckey);
            element.setAttribute("name", "skey_" + ckey);
            var foo = document.getElementById("itmbox");
            foo.appendChild(element);
            $("#frm").submit();
        }
    }
    else {
        alert('Your cart is empty , please choose your product');
        window.location = "http://synergiadigital.com/restaurant2/orderFood.php/"
    }
});​

Upvotes: 1

Views: 855

Answers (1)

Sunil Kumar P
Sunil Kumar P

Reputation: 113

I have solved it. The problem was that I was calling the submit function inside the loop. I have solved it by doing:

$(document).ready(function() {
    if (getCookie("cartcounter") != 0) {
        $("#counter").val(getCookie("cartcounter"));
        for (var i = 1; i <= cartcounter; i++) {

            var ckey = getCookie(i + "_skey");
            var element = document.createElement("input");
            alert("Element=" + element);
            element.setAttribute("type", "text");
            element.setAttribute("value", ckey);
            element.setAttribute("name", "skey_" + ckey);
            var foo = document.getElementById("itmbox");
            foo.appendChild(element);

        }
        $("#frm").submit();
    }
    else {
        alert('Your cart is empty , please choose your product');
        window.location = "http://synergiadigital.com/restaurant2/orderFood.php/"
    }
});​

Upvotes: 1

Related Questions