I have this jQuery script in an external file. Im using it to update a database. I've been practicing around with it and cannot get it right. I would like for the .ajax call to be ran when my button (labeled with ID "add") is clicked, however the database is updated everytime the page is refreshed and NOT when the button is clicked! Can someone explain why? Thanks in advance
$('#add').click(
$.ajax({
url: 'test.php',
success: function() {
alert("added");
}
})
);
UPDATE: Thanks to @flo I was able to get this working perfectly. Here's the final product:
$(document).on('click','#add',function() {
$.ajax({
url: 'test.php',
success: function() {
alert("added");
}
})
});
I'm not 100% sure about it, but I guess you are trigerring the click with some stuff to execute, instead of binding this event !
I mean:
$('#add').click($.ajax...)
should not be the same as:
$('#add').click(function (clickEvent) {
// Update here !
$.ajax...
});
But anyway, you should prefer:
$('#add').on('click', function (clickEvent) {
// Update here !
$.ajax...
});
Or even better:
$(document).on('click', '#add', function (clickEvent) {
// Update here !
$.ajax...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With