41

seems like a simple issue but the solutions to the other problem don't seem to work from me.

Trying to trigger a AJAX request from a button click but it doesn't seem to be firing.

example HTML

<button class="remove_weight_button" id="15">x</button>

javascript

$(".remove_weight_button").click(function(){
    var button_id = $(this).attr("id");
    $.ajax({
        type: "POST",
        url: "weight_tracker_process.php",
        data: {
            weight_id: button_id,
            action: "remove"
        },
        success: function(){
            getWeightData();
        },
        error: function(){
            alert("data removal error");
        }
    });
    return false;
});
3
  • First things first, Do you see any errors in the console?, is it reaching the handler (if not is it wrapped in document.ready), do you see any js error or network error in the console? Commented Oct 8, 2013 at 0:44
  • 1
    Are you sure the javascript is being run after the button is loaded? That's a common error. Commented Oct 8, 2013 at 0:46
  • try to add a prevent default at the top of your function Commented Oct 8, 2013 at 0:52

1 Answer 1

125

The code you have works fine in fiddle. Is your button being dynamically rendered through AJAX after the initial page load?

Use

$(document).on("click", ".remove_weight_button", function(){

instead of

$(".remove_weight_button").click(function(){
Sign up to request clarification or add additional context in comments.

9 Comments

ah of course, yep you're right it's being loaded by ajax. How does the above fix this?
@user2803072 The ".click" event you're using only looks for elements that were drawn during the initial page load. The "on" event looks for elements in the current state of the page
Alternatively $(".remove_weight_button").live("click", function() { ... if the page is loaded dynamically and you are using an older version of jQuery. The key is the click doesn't notice dynamically loaded DOM elements as you mentioned.
This solution saved me .. I was trying for 1 hour to just fire an event with JQuery and could not do it.
@Mike.MKrallaProductions You're confused about the parent / child relationship. The document is the parent element in the example above. It could be any element that is encapsulating .remove_weight_button.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.