JSFiddle - React, Tailwind, and code Playground
by Trisox
HTML
<a href="#" class="ajaxThingy">ajaxThingy clicker</a><br/><br/>
<h3>Succes:</h3>
<div class="succes"> </div>
<br/>
<h3>Complete:</h3>
<div class="complete"> </div>
<br/>
<h3>Error:</h3>
<div class="error"> </div>
CSS
body{margin:10px;}
h3{font-weight:600;}
.error,.complete,.succes{
height:50px;
width:300px;
}
.error{
border:2px solid red;
}
.complete{
border:2px solid blue;
}
.succes{
border:2px solid green;
}
JavaScript
$.fn.ajaxThingy = function() {
this.unbind();
return this.each(function() {
var $this = $(this);
$this.on("click",function (e) {
if($this.data('request-pending')){
return;
}
$this.data('request-pending', true);
e.preventDefault();
$.ajax({
type:"POST",
url:'/echo/html/',
data:{ html: "<p>Text echoed back to request</p>"},
cache:false,
success:function (data) {
$(".succes").empty().append(data);
},
complete:function () {
$(".complete").empty().html("completed");
},
error: function (xhr, ajaxOptions, thrownError) {
if ( xhr.status == 404 ) {
$(".error").empty().html("rebind click");
$this.removeData('request-pending')
}
if ( xhr.status == 401 ) {
}
}
});
});
});
};
$('.ajaxThingy').ajaxThingy();