I'm working on my first HTML form that performs an AJAX HTTP POST using jQuery. When a user makes a change to an input text field and tabs out of the field it triggers the AJAX script which in turn calls a PHP script which performs a database update.
The AJAX call can be successful but the database update could be unsuccessful (e.g. database related error) - I would like to insert the result of the PHP script into an alert. I can echo out any errors in in my PHP script, but I'm not sure how to get that into the appropriate alert.
Here's my Javascript:
<script type="text/javascript">
$(document).ready(function() {
$("#storeManager").change(function(){
var storeManager = $("#storeManager").val();
$.post('editProject.php', { storeManager: storeManager, id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
$("#managerRow").addClass("success");
}).fail(function () {
// no data available in this context
$("#managerRow").addClass("danger");
$("#ajaxAlert").addClass("alert alert-danger");
});
});
});
</script>
Here's the HTML table that contains the input field that triggers the AJAX call:
<table class="table table-striped table-bordered table-hover">
<tbody>
<tr>
<td>Store</td>
<td>Acme Widgets Inc</td>
</tr>
<tr>
<td>Retailer</td>
<td>Acme Corp</td>
</tr>
<tr>
<td>Store ID</td>
<td>9876543</td>
</tr>
<tr>
<td>State</td>
<td>NSW</td>
</tr>
<tr class="" id="managerRow">
<td>Manager</td>
<td>
<input type="text" class="form-control" id="storeManager" name="storeManager" value="Peter Johns">
</td>
</tr>
<tr>
<td>Phone</td>
<td>9222 3456</td>
</tr>
</tbody>
</table>
<div class="" id="ajaxAlert" role="alert"></div>
What I would like to do is, if there is any error from the editProject.php script that it stores in a $error variable and can echo out, to then insert this into the ajaxAlert and add a class: alert:
<div class="alert alert-danger" id="ajaxAlert" role="alert">The error from the database update from the php script appears here</div>
I'm new to jQuery and AJAX and everything I've tried hasn't updated the alert with the new class and alert text and I can't seem to find a similar to example that demonstrates this.