0

I am trying to submit a child-form, inside parent-form via ajax-jquery, so that it does not refresh entire page. Code is:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function (e) {
        $(document).on('submit', '#form-2', function() {
            var data = $(this).serialize();
            $.ajax({
                type : 'POST',
                url  : 'a2.php',
                data : data,
                success :  function(data) {                     
                    $("#form-2").fadeOut(500).hide(function() {
                        $(".result").fadeIn(500).show(function() {
                            $(".result").html(data);
                        });
                    });

                }
        });

        return false;
    });

    }) // document ready ends here;
    </script>
    </head>
    <body>
    <form action="a1.php" method="post" name="form-1" id="form-1">
        <input type="text" name="f1" />
        <input type="text" name="f2" />
        <input type="text" name="f3" />
        <input type="text" name="f4" />
        <!-----form 2 ajax starts----->
        <form method="post" name="form-2" id="form-2">
            <input type="text" name="g1" />
            <input type="submit" id="sf2">
        </form><!-----form-2 ends----->
    </form><!-----form-1 ends----->
    </body>
    </html>

But its not working, it does simply nothing. I too used - preventdefault() Any help ? I am trying to simply submit form-2 value in database, from which some dropdown of form-1 is getting all option values.

Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75
luna.romania
  • 309
  • 3
  • 15

1 Answers1

0

You could use:

$(document).on('click', '#sf2', function(event) {
    var g1 = $('#g1').val();
    $.ajax({
        type : 'POST',
        url  : 'a2.php',
        data : {
            g1: g1
        },
        success :  function(data) {
            $("#form-2").fadeOut(500).hide(function() {
                $(".result").fadeIn(500).show(function() {
                    $(".result").html(data);
                });
            });

        }
    });
});

and use a normal button:

<input type="text" name="g1" id="g1" />
<button type="button" id="sf2">Submit</button>

This is not good style though as forms should not be nested.

Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75