0

I'm trying to insert array value in php passing through ajax, but I am not succeeding. I think the problem is in ajax while sending array variable. My HTML form is as below.

<tr>
    <th>ID</th>
    <td><input type="number" id="navid"></td>
</tr>
<tr>
    <th>Menu NPL</th>
    <td><input type="text" name="menunpl[]"></input></td>
</tr>
<tr>
    <th>Menu ENG</th>
    <td><input type="text" name="menueng[]"></input>
    </td>
</tr>

And I've passed value as

$("#submit").click(function(){
    var navid = $("#navid").val();
    var menunpl = $("input[name='menunpl[]']" ).val()
    var menueng = $("input[name='menueng[]']" ).val()
    $.ajax({
        url: 'insert_nav.php',
        type: 'post',
        data: {navid:navid,menunpl:menunpl,menueng:menueng},
        success: function(data){
            alert(data);
            $('#nav')[0].reset();
        }
    });
});

But In serverside, it says Invalid argument supplied for foreach()

if (isset($_POST["navid"]) && !empty($_POST["navid"])) {
    foreach ($_POST['menunpl'] AS $key => $item){
        $query1 =$con->prepare("INSERT INTO menu(cid, title, en_title) VALUES (:navid, :menunpl, :menueng)");
        $query1->bindParam(':menunpl',$item);
        $query1->bindParam(':menueng',$_POST["menueng"][$key]);
        $query1->bindParam(':navid', $_POST["navid"]);
        $query1->execute();
        $msg1 = 'Menu has inserted';    
    }
}
6
  • Can you foreach over a string in PHP? I'm fairly certain from what you have shown that $_POST['menunpl'] would be a string. Commented May 16, 2018 at 3:32
  • Yes you can foreach a string to enumerate caracters.why array menunpl, is there many <input text menunpl> ? Commented May 16, 2018 at 8:36
  • @EricV. yes <input text menunpl> can be added by user. Commented May 16, 2018 at 8:55
  • 1
    I think the problem is the way you get the value from javascript : look at this stackoverflow.com/a/24503913/2332589 Commented May 16, 2018 at 9:56
  • 1
    @AnandHmt, your error is in ajax. In this way you can't pass array variable. Change var menunpl = $("input[name='menunpl[]']" ).val() to var menunpl = []; $('input[name="menunpl[]"]').each( function() {menunpl.push(this.value);}); and other variable as this. This should work. And do not forget to add array to id in html and ajax. Commented May 16, 2018 at 10:09

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.