0

I am using the jQuery DataTables Select plugin to select multiple rows from a table and store their data inside an array. Then I am making an Ajax Request in order to pass the array to another php file. The problem is that I can not fetch the data from the request.

Since AJAX calls can transfer only text I converted the array to a JSON sting but I had no luck fetching the data.

my dataTable.php code

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.1/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.5.0/css/select.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/select/1.5.0/js/dataTables.select.min.js"></script>
<title>JQuery DataTable</title>
</head>
<body>
<table id="myTable" class="display">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
            <th>Column 4</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Case</td>
            <td>num</td>
            <td>is</td>
            <td>1</td>
        </tr>
        <tr>
            <td>Case</td>
            <td>num</td>
            <td>is</td>
            <td>2</td>
        </tr>
    </tbody>
  </table>
  <button id="process-button">Process Selected Rows</button>
<script>
$(document).ready(function() {
  var table = $('#myTable').DataTable({
    select: true
  });
  
  // This array will store the data of the selected rows
  var selectedRows = [];
  
  // When a row is selected, its data is added to the 'selectedRows' array
  table.on('select', function(e, dt, type, indexes) {
    var rowData = table.rows(indexes).data().toArray();
    selectedRows = selectedRows.concat(rowData);
    console.log(selectedRows);
  });
  
  // When a row is deselected, its data is removed from the 'selectedRows' array
  table.on('deselect', function(e, dt, type, indexes) {
    var rowData = table.rows(indexes).data().toArray();
    selectedRows = selectedRows.filter(function(r) {
      return rowData.indexOf(r) === -1;
    });
    console.log(selectedRows);
  });
  
  // This function sends the 'selectedRows' array to the 'process.php' script using an AJAX request
  function processRows() {
  // Convert the 'selectedRows' array to a JSON string
  var selectedRowsJSON = JSON.stringify(selectedRows);
  $.ajax({
    type: "POST",
    url: "process.php",
    dataType: 'text',
    data: { selectedRows: selectedRowsJSON },
    success: function() {
    // Redirect the user to the 'process.php' file
    window.location.href = 'process.php';
    }
  });
}

  $('#process-button').click(function() {
  processRows();
  });
  
});
  </script>  
</body>
</html>

My process.php file

<?php
// Check if the 'selectedRows' JSON string was received in the request
if (isset($_POST['selectedRows'])) {
  // Convert the 'selectedRows' JSON string into an array
  $selectedRows = json_decode($_POST['selectedRows'], true);

  // Do something with the 'selectedRows' array here
  foreach ($selectedRows as $row) {
    $column1 = $row[0];
    $column2 = $row[1];
    $column3 = $row[2];
    $column4 = $row[3];
    
    echo $column1;
    echo $column2;
    echo $column3;
    echo $column4;
  }
} else {
  // Handle the case where the 'selectedRows' array was not received
  echo 'Array not received.';
}
?>

(Updated - according to comment on Rohit K. answer) I used the same php code with the one you provided My refactored script looks like this

var selectedRowsJSON = JSON.stringify(selectedRows); 
$.ajax({ type: "POST", url: "process.php", data: { selectedRows: selectedRowsJSON }, success: function(response) { let data = JSON.parse(response); } }); 

In the console I am getting this error now ->

Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

1 Answer 1

1

Try this

<?php
if (isset($_POST['selectedRows'])) {
  $selectedRows = json_decode($_POST['selectedRows'], true);
  foreach ($selectedRows as $row) {
    return json_encode(
        array(
            "column1" => $row[0],
            "column2" => $row[1],
            "column3" => $row[2],
            "column4" => $row[3],
        )
    );
    break;
  }
} else {
  return json_encode(['message' => 'Array not received.']);
}
?>

This will return json encoded string back to ajax as response and and on ajax success try this

success: function(response) {
    let result = JSON.parse(response);
}

this will convert json string to object

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, I refactored my code based on your answer but I my code is still not working. I used the same php code with the one you provided My refactored script looks like this var selectedRowsJSON = JSON.stringify(selectedRows); $.ajax({ type: "POST", url: "process.php", data: { selectedRows: selectedRowsJSON }, success: function(response) { let data = JSON.parse(response); } }); In the console I am getting this error now -> Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.

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.