marius2k12
marius2k12

Reputation: 1101

jQuery - Form submit

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; 
});

Upvotes: 0

Views: 149

Answers (3)

user1386320
user1386320

Reputation:

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.

Upvotes: 2

marius2k12
marius2k12

Reputation: 1101

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; 
}); 

Upvotes: -1

user1744166
user1744166

Reputation:

Try it:

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

Upvotes: 2

Related Questions