如何使用 AJAX 调用将表单值传递给 PHP 变量

How to pass form value to PHP variable with AJAX call?

本文关键字:PHP 变量 值传 表单 何使用 AJAX 调用      更新时间:2023-09-26

有问题有人有什么想法吗?我只发布了代码所必需的。我基本上有一个 HTML 表单,我想在提交表单之前从表单上的字段中提取值,运行 ajax 调用并填充另一个字段。我想如果我能把在表单中输入的 Txt 转移到 modcreate 上的 PHP 变量中.php它就会起作用。因为如果我在没有变量的情况下手动输入详细信息,它可以工作。

主页.php

表单中的相关部分

  <tr>
    <th>Service Tag:</th>
    <th><input type="text" id="inputTag" name="inputTag" value="" onblur="this.value=this.value.toUpperCase()"></td>
  </tr>

  <tr>
    <th>Model:</th>
    <th>
       <input type="text" id="inputModel" name="inputModel" value=""> 
       <a href="#" id="updateBtn">Populate</a>
       <div id="spinner">
          <img src="'images'ajax-load.gif" alt="Loading..."/>
       </div>
    </th>
  </tr>

 <script type="text/javascript" src="'js'jquery-latest.js"></script>
 <script type="text/javascript"> 
 $('#updateBtn').click( function(e) {
    //to disable the click from going to next page
    e.preventDefault();
    $.ajax({
       url: "modcreate.php",
       data: { 'txt1': $('#inputTag').val() },
       success: function(data) {
       }
    });
 });
 </script>

模组创建.php

<?php 
$field1value = $_GET['txt1'];
    $file_string = file_get_contents('blahblah.com/'.$field1value);
    preg_match("/<title>Product Support for (.+)'| Dell/i", $file_string, $matches);
    $print = "$matches[1]";
    echo $print;
?>

******溶液******我的 Ajax 调用缺少将数据发送回表单字段的部分

这是工作 Ajax 现在的样子,谢谢大家的所有指示

 <script type="text/javascript" src="'js'jquery-latest.js"></script>
 <script type="text/javascript"> 
 $('#updateBtn').click(function(e){
     //to disable the click from going to next page
     e.preventDefault();
     $.ajax({
         url: "modcreate.php",
         data: { 'txt1': $('#inputTag').val() },
         success: function(data) {
            $('#inputModel').val(data); //this was the missing part
         }
     });
 });
</script>
<script type="text/javascript"> 
 $('#updateBtn').click(function(e){
    //to disable the click from going to next page
    e.preventDefault();
    $.ajax({
            url: "modcreate.php",
            data: 'data="{ "txt1": '+$('#inputTag').val()+' }"',
            success: function(data){

          }
     }
);
});
</script>

在服务器端:

$income_data = json_decode($_GET['data'], true);
$field1value = $income_data['txt1'];