4

I have to pass Javascript array variable to PHP , so here php and javascript code both are in same page .

when i give console inside isset($_POST['kvcArray'])) -- > it is not printing . guess some problem with this . Can anyone help me in this

    body {
        color: #566787;
        background: #f5f5f5;
        font-family: 'Varela Round', sans-serif;
        font-size: 13px;
    }
    .table-wrapper {
            background: #fff;
            padding: 20px 25px;
            margin: 30px 0;
            border-radius:1px;
            box-shadow: 0 1px 1px rgba(0, 0, 0, 0.247);
    }
    .table-title {        
        padding-bottom: 15px;
        background: linear-gradient(40deg, #2096ff, #05ffa3) !important;
        color: #fff;
        padding: 16px 30px;
        margin: -20px -25px 10px;
        border-radius: 1px 1px 0 0;
        box-shadow: 0 1px 1px rgba(0, 0, 0, 0.247);
    }
    .table-title h2 {
        margin: 5px 0 0;
        font-size: 24px;
    }
    .table-title .btn-group {
        float: right;
    }
    .table-title .btn {
        color: #fff;
        float: right;
        font-size: 13px;
        border: none;
        min-width: 50px;
        border-radius: 1px;
        border: none;
        outline: none !important;
        margin-left: 10px;
        box-shadow: 0 1px 1px rgba(0, 0, 0, 0.247);
    }
    .table-title .btn i {
        float: left;
        font-size: 21px;
        margin-right: 5px;
    }
    .table-title .btn span {
        float: left;
        margin-top: 2px;
    }
    table.table tr th, table.table tr td {
        border-color: #e9e9e9;
        padding: 12px 15px;
        vertical-align: middle;
    }
    table.table tr th:first-child {
        width: 60px;
    }
    table.table tr th:last-child {
        width: 100px;
    }
    table.table-striped tbody tr:nth-of-type(odd) {
        background-color: #fcfcfc;
    }
    table.table-striped.table-hover tbody tr:hover {
        background: #f5f5f5;
    }
    table.table th i {
        font-size: 13px;
        margin: 0 5px;
        cursor: pointer;
    } 
    table.table td:last-child i {
        opacity: 0.9;
        font-size: 22px;
        margin: 0 5px;
    }
    table.table td a {
        font-weight: bold;
        color: #566787;
        display: inline-block;
        text-decoration: none;
        outline: none !important;
    }
    table.table td a:hover {
        color: #2196F3;
    }
    table.table td a.edit {
        color: #FFC107;
    }
    table.table td a.delete {
        color: #F44336;
    }
    table.table td i {
        font-size: 19px;
    }
    table.table .avatar {
        border-radius: 1px;
        vertical-align: middle;
        margin-right: 10px;
    }
    .pagination {
        float: right;
        margin: 0 0 5px;
    }
    .pagination li a {
        border: none;
        font-size: 13px;
        min-width: 30px;
        min-height: 30px;
        color: #999;
        margin: 0 2px;
        line-height: 30px;
        border-radius: 1px !important;
        text-align: center;
        padding: 0 6px;
    }
        .pagination li a:hover {
            color: #666;
        } 
        .pagination li.active a, .pagination li.active a.page-link {
            background: #03A9F4;
        }
        .pagination li.active a:hover {        
            background: #0397d6;
        }
    .pagination li.disabled i {
            color: #ccc;
        }
        .pagination li i {
            font-size: 16px;
            padding-top: 6px
        }
        .hint-text {
            float: left;
            margin-top: 10px;
            font-size: 13px;
        }    
    /* Custom checkbox */
    .custom-checkbox {
    position: relative;
    }
    .custom-checkbox input[type="checkbox"] {    
    opacity: 0;
    position: absolute;
    margin: 5px 0 0 3px;
    z-index: 9;
    }
    .custom-checkbox label:before{
    width: 18px;
    height: 18px;
    }
    .custom-checkbox label:before {
    content: '';
    margin-right: 10px;
    display: inline-block;
    vertical-align: text-top;
    background: white;
    border: 1px solid #bbb;
    border-radius: 1px;
    box-sizing: border-box;
    z-index: 2;
    }
    .custom-checkbox input[type="checkbox"]:checked + label:after {
    content: '';
    position: absolute;
    left: 6px;
    top: 3px;
    width: 6px;
    height: 11px;
    border: solid #000;
    border-width: 0 3px 3px 0;
    transform: inherit;
    z-index: 3;
    transform: rotateZ(45deg);
    }
    .custom-checkbox input[type="checkbox"]:checked + label:before {
    border-color: #03A9F4;
    background: #03A9F4;
    }
    .custom-checkbox input[type="checkbox"]:checked + label:after {
    border-color: #fff;
    }
    .custom-checkbox input[type="checkbox"]:disabled + label:before {
    color: #b8b8b8;
    cursor: auto;
    box-shadow: none;
    background: #ddd;
    }
    /* Modal styles */
    .modal .modal-dialog {
    max-width: 400px;
    }
    .modal .modal-header, .modal .modal-body, .modal .modal-footer {
    padding: 20px 30px;
    }
    .modal .modal-content {
    border-radius: 1px;
    }
    .modal .modal-footer {
    background: #ecf0f1;
    border-radius: 0 0 1px 1px;
    }
        .modal .modal-title {
            display: inline-block;
        }
    .modal .form-control {
    border-radius: 1px;
    box-shadow: none;
    border-color: #dddddd;
    }
    .modal textarea.form-control {
    resize: vertical;
    }
    .modal .btn {
    border-radius: 1px;
    min-width: 100px;
    } 
    .modal form label {
    font-weight: normal;
    } 
<script type="text/javascript">
$(document).ready(function(){
    // Activate tooltip
    $('[data-toggle="tooltip"]').tooltip();
    
    // Select/Deselect checkboxes
    var checkbox = $('table tbody input[type="checkbox"]');
    $("#selectAll").click(function(){
        if(this.checked){
            checkbox.each(function(){
            this.checked = true;                        
            });
        }else{
            checkbox.each(function(){
                this.checked = false;                        
            });
        } 
    });
    checkbox.click(function(){
        if(!this.checked){
            $("#selectAll").prop("checked", false);
        }
    });
});
</script>
</head>
<body>
    <div class="container">
        <div class="table-wrapper">
            <div class="table-title">
                <div class="row">
                    <div class="col-sm-6">
      <h2>Manage <b>Instances</b></h2>
     </div>
     <div class="col-sm-6">
      <a href="#addEmployeeModal" class="btn btn-success" data-toggle="modal"><i class="material-icons">&#xE147;</i> <span>Add New Employee</span></a>
      <!-- <button id="Delete" onclick="Deleteall();" class="btn btn-danger" data-toggle="modal"><i class="material-icons">&#xE872;</i> <span>DELETe Existing User</span></a>       -->
       <input type="submit" class="button1" name="insert" value="insert" /> 
    </div>
</div>
</div>
    <div align="center">
    <form method="post" id="theform">
     <button type="button" name="load_data" id="load_data" class="btn btn-info">Load Data</button>
     </form>
    </div>
    <br />
    <div id="employee_table">
    </div>
   </div>
  </div>

   <div id="addEmployeeModal" class="modal fade">
  <div class="modal-dialog">
   <div class="modal-content">
   <form method="POST" action="Index.php">  
     <div class="modal-header">      
      <h4 class="modal-title">Add Employee</h4>
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
     </div>
     <div class="modal-body">     
      <div class="form-group">
      <label>Customer Name</label>
       <input type="text" class="form-control"  name="CName" required>
      </div>
      <div class="form-group">
      <label>Environment</label>
       <input type="text" class="form-control" name="Environment" required>
      </div>
      <div class="form-group">
      <label>URL Value</label>
       <textarea class="form-control" name = "URLValue"required></textarea>
      </div>   
     <div class="modal-footer">
      <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
      <input type="submit" name="submit" class="btn btn-info" value="Insert">
     </div>
    </form>
   </div>
  </div>
 </div>
</div>

 </body>
<script type="text/javascript">
    $( document ).ready(function() {
        $( ".button1" ).click(function() {
            var val = [];
            $("input:checked").each(function (index,value) {
                    val[index] = this.value;
            });

            var myJSONText = JSON.stringify(val);
            $.ajax({
                data: {"myJSONText": myJSONText},
                type: 'POST',
                success: function(response) {
                    alert(response);
                }
            });
        });
    });
</script>

<?php
    if (isset($_POST['myJSONText'])) {
        echo "<script>console.log('Debug Objects' );</script>";
        echo "<pre>";
        var_dump(json_decode($_POST['kvcArray'], true));
        echo "</pre>";
        die();
    }
?>

 <?php   
  if(isset($_POST['submit'])){
       //index.php
            $file_open = fopen("FILES/employee.csv", "a");
            $no_rows = count(file("FILES/employee.csv"));
            if($no_rows > 1){
                $no_rows = ($no_rows - 1) + 1;
            }
            $form_data = array(
            'CustomerName'  => $_POST['CName'],
            'Environment'  =>  $_POST['Environment'],
            'URLValue'  =>  $_POST['URLValue']
            );

            fputcsv($file_open, $form_data);
    }

 ?>


</html>

<script>
$(document).ready(function(){
 $('#load_data').click(function(){
  $.ajax({
   url:"FILES/employee.csv",
   dataType:"text",
   success:function(data)
   {
    var employee_data = data.split(/\r?\n|\r/);
    var table_data = ' <table class="table table-striped table-hover"><thead> <tr><th><span class="custom-checkbox"><input type="checkbox" id="selectAll"><label for="selectAll"></label></span></th>';
    table_data += '<tr><th></th>';
    for(var count = 0; count<employee_data.length; count++)
    {
     var cell_data = employee_data[count].split(",");
    //  table_data += '<tr>';
     for(var cell_count=0; cell_count<cell_data.length; cell_count++)
     {
      if(count === 0)
      {
       table_data += '<th>'+cell_data[cell_count]+'</th>';
       if(cell_count == 4){
           table_data += '<th></th><th></th>';
       }
      }
      else
      {
          if(cell_count === 0 ){
            table_data +='<tr><td><span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox"'+count+'" name="options[]" value="'+count+'"><label for="checkbox1"></label></span></td>';
            table_data += '<td>'+cell_data[cell_count]+'</td>';
         }else{
             table_data += '<td>'+cell_data[cell_count]+'</td>';
          }
      }
     }
         table_data += '</tr>';
    }
    table_data += '</table>';
    $('#employee_table').html(table_data);
   }
  });
 });
 
});
</script>

So whole code is provided above , here adding instance works fine , but only problem is when i click on delete all the checkbox values selected should be passed to php , so that i can delete that particular row from csv file .

9
  • but in php am not able to fetch the array value . why? what does print_r shows? Commented Oct 28, 2020 at 14:20
  • it doesn't show anything , no error too @cojack Commented Oct 28, 2020 at 14:27
  • Does this answer your question? How to pass Javascript array to PHP file using AJAX? Commented Oct 28, 2020 at 14:28
  • This might help too stackoverflow.com/questions/2348152/… Commented Oct 28, 2020 at 14:29
  • @NiranjanaNeeranj try to print it without json_decode Commented Oct 28, 2020 at 14:32

1 Answer 1

1

Based on your edit couple of notes about your code: 1st - put all you javascript function in 1 place, lets say just before the closing body tag - like this:

<script>
    $(document).ready(function(){
      // all your function here ! in 1 place
    });
</script>
</body>
</html>

2nd - not so important but still, move all the php code at the top of your file:

<?php
  // all the php here
?>
<!DOCTYPE html>
<html>
<head>
...
...

As far as I understand you're making request to the same page where you form with check boxes is. So you can have something like this:

<?php
    if (isset($_POST['kvcArray'])) {
        echo "<pre>";
        echo "<b>".__FILE__."</b><br/>";
        var_dump(json_decode($_POST['kvcArray'], true));
        echo "</pre>";
        die();
    }
?>

<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox1" name="options[]" value="1"><label for="checkbox1"></label></span><br />
<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox2" name="options[]" value="2"><label for="checkbox2"></label></span><br />
<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox3" name="options[]" value="3"><label for="checkbox3"></label></span><br />
<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox4" name="options[]" value="4"><label for="checkbox4"></label></span><br />
<input type="submit" class="button" name="insert" value="insert" />

Note that I have edited your js code, the way you're constructing your array and also no need to use "url" inside ajax when posting to same page!

<script type="text/javascript">
    $( document ).ready(function() {
        $( ".button" ).click(function() {

            var val = [];
            $("input:checked").each(function (index,value) {
                    val[index] = this.value;
            });

            var myJSONText = JSON.stringify(val);
            $.ajax({
                data: {'kvcArray': myJSONText},
                url: 'index.php',
                type: 'POST',
                success: function(result) {
                    //alert("Success");
                }
            });
        });
    });
</script>

This code has been tested and works on 100%

7
  • Sorry but it didn't work for me in my code . is there any way i can pass the whole code Commented Oct 29, 2020 at 3:57
  • and i tried it alone without my code integrated in it . but neither it gives me error nor it is dumbing values , and when i give alert(data) inside success it shows me entire code in it Commented Oct 29, 2020 at 4:16
  • can you post your entire code then? All the code from index.php. Commented Oct 29, 2020 at 7:26
  • but it is not allowing me to post Commented Oct 29, 2020 at 7:30
  • What do you mean its not allowing you? Just edit your question and put all the code from the index.php file... Commented Oct 29, 2020 at 7:32

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.