I have a table that allows users to make a selection from a list of items:
<table class="table table-condensed table-striped table-bordered">
<thead>
<th scope="col">Code</th>
<th scope="col">Description</th>
<th class="text-center" scope="col">Select</th>
</thead>
<tbody>
<tr class="" id="PR7518">
<td>1234A</td>
<td>Option A</td>
<td class="text-center">
<button type="button" class="btn btn-success btn-sm">Select</button>
</td>
</tr>
<tr class="" id="PR7636">
<td>45678B</td>
<td>Option B</td>
<td class="text-center">
<button type="button" class="btn btn-success btn-sm">Select</button>
</td>
</tr>
<tr class="" id="PR9149">
<td>9988C</td>
<td>Option C</td>
<td class="text-center">
<button type="button" class="btn btn-success btn-sm">Select</button>
</td>
</tr>
<tr class="" id="PR9187">
<td>4455D</td>
<td>Option D</td>
<td class="text-center">
<button type="button" class="btn btn-success btn-sm">Select</button>
</td>
</tr>
</tbody>
</table>
When they click the Yes button it fires off an AJAX request to set a PHP session variable for the ID of the item they selected:
$productID = $_POST['itemID'];
$_SESSION['selectedItemID'] = $itemID;
When the user submits the form I do a test to ensure the $_SESSION['selectedItemID'] is not empty and if it's empty it displays an error message, e.g.:
if ($_SESSION['selectedItemID'] == '') {
// display error message
}
I would like to add some client site validation so that it displays an alert on the form page and prevents them from submitting the form if the user hasn't already made a selection.
Here's my script as it currently stands:
$(document).ready(function() {
$('button.btn-success').click(function() {
// Remove the classes from all of the TR elements
$(this).parents('table').find('tr').removeClass('success warning danger');
var itemID = $(this).closest('tr').attr('id');
console.log(itemID);
// Create a reference to $(this) here:
$this = $(this);
$.post('updateSelection.php', {
itemID: itemID,
selectionType: 'yes'
}, function(data) {
data = JSON.parse(data);
if (data.error) {
console.log(data);
console.log('something was wrong with the ajax request');
$this.closest('tr').addClass("warning");
//make alert visible
$("#alert_ajax_error").show();
return; // stop executing this function any further
} else {
console.log('update successful - success add class to table row');
$this.closest('tr').addClass("success");
$this.closest('tr').removeClass("danger");
//$(this).closest('tr').attr('class','success');
}
}).fail(function(xhr) {
console.log('ajax request failed');
// no data available in this context
$this.closest('tr').addClass("warning");
//make alert visible
$("#alert_ajax_error").show();
});
});
});
I'm not sure how I can link the submit button to check if there the PHP $_SESSION['selectedItemID'] session variable exists? Or if there is another way to achieve the same result?