Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .click event runs on page load

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");
        }
    })
});
like image 792
stephenthedev Avatar asked Apr 19 '13 22:04

stephenthedev


1 Answers

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...
});
like image 51
Flo Schild Avatar answered Sep 28 '22 14:09

Flo Schild