0

I have a form that I intend to submit using jQuery. The following code works fine for the first time.

If the returning data equals "updated" I re-create the form within my #cart-content element. In other words: If i submit the form and it updates my cart I have a new form on my site (which has the same class, same inputs etc).

If I then click on submit again it wont trigger my jQuery code. I guess that because it's a new form that did not exist when the page was loaded so jQuery is not bound to its events and it doesnt get triggered when I submit the form.

What do I have to change to get it working? Thanks in advance!

$("form.update-cart").on("submit", function(event){
        $.post(link + "create_order/update_cart",  $(this).serialize(),  
        function(data){  
            if(data == 'updated')
            {
                var csrf_cookie = $.cookie('csrf_cookie_name');
                $("#cart-content").load(link + "create_order/display_cart", {"csrf_test_name": csrf_cookie});
            }
            else if(data == 'nothing-to-update')
            {
                return false;
            }
            else
            {  
                alert("Couldnt update cart!");  
            }  
        });  
        return false; 
});
marius2k12
  • 1,041
  • 1
  • 18
  • 32
  • 1
    Show us your html, are you replacing the whole form ? Why not just have another event handler bound using `.on` for the new form that is injected ? – aziz punjani Oct 15 '12 at 13:34

3 Answers3

2

Try it:

$("form.update-cart").live("submit", function(event){

2

In response to you and Catalin Ene, jQuery's "live" function is being deprecated from jQuery.

You should use "on" function if you're using jQuery 1.7.x or later:

$("form.update-cart").on("submit", function(event) {

And you can use "delegate" if your jQuery's version is lower than 1.7:

$("form.update-cart").delegate("submit", "#submit_btn", function(event) {

Also, an advice: It's a good practice to use XML or JSON outputs from your server-side scripts.

Community
  • 1
  • 1
-1

I've figured it out but ill accept an answer as soon as i can. Thanks!

$(document).on("submit", "form.update-cart", function(event) {
        $.post(link + "create_order/update_cart",  $(this).serialize(),  
        function(data){  
            if(data == 'updated')
            {
                var csrf_cookie = $.cookie('csrf_cookie_name');
                $("#cart-content").load(link + "create_order/display_cart", {"csrf_test_name": csrf_cookie});
            }
            else if(data == 'nothing-to-update')
            {
                return false;
            }
            else
            {  
                alert("Konnte Warenkorb nicht aktualisieren!");  
            }  
        });  
        return false; 
}); 
marius2k12
  • 1,041
  • 1
  • 18
  • 32