简体   繁体   中英

auto submit form on pageload using AJAX and get html type result?

I'm trying to autosubmit a form on page load using ajax and then get the HTML (a bunch of divs that will be echo-ed on the AJAX URL) back to my AJAX page.

first off, my code auto submits the form but it will ignore the AJAX call so the user will be taken to the form's action page.

also, if I remove the auto submit code from my AJAX code and submit the form manually via the submit button I get nothing back from the AJAX URL page!

This is my entire code:

window.onload = function(){
document.forms['myformR'].submit()  


  // this is the id of the form
    $("#myformR").submit(function() {

        var url = "results.php"; // the script where you handle the form input.

        $.ajax({
               type: "POST",
               url: url,
                dataType: "html", //expect html to be returned                
                success: function (response) {
                    $("#prores").html(response);


                }
             });

        return false; // avoid to execute the actual submit of the form.
    });

}

any advise would be appreciated.

EDIT, THIS IS MY ajax PHP URL page:

<?php
session_start();
?>
<?php
include "config/connect.php";
$searchList = "";
$clause = " WHERE ";//Initial clause
$sql="SELECT *
FROM `yt`
INNER JOIN `ATTRIBUTES` ON yt.subcats=ATTRIBUTES.type";//Query stub
if(isset($_POST['submit'])){
    if(isset($_POST['keyword'])){
        foreach($_POST['keyword'] as $c){
            if(!empty($c)){
                ##NOPE##$sql .= $clause."`".$c."` LIKE '%{$c}%'";
                $sql .= $clause . " (ATTRIBUTES.sizes LIKE BINARY '$c' OR ATTRIBUTES.colors LIKE BINARY '$c' OR ATTRIBUTES.type LIKE BINARY '$c')";
                $clause = " OR ";//Change  to OR after 1st WHERE
            }
        }
        $sql .= " GROUP BY yt.id ";
        //print "SQL Query: $sql<br />"; //<-- Debug SQl syntax.
        // Run query outside of foreach loop so it only runs one time.
        $query = mysqli_query($db_conx, $sql);
        //var_dump($query); //<-- Debug query results.
        // Check that the query ran fine.
        if (!$query) {
            print "ERROR: " . mysqli_error($db_conx);
        } else {
            // Use $query inside this section to make sure $query exists.
            $productCount = mysqli_num_rows($query);
            $i=0; // count the output amount
            if ($productCount > 0) {
                while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
        $sizesOption ="";
        $colorOption ="";
             $id = $row["id"];
             $product_name = $row["product_name"];
             $details = $row["details"];
             $details = preg_replace("/\\\\r\\\\n/", "", $details);
             $price = $row["price"];
             $category = $row["category"];
             $manu = $row["manu"];
             $sizez = $row["sizez"];
             $colours = $row["colours"];
             $colours = preg_replace('/\.$/', '', $colours);
             $sizez = preg_replace('/\.$/', '', $sizez); //Remove dot at end if exists
             $array = explode(',', $sizez);
             $arrayC = explode(',', $colours); //split string into array seperated by ','
             foreach($array as $value) //loop over values
             {
                 //echo $value . PHP_EOL; //print value
                 $sizesOption .='<option>'.$value.'</option>';
              }
            foreach($arrayC as $valueC) //loop over values
             {
                 //echo $value . PHP_EOL; //print value
                 $colorOption .='<option>'.$valueC.'</option>';
              }
                   $searchList .= '<div align="center" class="mypro" style="position:relative; width:270px; height:470px; border:solid 1px #CCC; margin:10px; float:left; overflow:hidden; padding:5px;">

<a class="overlay" href="product.php?id='.$id.'"></a>

<!--<a class="overlayBtns" href="">Quick View</a>-->

<div class="overlayAdd">



            <a style="font: bold 11px Arial;
  text-decoration: none; background-color: #FFF; color: #333333; padding: 10px; border:none; border-radius:4px; width:120px; height:30px;" id="go" rel="leanModal" name="test" href=".test'.$id.'">Qick View <i style="color:#000; font-size:18px;" class="fa fa-eye"></i></a>



           <div  style="display:none; display:none; width:580px; height:auto; background-color:#FFF; border-radius:4px; padding:12px;" class="test'.$id.'">


           <h2>'.$product_name.'</h2>

         <p style="text-align:left;">'.$details.'</p>
         <form id="form'.$id.'" class="form1" name="form1" method="post" action="cart.php">
         <p>
         <p style="text-align:left; font-weight:bold;">Size</p>
         <select id="sizeSelect"  name="sizeSelect" style="">
         '.$sizesOption.'
         </select>


         <p style="text-align:left; font-weight:bold;">Colour</p>
         <select id="colorSelect" name="colorSelect" style="">
         '.$colorOption.'
         </select>

         </p>
        <p style="text-align:left; font-weight:bold; width:100px; float:left;">Quantity</p> 
             <input min="1" type="number" id="quantity" name="quantity" value="1" />
        </p> 
        <p>
        <input type="hidden" name="pid" id="pid" value="'.$id.'" />
        <input type="hidden" name="moneyPrice" id="moneyPrice" class="moneyPrice" value="" />
        <input type="hidden" name="moneyCurreny" id="moneyCurreny" class="moneyCurreny" value="" />
        <input style="background-color:#000; color:#FFF;" type="submit"  value="ADD TO BASKET" />

      </form></p>
      <br><br>
      <a href="product.php?id='.$id.'">View Item Full Details</a><br><br>

<div class="share-buttons" data-url="http://enzua.com/product.php?id='.$id.'" data-text="http://enzua.com/product.php?id='.$id.'"></div>

        </div></div>


<img width="100%" src="product_images/'.$id.'Image1.jpg" alt=""  />


<p style="padding:2px;">'.$product_name.'</p>
<p style="padding:2px;">'.$manu.'</p>

    <div style="padding:5px;" class="price">

      <div class="prod-price"><span class=money>£'.$price.'.00</span></div>
    </div>

</div>';
                }
            }
        }
    }
}

?>
<?php 
echo $searchList;
exit(); 
?>

AND THIS IS MY HTML FORM:

    <form class="myformR" id="myformR" name="myformR" method="post" action="results.php">

    <input type="hidden" name="keyword[]" value="dress" />

    <input id="smt" type="submit" value="submit" name="submit" />

    </form>
<div id="prores"></div>

use below code

 $(window).load(function(){
 // this is the id of the form
    var url = "results.php"; // the script where you handle the form input.
    $.ajax({
           type: "POST",
           url: url,
           data:$( "#myformR" ).serialize(),
           dataType: "html", //expect html to be returned                
           success: function (response) {
                $("#prores").html(response);
            }
         });
});

If I understand you problem correctly you just want to submit the form on page load and currently with your code it is not submitting via ajax. can you please try the following code

$("#myformR").submit(function(e) {
  e.preventDefault();
  // your code
}

I guess what you need is this

  $("#myformR").submit(function() { var url = "results.php"; // the script where you handle the form input. $.ajax({ type: "POST", url: url, data: new FormData( this ), processData: false, contentType: false, dataType: "html", //expect html to be returned success: function (response) { $("#prores").html(response); } }); return false; // avoid to execute the actual submit of the form. }); 

send the formdata to the backend with the information about the form Hope this helps

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