Search code examples
jqueryajaxpostparent

Submitting id of parent div of button using ajax


I am trying to submit the ID of the parent DIV that a button is in using AJAX. This is the markup:

<div id="32"><input id="button" type="button" class="before" onclick="add_fav();" /></div>

and this is the ajax script in its current state:

<script>
function add_fav()
{   
jQuery.ajax({       
      url: 'addfav.php',
      type: 'POST',
      data: {'id':jQuery(this).closest("div").attr("id"),is_ajax: 1},
      success: function(html) {
        jQuery('#button').removeClass('before');
        jQuery('#button').addClass('after');
        jQuery('#button').attr('disabled', 'disabled');
      }, 
      error: function() {
        jQuery('#error').html('<div>Error! Unable to add food item.</div>');
      }
    });
}
</script>

This isn't working so the method I am using to pass the id of the DIV is clearly not right. Perhaps someone could put me straight?


Solution

  • If using an inline click handler pass a reference to the clicked item to your function:

    onclick="add_fav(this);"
    

    Then:

    function add_fav(btn)
    {   
       jQuery.ajax({       
          url: 'addfav.php',
          type: 'POST',
          data: {'id':jQuery(btn).closest("div").attr("id"),is_ajax: 1},
          success: function(html) {
            jQuery('#button').removeClass('before');
            jQuery('#button').addClass('after');
            jQuery('#button').attr('disabled', 'disabled');
          }, 
          error: function() {
            jQuery('#error').html('<div>Error! Unable to add food item.</div>');
          }
        });
    }
    

    Within the inline attribute this does refer to the clicked element, but not within the function you're calling (unless you take steps to make it so with .call() or .apply()).

    However, I'd recommend binding the event handler with jQuery:

    jQuery("input.before").click(function(){
       jQuery.ajax({       
          url: 'addfav.php',
          type: 'POST',
          data: {'id':jQuery(this).closest("div").attr("id"),is_ajax: 1},
          success: function(html) {
            jQuery('#button').removeClass('before');
            jQuery('#button').addClass('after');
            jQuery('#button').attr('disabled', 'disabled');
          }, 
          error: function() {
            jQuery('#error').html('<div>Error! Unable to add food item.</div>');
          }
        });
    });
    

    ...and then jQuery makes sure this is set appropriately, and also you don't need the inline onclick. Put the above in a document.ready handler or in a script block that appears after the button (e.g., at the end of the body).