I have the following code that is performing the following functions:
- The PHP section reads the CSV file and converts its data into an
array.
- The table is constructed using HTML and PHP loops to display
the CSV data.
- Each row in the table has an “Import Risk” button and a
“Refresh” button.
- The “Import Risk” button triggers an AJAX request to the ajax-import.php file, sending the JSON data associated with the row.
- The response from ajax-import.php is parsed, and if successful, the table row is updated with the risk information or error messages.
- The JSON data for each row is stored
as the data-json attribute of the “Import Risk” button.
- The “Refresh” button triggers an AJAX request to the refresh.php file, which
retrieves the latest data for the row. The table row is updated with
the refreshed data.
There is an issue that persists and can’t seem to get to the bottom of – the issue appears only after the “Import” button is clicked. The data-json is refreshed (when I click the “Refresh” button), but JSON being sent to ajax-import.php appears to be the initial version of that was sent when the import button was clicked.
The intended outcome is to be able to refresh the data-json anytime the “Refresh” button is clicked and that updated JSON is what should be sent to the ajax.import.php script for processing.
<!-- Start Table Content -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h2>CSV File Contents</h2>
<?php $csvtoarray_clean = sanitize_csv_file($file_path); ?>
<?php // Convert the CSV data to an array
$csvtoarray = array_map('str_getcsv', explode("n", $csvtoarray_clean));
?>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<?php foreach($csvtoarray[0] as $col): ?>
<th><?= htmlspecialchars($col) ?></th>
<?php endforeach; ?>
<th>JSON Output</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php for($i=1; $i<count($csvtoarray); $i++): ?>
<tr>
<td><?= $i; ?></td>
<?php foreach($csvtoarray[$i] as $cell): ?>
<td><?= htmlspecialchars($cell) ?></td>
<?php endforeach; ?>
<?php $json_data = processJson(json_encode(array_combine($csvtoarray[0], $csvtoarray[$i])),$file_ref); ?>
<td style="min-width: 550px;">
<code>
<?php echo removeEmptyValues($json_data);?>
<?php $validation_response = json_decode($json_data, true); ?>
</code>
</td>
<td class="response-col">
<?php if ($validation_response['status'] == 'error'): ?>
<strong>There are errors on this row of data:</strong>
<?php foreach ($validation_response['errors'] as $error): ?>
<li><?= htmlspecialchars($error) ?></li>
<button class="refresh-btn btn btn-secondary" data-row="<?= $i ?>" data-hash="<?= md5(serialize($csvtoarray[$i])) ?>">Refresh</button>
<?php endforeach; ?>
<?php else: ?>
<div class="alert alert-danger" role="alert" style="display: none;"></div>
<div class="btn-group" role="group" aria-label="Actions">
<button class="import-button btn btn-primary" data-row="<?= $i ?>" data-json="<?php echo htmlspecialchars(removeEmptyValues($json_data)) ?>">Import Risk</button>
<button class="refresh-btn btn btn-secondary" data-row="<?= $i ?>" data-hash="<?= md5(serialize($csvtoarray[$i])) ?>">Refresh</button>
</div>
<?php endif; ?>
</td>
</tr>
<?php endfor; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- End Table Contents -->
<script>
$(document).ready(function() {
// Handle import button click
$(document).on('click', '.import-button', function() {
var json_data = $(this).data('json');
var button = $(this);
var alert = button.closest('tr').find('.alert');
alert.hide();
$.ajax({
type: 'POST',
url: 'ajax-import.php?cache=' + new Date().getTime(), // Add cache-busting parameter to the URL
data: {
json_data: button.data('json'), // Fetch the latest data-json value from the button
cacheBuster: new Date().getTime() // Cache-busting parameter
},
beforeSend: function(xhr) {
xhr.setRequestHeader('Cache-Control', 'no-cache');
},
success: function(response) {
try {
var data = JSON.parse(response);
var risk_number = data.result.riskNumber;
var risk_url = data.result.riskURL;
var status = data.result.status;
var responseText = data.result.responseText;
var errorText = data.result.errorText;
if (risk_url !== undefined) {
button.closest('tr').find('.response-col').html('<a href="' + risk_url + '" class="btn btn-primary" target="_blank">' + risk_number + '</a>');
} else {
var alertContent = '<h4 class="alert-heading">' + responseText + '</h4>' + errorText;
alert.html(alertContent);
alert.show();
}
// Log the data being sent to the import script
console.log('Import Data:', button.data('json')); // Log the latest data-json value
// Refresh the data in the table row
updateDataAndDOM(button, response);
} catch (error) {
console.error('Error parsing JSON:', error);
}
},
error: function(xhr, status, error) {
var errorMessage = 'Error: ' + error;
alert.html(errorMessage);
alert.show();
button.text('Failed');
button.addClass('btn-danger');
}
});
});
// Function to update JSON data and DOM elements
function updateDataAndDOM(refreshButton, refreshedData) {
var row = refreshButton.data('row');
var refreshedRowData = JSON.parse(refreshedData);
var rowDataElements = refreshButton.closest('tr').find('td:not(.response-col)');
rowDataElements.each(function(index) {
var header = $(this).closest('table').find('th').eq(index).text();
var newData = refreshedRowData[header];
if (newData !== undefined) {
$(this).text(newData);
}
});
importButton = refreshButton.closest('tr').find('.import-button[data-row="' + row + '"]');
importButton.attr('data-json', refreshedData); // Update the data-json attribute
}
// Handle refresh button click
$(document).on('click', '.refresh-btn', function() {
var refreshButton = $(this);
var row = refreshButton.data('row');
var hash = refreshButton.data('hash');
$.ajax({
url: 'refresh.php',
data: {
row: row,
hash: hash,
csvFilePath: '<?php echo $file_path; ?>',
timestamp: new Date().getTime() // Append timestamp as a parameter
},
type: 'GET',
dataType: 'json',
success: function(response) {
if (response.status === 'refreshed') {
var refreshedData_raw = response.refreshed_data;
var refreshedData = JSON.stringify(refreshedData_raw);
console.log('Refreshed Data:', refreshedData_raw);
updateDataAndDOM(refreshButton, refreshedData);
} else {
console.log(response.message);
var emptyData = '{}';
updateDataAndDOM(refreshButton, emptyData);
}
},
error: function(xhr, status, error) {
console.log('Error: ' + error);
var emptyData = '{}';
updateDataAndDOM(refreshButton, emptyData);
}
});
});
});
</script>