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);
})
};
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
};
});
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
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);
})
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.