Why does my Jquery code not work on elements loaded with . load(), how to load them?

Asked

Viewed 1,814 times

3

What is the correct way to load my jQuery scripts together with . load().

I did this way but wanted another solution that works with all the updates that occur with the form, as remove of products, change of quantity of the cart and etc:

// Adição ao Carrinho com retorno de plugins Jquery

$('#Carrinho').submit(function () {
    var $this = jQuery(this),
        dados = $this.serialize();
    jQuery.ajax({
        type: "POST",
        datatype: 'json',
        url: $this.attr('action'),
        data: dados,
        complete: function (update) {
            if ($(".list-inline button").hasClass("active")) {
                $("#cart-header").load("https://127.0.0.1/ #cart-header-container", function () {

                    // Estou atualizando meu carrinho, mas os demais scripts de remoção de produtos 
                    //ao carrinho, e alteração de quantidades precisam vir junto com está função, se o 
                    //usuários adicionar 10 produtos ao carrinho teria de repetir 10 vezes esse, e o 
                    //codigo ficaria muito longo, e não acredito ser a técnica correta.

                    // Abre - Fecha Sacola  
                    $(document).ready(function () {
                        $("#cart-right-nav").click(function () {
                            $("#cart-header").slideToggle("slow");
                        });
                    });
                    // Fim Abre - Fecha Sacola  
                });
                $("#cart-head-loader").fadeOut(1000);
            } else {
                $("#buy-btn").css("display", "block")
                $(".added-to-cart").css("display", "none");
            }
        },
        error: function (erro) {
            alert("Não adicionou a sacola.");
        }
    });
    return false;
});
  • What exactly doesn’t work? What’s going on, and what’s supposed to happen? What piece of code isn’t running?

  • It works, only this is, no . load() I call a script to work with the content that was loaded, only that loaded content will need another . load() with another script to work, so my code will be too long, I wanted a solution to load my code, every time . load() was used. I tried to put the code inside the elements that are loaded, but it doesn’t work, the . load() doesn’t bring my code together. @Viníciusgobboa.deOliveira

  • 2

    Not exactly a duplicate, but most likely that answer would solve your problem because it seems you are trying to run a script on a page that was loaded by AJAX which, natively, it is impossible.

  • Excellent reply @Brunoaugusto, I think the solution. I will try to implement it in the code and see what.Thanks

1 answer

1


Thanks again to Bruno Augusto, who practically solved my problem !

              $.getScript('script-carrinho.js');

I managed to solve just by making a call from the file 'script-cart.js', Through $.getScript(), inside the callback of complete, so the script needed to run this function is loaded every time it is executed.

$('#Carrinho').submit(function () {
    var $this = jQuery(this),
        dados = $this.serialize();
    jQuery.ajax({
        type: "POST",
        datatype: 'json',
        url: $this.attr('action'),
        data: dados,
        complete: function (update) {
            if ($(".list-inline button").hasClass("active")) {
                $("#cart-header").load("https://127.0.0.1/ #cart-header-container", function () {


                  $.getScript('script-carrinho.js');

                    // Consegui resolver apenas fazendo uma chamada do arquivo 'script-carrinho.js', 
                   // Através do $.getScript(), assim o script necessário para o funcionamento desta,
                  // função fica carregado.


                    // Abre - Fecha Sacola   --- Este script também entrou no arvuio 'script-carrinho.js'
                    $(document).ready(function () {
                        $("#cart-right-nav").click(function () {
                            $("#cart-header").slideToggle("slow");
                        });
                    });
                  // Fim Abre - Fecha Sacola --- Este script também entrou no arvuio 'script-carrinho.js'


                });
                $("#cart-head-loader").fadeOut(1000);
            } else {
                $("#buy-btn").css("display", "block")
                $(".added-to-cart").css("display", "none");
            }
        },
        error: function (erro) {
            alert("Não adicionou a sacola.");
        }
    });
    return false;
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.