简体   繁体   中英

Form's submit does not work when I load a page with JQuery

I'm working on this system, and the guy who wrote it uses JQuery to submit the form like this:

$(".btnFinalizaEnvioPedido").click(function() {
    $("#modalAvisoEnviaPedido").modal("hide");
    $("#myModalCarregando").modal('show');
    $("form[name=pedido]").submit();
});

And this is his form:

<form class="jqtransform" method="post" name="pedido" id="form-pedido">

This page wherein the form lies works perfectly when accessed by itself, but I find this method ugly so I'm loading the whole page with JQuery in the previous one, but when I do it, the whole form stops working.

<script>
    $(document).ready(function() {
        $(".icon_sisconbr-icons-pedidos").click(function () {
            $("body").load("../pedido/novo.php");
        });
        $(".btnFinalizaEnvioPedido").click(function () {
            $.ajax({
                type: "POST",
                url: "../pedido/acoes.php",
                success: function (result) {
                    ...     
                }
            });
        });
    });
</script>

I don't know how to make that submit work with AJAX. The method is POST (Not GET). Why the submit works when I actually ENTER the page with a <a> / link, and does not work when I load the whole page with JQuery's load??

When you use load the contents of the page are created after document.ready has already fired, so your click event is attached when the button doesn't exist on the page.

Instead of .click you can use .on to attach to the document itself and specify the element to listen to events on.

$(document).on("click", ".btnFinalizaEnvioPedido", function () {
    $.ajax({
        type: "POST",
        url: "../pedido/acoes.php",
        success: function (result) {
            ...     
        }
    });
});

See: http://api.jquery.com/on/ for more info

Because you must load body before bind to elements. In your scenario try to bind click for ajax event after $('body').load(/***/) stuff.

Your manner doesn't post the form data, if you want to use your code you must pass the form inputs in data string: $(".btnFinalizaEnvioPedido").click(function () { $.ajax({ type: "POST", data: 'name='+('#name_txt').val()+'&address='+. ('#address_txt').val(), url: "./pedido/acoes.php", success: function (result) { ...
} }); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM