0

How to save an all value of multi-select when it was along with file via formdata. It always show file "Invalid arguments for foreach()". Even thought the file has been save into respective folder but the multi-select options didn't come into foreach and save into database.

Warning: Invalid arguments supplied in foreach()

The following codes I am using.

HTML

<!--JQUERY-->
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
    <!--Bootstrap 3.3.7-->
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <!--Font-awesome 4.7.0-->
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<button class="btn btn-success addnewjob" data-toggle="modal" data-target="#add_new_record_modal">Add New Job</button>


<!-- Modal - Add New Record/User -->
<div class="modal fade bs-example-modal-lg" id="add_new_record_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Add New Record</h4>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
            <select name="test[]" id="sbTwo" multiple="multiple" class="form-control">
              <option value="PAPER CUP">PAPER CUP</option>
              <option value="PAPER BOWL">PAPER BOWL</option>
              <option value="PAPER PLATE">PAPER PLATE</option>
              <option value="PAPER BAG">PAPER BAG</option>
            </select>
          </div>

          <div class="col-xs-12 col-sm-12 col-md-3 col-lg-3">
            <label for="jspec_filedoc">DOC Files</label>
            <div class="input-group">
              <label class="input-group-btn">
                <span class="btn btn-info">
                                                        <span class="fa fa-file-image-o"></span>
                <input id="jspec_filedoc" name="jspec_filedoc" type="file" accept=".doc, .docx,.xlsx" style="display: none;" multiple>
                </span>
              </label>
              <input type="text" class="form-control" id="existingaifile" placeholder="Document File" readonly>
            </div>
          </div>

        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary" onclick="addRecord()">Add Record</button>
        </div>
      </div>
    </div>
  </div>
  <!-- // Modal -->

SCRIPT

function addRecord() {

  var conf = confirm("Are you sure, do you really want to APPROVE this file?");
  if (conf == true) {
    // get values

    $('#sbTwo option').prop('selected', true); //select all data in multiselect
    var test = $("#sbTwo").val();
    var pj_schednum = $('#pj_schednum').val();
    var jspec_filedoc = $('#jspec_filedoc').prop('files')[0];

    var form_data = new FormData();
    form_data.append('jspec_filedoc', jspec_filedoc);
    form_data.append('pj_schednum', pj_schednum);
    alert(form_data.append('test', test));

    $.ajax({
      url: 'ajax/createjob.php',
      dataType: 'text',
      cache: false,
      contentType: false,
      processData: false,
      data: form_data,
      type: 'POST',
      success: function(data) {
        alert(data);
      }
    });
  }
}

$(document).ready(function() {
  $(function() {

    $(document).on('change', ':file', function() {
      var input = $(this),
        numFiles = input.get(0).files ? input.get(0).files.length : 1,
        label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
      input.trigger('fileselect', [numFiles, label]);
    });

    $(document).ready(function() {
      $(':file').on('fileselect', function(event, numFiles, label) {
        var input = $(this).parents('.input-group').find(':text'),
          log = numFiles > 1 ? numFiles + ' files selected' : label;

        if (input.length) {
          input.val(log);
        } else {
          if (log) alert(log);
        }
      });
    });
  });
});

PHP

<?php
    if(isset($_POST['pj_schednum']) && isset($_POST['test']) && isset($_FILES['jspec_filedoc']))
    {
        // include Database connection file 
        include("db_connection.php");

        //get current date with 24 hours time format
        date_default_timezone_set('Asia/Manila');
        $a = date('m/d/Y H:i:s'); 
        $b = date('m/d/Y h:i A', strtotime($a));
        $z = date('mdYHis');    

        // get values 
        $file_name3 = explode(".", $_FILES['jspec_filedoc']['name']); 
        $new_name3 = rand() . '.'. $file_name3[1];  
        $sourcePath3 = $_FILES["jspec_filedoc"]["tmp_name"];
        $savethisname3='JT'.$z.$new_name3;        
        $targetPath3 = "../bin/jobs_attachments/docfile/".$savethisname3;  
        move_uploaded_file($sourcePath3, $targetPath3);  


        $i = 0;
        foreach ($_POST['test'] as $operation_processname){  
            echo $operation_processname."\n";

            $operation_step=$i++;//The steps

            $query = "INSERT INTO operation (o_name, o_step, o_doc, o_added) VALUES('$operation_processname', '$operation_step','$savethisname','$b')";
            if (!$result = mysqli_query($db, $query)) {
                exit(mysqli_error());
            }
        }

        echo "1 Record Added!";
    }
?> 

RESULT

+-----------------------------------+
+o_name| o_step| o_doc| o_added     |
+-----------------------------------+
|PAPER CUP |0 |doc1.docx | 01/11/2017 05:16:45 PM|
|PAPER BOWL|0 |doc2.docx | 01/12/2017 05:16:45 PM|
|PAPER PLATE|0 |doc3.docx | 01/13/2017 05:16:45 PM|
|PAPER BAG|0 |doc4.docx | 01/14/2017 05:16:45 PM|
+------------------------------------------------+
17
  • can you show your $_POST dump data here ? Commented Aug 22, 2017 at 7:40
  • your jQuery version? Commented Aug 22, 2017 at 7:45
  • @MuhammadAkberKhan I'm getting all options value of multiselect but it didn't pass though the foreach. I got exact data when I echo the $_POST['test']; I am using jquery-1.12.3.min.js. Commented Aug 22, 2017 at 7:46
  • just want to check $_POST index, there may be some space in key? like $_POST['test '], share this test index we can sort it out Commented Aug 22, 2017 at 7:48
  • 1
    @Ailyn show us how echo print the $_POST['test'] Commented Aug 22, 2017 at 9:14

1 Answer 1

1

You send your data by getting likevar test = $("#sbTwo").val(); .So when you access from php ,it will access as a string eg item1,item2 .So try explode first before you loop .

$test = explode(",",$_POST['test']);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks works fine. It totally explode the array data and convert into array. Then save, the same with my expected results.

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.