简体   繁体   中英

Submit the form returned by ajax

I want to submit the form returned by ajax but it's not submitting the form.

Here is the code I tried

This file is called 3.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
    $(function(){
      $("#submitform").on("click", function(){
       $.post("4.php").done(function(data){
         //$($.parseHTML(data)).find("#paypalsubmit").submit();
         $($.parseHTML(data)).find("input[type='submit']").submit();
       });
      });

    });
    </script>
    <div id="submitform">click</div>

4.php file

    <form id="paypalsubmit" method="post" action="stackoverflow.com">
    <input type="text" value="hello stack" name="inputt">
    <input type="submit" name="submit" value="submit">
    </form>

update used click function and it worked

Tried another method still it doesn't work

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

    <script>
    $(function(){
      $("#submitform").on("click", function(){
        alert("hello");
       $.post("4.php").done(function(data){
        $("#formplace").html(data).find("#paypalsubmit").submit();
        setTimeout(function(){
            alert("submitting the form");
            //$("#formplace").find("#paypalsubmit").submit();},
            //$("#paypalsubmit").submit();},
            $("#formplace").find("input[type='submit']").click();},
            2000);


       });

      });

    });
    </script>
    <div id="submitform">click</div>

    <div id="formplace"> </div>

Thanks

Instead use a virtual div to hold the form and then submit the form instead:

$.post("4.php").done(function(data){
   var $div = $('<div>',{ html : data });
   $div.find("form")[0].submit();
});

Not sure if form can be submitted as above i suggested. But another way is to put the form in the page and then submit it:

$.post("4.php").done(function(data){
   $('body').append(data);
   $("#paypalsubmit")[0].submit();
});

Replace below line

$($.parseHTML(data)).find("input[type='submit']").submit();

To

$("#paypalsubmit").submit();

You should change out your on click for

$("#submitform").on("click", "#submitform", function() {

This will allow jQuery to see the newly created submit button.

I thinks ,you can't submit without action ("click") for new appended one ! For me ,used trigger is working .Find type submit instead of form id

 $(function(){
      $("#submitform").on("click", function(){
        alert("hello");
       $.post("4.php").done(function(data){
        $("#formplace").html(data).find(":submit").trigger("click");
      });    
    });

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