I have a select menu that, when a user makes a selection, it fires off an AJAX request to a PHP script to query a database and return a value that matches the selection and inserts this into an associated input field.
This is all working well, however I now need to cater for the possibility that an empty result might be returned (up until now a matching result was always returned). If that is the case it needs to delete the value from the associated input field/clear this input field.
Here's what a successful AJAX request returns (JSON data):
[{"senderMobile":"0412 345 678"}]
and here's what an empty result returns:
[{"senderMobile":""}]
Here's the AJAX code that calls the PHP script and updates the input field:
$(document).ready(function() {
$("#smsFromName").change(function() {
var smsFromName = $("#smsFromName").val();
console.log(smsFromName);
$.post('getSMSSender.php', {
senderName: smsFromName
}, function(data) {
data = JSON.parse(data);
if (data.error) {
alert("error");
$("#smsFrom").html('');
return; // stop executing this function any further
} else {
console.log(data[0].smsFrom);
$("#smsFrom").val(data[0].senderMobile);
}
}).fail(function(xhr) {
$("#smsFrom").html('');
});
});
});
I gather I need to update this section to include an option that if there is no data to simply clear out the #smsFrom input field:
} else {
console.log( data[0].smsFrom );
$("#smsFrom").val(data[0].senderMobile);
but I'm stumped at this point.
</div>