Reputation: 1027
is it possible to send a value from button to Jquery AJAX with onclick function ? I have tried something like this code, but not working. There is nothing on console log.
html
<button type="button" class="hapus_krs" onclick="hapus_krs(this.value)" value="1">x</button>
<button type="button" class="hapus_krs" onclick="hapus_krs(this.value)" value="2">x</button>
<button type="button" class="hapus_krs" onclick="hapus_krs(this.value)" value="n">x</button>
script
function hapus_krs() {
var formData = {
'id_mhs': $(this).val()
};
$.ajax({
type: 'POST',
url: '<?=base_url()?>akademik/hapus_krs',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
})
};
Upvotes: 2
Views: 9893
Reputation: 3614
When you invoke the function with onclick="hapus_krs(this.value)"
, you are already passing the button value to the function as parameter:
function hapus_krs(value) {
var formData = {
'id_mhs': value
};
}
Unobtrusive JS version:
<button type="button" class="hapus_krs" value="1">x</button>
<button type="button" class="hapus_krs" value="2">x</button>
<button type="button" class="hapus_krs" value="n">x</button>
$('button.hapus_krs').click(function() {
var formData = {
'id_mhs': this.value // $(this).val() also works but it's unnecessary to invoke another jQuery call
};
});
Upvotes: 2
Reputation: 8542
You have to be careful when playing with this
. In your code, this
might not refer the the button that has been clicked.
In addition, you are passing a this.value
as a parameter and yet you are not using it. So your function should look like the following:
function hapus_krs(value) {
var formData = {
'id_mhs': value
};
$.ajax({
type: 'POST',
url: '<?=base_url()?>akademik/hapus_krs',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
})
};
Upvotes: 1
Reputation: 12181
Here you go with the solution https://jsfiddle.net/60qu6mev/
$('.hapus_krs').click(function(){
var formData = {
'id_mhs': $(this).attr('value')
};
console.log(formData);
$.ajax({
type: 'POST',
url: '<?=base_url()?>akademik/hapus_krs',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="hapus_krs" value="1">x</button>
<button type="button" class="hapus_krs" value="2">x</button>
<button type="button" class="hapus_krs" value="n">x</button>
I have removed the onclick from HTML, rather used a jQuery click event to handle ajax call & retrieve value from button
Upvotes: 2