views:

50

answers:

1

The client is making a request to the server. I need to take part of that request, and make the form button work with Ajax.

This piece of code works perfectly for links:

var pagination_render = function() {
    var pagination = $('.pagination a');
    pagination.each(function() {
        $(this).click(function(event) {
            load_server(this.href, '.houseindex');
            return false;
        });
    });
};
pagination_render();

I tried numerous things for making the Ajax button work, and this is one of the tries:

var contact_user = function () {
    $('.expanded').find('#submit').each(function() {
        $(this).unbind('click');
    });

    $('.expanded').each(function() {
        $(this).find('#submit').click(function(event) {
            form_submit($(this).parent(), '.contactuser .msg');
            return false;
        });
    });
}

Whenever there is a successful Ajax call, it goes through all of the expanded items, and then binds a click event.

Now, sometimes this code works, and sometimes it doesn't.. When it doesn't work, it disables other events (toggle links) I have set up. It seems as if I need to wait a few ms for it to load the component into the DOM.. Do I?

+2  A: 

So I get that when you call contact_user you:

  1. First unbind any previous binded click events from the submit button. I see one possible problem there and is that you are looking for an id of #submit. You should only have one id in a single page. Therefore you only need to use $('#submit').each(...) or if you have several submit buttons in the page either use a class if there are several submit buttons inside an .expanded item or just use $('.expanded :submit')
  2. Adding a custom event when clicking the submit button. Same thing, you can simplify this by $('.expanded :submit') or if you truly only have one button with an id of submit (quite confusing). Go with $('#submit').

In conclusion:

var contact_user = function(){
   $('.expanded :submit').unbind('click');
   $('.expanded :submit').click(function(){
      form_submit($(this).parent(), '.contactuser .msg');
      return false;
   });
};

the :submit selector will select all <input type="submit" />.

UberNeet
Perfect answer, thank you.The problem, apparently, was in a duplicate call for a function.I like the idea of using :submit, forgot it's a possibility with jQuery.
Yossi