2

I have html form that allowed to insert multiple input. I am able to insert only first input. How to insert multiple value in php passing through ajax, My HTML form is as below.

<tr>
    <th>ID</th>
    <td><input type="number" id="navid"></td>
</tr>
<tr>
    <th>Menu IN</th>
    <td><input type="text" name="menuin"></input></td>
</tr>
<tr>
    <th>Menu ENG</th>
    <td><input type="text" name="menueng"></input>
    </td>
</tr>

User can add input field dynamically(dynamic add has be done by jquery) enter image description here It is not problem to pass if only one input group. But I want to pass multiple input if user add more than one.

And I've passed value as

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

I've inserted input values passed by ajax as below

if (isset($_POST["navid"]) && !empty($_POST["navid"])) {
        $query1 =$con->prepare("INSERT INTO menu(cid, title, en_title) VALUES (:navid, :menuin, :menueng)");
        $query1->bindParam(':menuin',$_POST["menuin"]);
        $query1->bindParam(':menueng',$_POST["menueng"]);
        $query1->bindParam(':navid', $_POST["navid"]);
        $query1->execute();
        $msg1 = 'Menu has inserted';    
    }

Now I want to insert multiple values. How to do ?

Dipak
  • 931
  • 14
  • 33
  • This `$("input[name='menuin']").val();` will only fetch the first input that it finds and not all. That is why you only get one value for your input. I would suggest you serialize your form instead and send everything to PHP. – hungrykoala May 16 '18 at 05:08
  • The same principle applies to your `#navid`. What is it that you're tying to achieve here? So that we can format our answer better and so that we can help you. – hungrykoala May 16 '18 at 05:10
  • You can't have multiple elements with the same ID. Doing so makes your HTML invalid and this must be fixed to guarantee it works correctly. Also if you want to have multiple form elements with the same name attribute you can use an array, like ``. – Mike May 16 '18 at 05:12
  • @hungrykoala, Thanks for your response. Please see edited question – Dipak May 16 '18 at 05:20
  • @Mike. I had tried it but I can't pass array variable to php through ajax. Please see edited question – Dipak May 16 '18 at 05:24
  • @Mike apparently you can have multiple inputs with the same name. PHP will just treat them as an array. According [here](https://stackoverflow.com/questions/2906793/is-it-valid-to-have-two-input-elements-with-the-same-name) – hungrykoala May 16 '18 at 05:29
  • @hungrykoala No, you can't have multiple inputs with the same name in the same form. One will overwrite the other one. I just tested it. – Mike May 16 '18 at 05:38
  • @Mike it seems that post is outdated then. I've always used an array name if I need multiple inputs. – hungrykoala May 16 '18 at 05:39
  • @hungrykoala Actually that post is not outdated. If you have multiple inputs with the same name, they **will** be submitted to the server exactly like that, however PHP will only use the last value. It's not your browser that does that, but PHP. It is possible that other server-side languages will parse it differently, but that's how PHP works. I'm sure this would be available as-is in [php://input](http://php.net/manual/en/wrappers.php.php#wrappers.php.input). – Mike May 16 '18 at 05:46
  • @Mike thank you for that. I assumed they talk about PHP in the accepted answer. – hungrykoala May 16 '18 at 05:48
  • 1
    @hungrykoala Actually according to [this answer](https://stackoverflow.com/a/452088/811240) it looks like using array form names is more of a PHP invention, and most other server-side languages will provide a collection of values if there are multiple elements with the same name. – Mike May 16 '18 at 05:52

2 Answers2

3

You have to apply array in input field for multiple input element. And pass array through ajax and insert to database using foreach loop.

HTML

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

Ajax

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

PHP

foreach ($_POST["navid"] AS $key => $item){               
    $query1 =$con->prepare("INSERT INTO menu(cid, title, en_title) VALUES (:navid, :menuin, :menueng)");
    $query1->bindParam(':menuin',$_POST["menuin"][$key]);
    $query1->bindParam(':menueng',$_POST["menueng"][$key]);
    $query1->bindParam(':navid',$item);
    $query1->execute();
    $msg1 = 'Menu has inserted';     
}    
Dipak
  • 931
  • 14
  • 33
  • What a great answer... kudos to you. This problem had ruined my day. Now it works. Once again thanks. – Dipak May 16 '18 at 10:16
1

HTML:

<form id="the_form">
<tr>
    <th>ID</th>
    <td><input type="number" name="navid[]" id="navid"></td>
</tr>
<tr>
    <th>Menu IN</th>
    <td><input type="text" name="menuin[]"></input></td>
</tr>
<tr>
    <th>Menu ENG</th>
    <td><input type="text" name="menueng[]"></input>
    </td>
</tr>
<input type="submit" value="Submit Form" id="submit"/>
</form>

I added a name for your ID so that it will be included when you submit the form, I just added a form tag since it was not present in your question.

JS:

  Read about serialize 
  (https://stackoverflow.com/questions/15173965/serializing-and-submitting-a-form-with-jquery-post-and-php)


$("#submit").click(function(){
    var form_data = $("#the_form").serialize();
    $.ajax({
        url: 'insert_nav.php',
        type: 'post',
        data: {form_data:form_data},
        success: function(data){
            alert(data);
            $('#nav')[0].reset();
        }
    });
});

PHP //Since the submitted data is now a collection of an array you'll have to loop through it to save them in the database as you cannot save an array directly in a DB.

if (!empty($_POST["navid"])) {
    for($counter = 0; $counter < sizeof($_POST["navid"]); $counter++){
        $query1 =$con->prepare("INSERT INTO menu(cid, title, en_title) VALUES (:navid, :menuin, :menueng)");
        $query1->bindParam(':menuin',$_POST["menuin"][$counter]);
        $query1->bindParam(':menueng',$_POST["menueng"][$counter]);
        $query1->bindParam(':navid', $_POST["navid"][$counter]);
        $query1->execute();
        $msg1 = 'Menu has inserted'; 
    }    
 }
hungrykoala
  • 1,083
  • 1
  • 13
  • 28
  • @hugrykoala your assistance in this matter is greatly appreciated. still it doesn't work. i am wondering whats wrong with me. ajax only return blank message and data can't be inserted. – Dipak May 16 '18 at 06:02