繁体   English   中英

如何使用 PHP ajax 在 Modal Box 中提交 HTML 表单数据?

[英]How to submit HTML form data in Modal Box using PHP ajax?

我想使用 PHP 和 Ajax 在数据库中的state mysql table中添加state名称,但模式框未提交信息。 我在模型框中发布了所有用于单按钮提交的代码,如下所示:

我的目录结构是:

目录结构

服务器文件

test.html

<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
    <link rel="stylesheet" type="text/css" href="./model.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"> 
    </script>
</head>
<body>
    <button id="add_state">Add State</button>

     <div>
      <?php                                            


         include('server/connection.php');

         $sqlSelect="SELECT * FROM tbl_state_info ORDER By StateName ASC";
         $result = $conn -> query ($sqlSelect);                                           
         $result = $conn -> query ($sqlSelect);                                          
         echo "<select name='StateName'>";
         echo "<option>select</option>";                                            
         while ($row = mysqli_fetch_array($result)) {
         echo "<option value=$row[StateName]> $row[StateName] </option>";
         }
         echo "</select>";
      ?>     


     </div>

    <div id="add_state_model" class="add_state_model">
        <div class="add_state_model_content">
            <span class="state_model_close">&times;</span>
            <form id="state_submit_form" method="post" action="">
                <label>Enter State:</label>
                <input type="text" name="state">
                    <input type="submit" name="state_submit">
                    </form>
                    <div class="message_box" style="margin-left: 60px;"></div>
                </div>
            </div>
            <script src="./model.js"></script>
        </body>
    </html>

对于后端,我使用 javascript 和 PHP

model.js


var add_state_model = document.getElementById('add_state_model');
var add_state_button = document.getElementById('add_state');
var add_state_span = document.getElementsByClassName('state_model_close')[0];

add_state_button.onclick = function(){
    add_state_model.style.display = "block";
}

add_state_span.onclick = function(){
    add_state_model.style.display = "none";
}

window.onclick = function(event) {
  if (event.target == add_state_model) {
    add_state_model.style.display = "none";
  }
}


$(document).ready(function(){

  var delay = 1000;

$('[name="state_submit"]').click(function(e){

           e.preventDefault();


           var state = $('#state_submit_form').find('[name="state"]').val();

           if(state === ''){
            $('.message_box').html(
                '<p><span style="color:red;">Please enter state name!</span></p>'
                );
            $('[name="state"]').focus();
            return false;
           }          

           console.log(state);    


          $.ajax({
                type: "POST",                       
                url: "server/addstate.php",
                data: {"state":state},
                beforeSend: function() {
                    $('.message_box').html(
                    '<img src="./tenor.gif" width="40" height="40"/>'
                    );
                }, 
                success: function(data)
                {
                    setTimeout(function() {
                    $('.message_box').html(data);
                    }, 1000);
                }
          });  
    });

});


还有服务器页面addstate.php

<?php

if ( ($_POST['state']!="") ){

$state = $_POST['state'];

include('connection.php');

/* check connection */
if ($conn->connect_errno) {
    printf("Connect failed: %s\n", $conn->connect_error);
    exit();
}

//insert query for registration
$insertSql = "INSERT INTO `tbl_state_info`(`StateName`) VALUES ('$state')";

if ($conn->query($insertSql) === TRUE) {

    echo "<span style='color:green;'>
     <p>State added to dropdown</p>
     </span>";     

    }else{        
        printf("Error: %s\n", $conn->error);        
    }  
}

?>

connection.php文件

<?php

    // set the timezone first
    if(function_exists('date_default_timezone_set')) {
        date_default_timezone_set("Asia/Kolkata");
    }

    $conn = new mysqli('localhost', 'root', '');

    //check connection
    if($conn->connect_error){
        die("Connection Failed".$conn->connect_error);
    }

    //connect database
    mysqli_select_db($conn, 'crm');
?>

和 css 文件model.css ,它用于模型框弹出


.add_state_model {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.add_state_model_content {
  background-color: #fefefe;
  margin: 15% auto; /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  width: 30%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.state_model_close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.state_model_close:hover,
.state_model_close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

我收到以下错误:

错误

在你的 ajax 请求数据对象中只接受 json 对象并且你已经传递了查询字符串试试这个代码

$.ajax({
    type: "POST",                       
    url: "http://localhost/CRM/server/addstate.php",
    data: {"state":state},
    beforeSend: function() {
        $('.message_box').html(
        '<img src="tenor.gif" width="40" height="40"/>'
        );
    }, 
    success: function(data)
    {
        setTimeout(function() {
        $('.message_box').html(data);
        }, 1000);
    }
}); 

第二件事 settimeout 接受我指定的 1 秒的延迟(以毫秒为单位)

如果我没有错,请纠正我

您可以访问此 URL,这将帮助您解决问题如何解决“重定向已被 CORS 策略阻止:没有“访问控制-允许-来源”标头”?

或者尝试更改我尝试过的 URL 路径它对我有用

 url: "http://localhost/CRM/server/addstate.php", 
    to
    url: "server/addstate.php"

在此处输入图片说明 如果有任何帮助,请随时问我

暂无
暂无

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

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