简体   繁体   English

自动使用AJAX在pageload上提交表单并获取html类型结果?

[英]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. 我正在尝试使用ajax在页面加载时自动提交表单,然后将HTML(将在AJAX URL上回显的一堆div)返回到我的AJAX页面。

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. 首先,我的代码会自动提交表单,但是它将忽略AJAX调用,因此用户将被带到表单的操作页面。

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! 另外,如果我从AJAX代码中删除了自动提交代码,并通过“提交”按钮手动提交了表单,那么我在AJAX URL页面上什么也收不到!

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: 编辑,这是我的ajax PHP URL页面:

<?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: 这是我的HTML表格:

    <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. 如果我正确地理解了您的问题,那么您只想在页面加载时提交表单,当前使用您的代码就不能通过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 将表单数据和有关表单的信息发送到后端,希望对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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