简体   繁体   中英

How to send data multiple same name input using ajax and php

I am trying to make a poll system for my project like facebook. But I need help in a matter. I use the following JavaScript code to increase the answers for inputs.

$("body").on("click",".createnew", function(){
      $(".inputsl").append("<div class='inputt'><input type='text' name='myanswer' id='createmyanswer' class='myinput' placeholder='Write answer!'></div>");
   });

When you click on the CreateNew button users can prompted to write a new answer. Like this:

<div class="inputsl">
   <div class="inputt"><input type="text" id="createmyanswer" name="myanswer" class="myinput"></div>
   <div class="inputt"><input type="text" id="createmyanswer" name="myanswer" class="myinput"></div>
   <div class="inputt"><input type="text" id="createmyanswer" name="myanswer" class="myinput"></div>
   <div class="inputt"><input type="text" id="createmyanswer" name="myanswer" class="myinput"></div>
</div>

So you can see all input name and id is same. It is easy to send one input value. But I want to give the user the right to ask more than one question.

For this I used the following ajax code.

$("body").on("click",".insertp", function(){
       var answers = $("#createmyanswer").val();
       var dataPollAnswers = 'answers=' + answers;
       $.ajax({
           type:'POST',
           url:'/requests/postPollAnswers',
           data: dataPollAnswers,
           cache: false,
           beforeSend: function(){},
           sucess: function(){
               console.log("Success!");
           }   
        });
     });

The last think is php codes for postPollAnswers. I have used the following php codes for sending all created answers.

<?php 
include_once '../inc/inc.php';
if(isset($_POST['answers'])){
    $answers = mysqli_real_escape_string($db, $_POST['answers']);
    if($answers){
foreach($answers as  $setAnswer){
      $insertAnswersfromData = $InSert->Insert_Poll($uid, $setAnswer);
    }
    }
}
?>

I think i have array problem i have searched a solution and tryed many thinks but i can not send multiple answers. I have checked also maybe i need some jquery code like serialize() ect. and tryed but i can not get any result.

Also i am getting this warning:

Warning: Invalid argument supplied for foreach()

Anyone can help me here please ?

Just change selector to class name and use serialize

dataPollAnswers = $('.myinput').serialize(); 

Note : id should be unique

Update 1:

PHP :

foreach($_POST['myanswer'] as $row)
 {             ^^^^^^^^^^
    echo $row;
 } 

Note : Input name is myanswer not answer

Update 2:

PHP

    <?php 
    include_once '../inc/inc.php';
    if(isset($_POST['myanswer'])){

            foreach($_POST['myanswer'] as  $setAnswer)
            {
              if(!empty($setAnswer))
              {
              $new_set_ans = mysqli_real_escape_string($db, $setAnswer);
              $insertAnswersfromData = $InSert->Insert_Poll($uid, $new_set_ans);
               }
            }
    }
    ?>

just take name attribute as array and their id's should be unique:

 var i;

$("body").on("click",".createnew", function(){
      $(".inputsl").append("<div class='inputt'><input type='text' name='myanswer[]' id='createmyanswer'"+i+" class='myinput' placeholder='Write answer!'></div>");
     i++;//no needed if you dont want to use id attribute
   });

Then post as usual using name attribute and you will get array at server side .

Thanks

Here is working demo for you:

 $("#submit").click(function(){ var paramsToSend = {}; var i = 1; $("input[name='myanswer[]']").each(function(){ paramsToSend[i] = $(this).val(); i++; }); $("#dataToSend").html(JSON.stringify(paramsToSend)); $.ajax({ type: "POST", url: 'URL_HERE', data: {params:JSON.stringify(paramsToSend)}, success: function(data) { console.log("SUCCESS!!!"); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="inputsl"> <div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div> <div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div> <div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div> <div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div> </div> <button id="submit"> Submit </button> <div id="dataToSend"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM