Skip to content

Instantly share code, notes, and snippets.

@dusta
Last active July 17, 2018 11:57
Show Gist options
  • Save dusta/1bb37215075c3dd62f687b224b00f19b to your computer and use it in GitHub Desktop.
Save dusta/1bb37215075c3dd62f687b224b00f19b to your computer and use it in GitHub Desktop.
Ajax data attributes
<script src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<div class="form" data-action="https://google.com" data-method="GET">
Query: <input type="text" name="q" value="test">
<button type="button" class="submit btn btn-success">Wyślij GET</button>
</div>
<div class="form" data-action="https://google.com" data-method="POST">
Query: <input type="text" name="q" value="test">
<input type="hidden" name="token" value="someToken">
<button type="button" class="submit btn btn-success">Wyślij POST</button>
</div>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
$("body").on('click', '.form .submit', function() {
const form = $(this).parents('.form'); // Bind Form target element
if(form.data('disable')){
return;
}else{
form.data('disable', true);
}
let action = form.data('action'); // Attribute data-action
let method = form.data('method'); // Attribute data-method
let query = form.find('[name="q"]').val(); // search element
let tmp = form.find('.submit').html(); // Current text element
form.find('.submit').html('Wait ...'); // Replace after click
switch (method) {
case 'GET':
$.ajax({
url: action,
method: 'GET',
data: {
q: query,
},
success: function(response){
if (response.code == "200") {
console.log('ok');
} else {
console.log('error');
}
},
error: function(respone){
console.log('error');
}
}).always(function() {
form.find('.submit').html(tmp);
form.removeData('disable');
});
break;
case 'POST':
$.ajax({
url: action,
method: 'POST',
data: {
q: query,
token: form.find('[name="token"]').val()
},
success: function(response){
if (response.code == "200") {
console.log('ok');
} else {
console.log('error');
}
},
error: function(respone){
console.log('error');
}
}).always(function() {
form.find('.submit').html(tmp);
form.removeData('disable');
});
break;
default:
console.log('Method not allowed');
break;
};
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment