jQuery Ajax Error Handling
by b_long
HTML
<script src="https://bioconductor.org/js/jquery.js"></script>
<br/>
<button id="goodButton">Do success</button>
<button id="badButton">Do error</button>
<br/><br/>
<p>
Click a button above to initiate. <br/> Ajax output will be displayed below:
</p>
<br/>
<pre id="output" style="background-color: lightblue;"></pre>
JavaScript
// jQuery 2.2.0 : https://code.jquery.com/jquery-2.2.0.min.js
// jQuery 1.6.4 : https://bioconductor.org/js/jquery.js
$(document).ready(function() {
output = $("#output");
function doAjax(service) {
var myData = {
json: JSON.stringify({
text: "This is test data",
currentTime: new Date()
})
};
output.empty();
return $.ajax({
type: 'POST',
data: myData,
dataType: 'jsonp',
url: service,
success: function(data) {
output.append('Ajax result: \n' + JSON.stringify(data, null, 4) + '');
},
error: function(jqXHR, textStatus, errorThrown) {
output.append("An error occurred performing search. The server returned : " + JSON.stringify(errorThrown));
}
});
}
var badArg = '&q=foo:bar%20id:*\/release\/bioc\/htm0',
goodArg = '&q=rsamtools%20id:*\/release\/bioc\/htm0',
biocSearchUrl= '//master.bioconductor.org/solr/default/select?indent=on&version=2.2&rows=20&fl=id,score,title&qt=standard&wt=json&explainOther=&hl=on&hl.fl=&hl.fragsize=200'
$("#goodButton").click(function() {
doAjax(biocSearchUrl + goodArg)
});
$("#badButton").click(function() {
doAjax(biocSearchUrl + badArg)
});
});