I need some help. I'm going use AJAX (for the first time) and I'd like you to tell me whether the way I am going to show you is optimal.
Let's say that I have a select element.
<select class="update-db" data-id="25" data-original-value="2">
<option value="1">Yellow</option>
<option value="2" selected="selected">Red</option>
<option value="3">Blue</option>
</select>
So here is what I do:
$(document).on('change', 'select.update-db', function() {
// Get needed data
var select = $(this);
var id = select.attr('data-id');
var originalValue = select.attr('data-original-value');
var newValue = select.val();
// Perform the request
$.ajax({
method: 'POST',
url: 'update-db.php',
data: { id: id, 'original-value': originalValue, 'new-value': newValue }
});
// Then, if everything is okay, change the "original value" of the select element
// so that we can perform the updating operation again without having to refresh the page
.done(function() {
select.attr('data-original-value', newValue);
});
});
Then, on the other side, a PHP script validates everything and updates the database.
Is this the correct way of using AJAX? I feel it's not. What am I doing wrong?