duanmiyang6201
duanmiyang6201
2019-02-11 18:32

在简单的HTML PHP表单中从JQuery返回PHP变量

已采纳

so I have a very simple html form (form.php) and use php to inserted into a SQL DB.

The problem is that I have a dynamic add names feature (get_names.html), which I want to have the return from the javascript function "post()" to my PHP variable $name, so I can submit all the form at once.

For the field name, I use AJAX with PHP (return_names.php) to retrieve the 'name' as a string, and it works with $_POST.

How to pass the return from return_names.php to $name in the form?

form.php

    <meta http-equiv="Content-type" content="text/html; charset=UTF- 
8" />
    <html>
    <body>
    <head>
    <script type="text/javascript" src="myjquery.js"></script>
    </head>
    <?php
    include("connect-db.php");
    function renderForm($id = '', $place = '', $name ='') { ?>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <form action="" method="post">
    <div>
    <?php if ($id != '') { ?>
    <input type="hidden" name="id" value="<?php echo $id; ?>" />
    <p>ID: <?php echo $id; ?></p>
    <?php } ?>
    <br/>
    <strong>Place: </strong> <input type="text" name="place"
    value="<?php echo $place; ?>"/><br/>
    <br/>
    <strong>Name: </strong> <input type="text" name="name"
    value="<?php echo $name; ?>"/><br/>
    <br/>
    <?php
    if (isset($_POST['submit']))
    {

    $id = htmlentities($_POST['id'], ENT_QUOTES);
    $place = htmlspecialchars($_POST['place'], ENT_QUOTES);
    $name = htmlspecialchars($_POST['name'], ENT_QUOTES);
    ($stmt = $mysqli->prepare("INSERT mydb (id, place, name)
    VALUES (?, ?, ?)"));
    {
    $stmt->bind_param("iss", $id, $place, $name);
    $stmt->execute();
    $stmt->close();
    }
    }
    }
    ?>
    <br/>
    </div>
    </form>
    </body>
    </html>

get_names.html

<head>
<script src="jquery-3.3.1.min.js"></script>
</head>
<script type='text/javascript'>
    const optionsSelect = [{
    id: 1,
    title: 'Mr'
    },
    {
    id: 2,
    title: 'Mrs'
    }
    ];
    function getResults() {
    const { selects, inputs } = getInputs();

    return selects.reduce((acc, select, i) => {
    const { title, name } = getValuesFromElements(select, 
inputs[i]);
    msg = (title && name) ? `${acc} ${title}. ${name}` : acc;
    document.getElementById("asservat").innerHTML = msg;
    var msgs = msg;
    //return (title && name) ? `${acc} ${title}. ${name}` : acc;
    return msgs;
    }, '');
    }

    function getResultsAsArray() {
    const { selects, inputs } = getInputs();

    const getFieldValues = (select, i) => {
    const { title, name } = getValuesFromElements(select, 
 inputs[i]);

    return (title && name) ? `${title}. ${name}` : '';
    };

    return selects.map(getFieldValues).filter(Boolean);
    }

    function getValuesFromElements(select, {value: name}) {
    const { title } = optionsSelect[select.value - 1];

    return {title, name};
    }

    function getContainerElements(query) {
    return Array.from(document.querySelectorAll(`#container > 
${query}`));
    }

    function getInputs() {
    const selects = getContainerElements('select');
    const inputs = getContainerElements('input');

    return {
    selects,
    inputs
    }
    }
    function addFields() {
    const { value: number } = document.getElementById('member');
    const container = document.getElementById('container');

    while (container.hasChildNodes()) {
    container.removeChild(container.lastChild);
    }

    for (let i = 0; i < number; i++) {
    const select = document.createElement('select');
    for (let j = 0; j < optionsSelect.length; j++) {
      const options = document.createElement('option');
      options.value = optionsSelect[j].id;
      options.text = optionsSelect[j].title;
      select.appendChild(options);
    }
    container.appendChild(select);
    container.appendChild(document.createTextNode(' -> Name ' + (i + 1)));
    const input = document.createElement('input');
    input.type = 'text';
    container.appendChild(input);
    container.appendChild(document.createElement('br'));
    }
    }

    </script>

    <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
    <a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
    <a href="#" onclick="console.log(getResults())">Log results</a>
    <p id="container"></p>
    <div id="asservat"></div>
    <input type="button" value="Submit" onclick="post();">ajax<br />
    <script type="text/javascript">
    function post(){
    var name = getResults();
    $.post('return_names.php',{postname:name},
    function(data){
    $('#name').html(data);
    });
    return $('#name').html(data);
    }
    </script>

return_names.php

    <?php
    function data() {
    $name = $_POST['postname'];
    echo "Name as string ->", $name, " <- here";
    return $name;
    }
    data();
    ?>

I expect to echo $name in the form.php and get the strings returned by "return_names.php" for example "Mr. Ann Mrs. Anna"

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douan2907 douan2907 2年前

    So updating this in case someone stumbles upon similar. I managed using JQuery as following:

    get_names.html

    <head>
    <script src="jquery-3.3.1.min.js"></script>
    </head>
    <script type='text/javascript'>
      const optionsSelect = [{
          id: 1,
          title: 'Mr'
        },
        {
          id: 2,
          title: 'Mrs'
        }
      ];
      function getResults() {
        const { selects, inputs } = getInputs();
    
        return selects.reduce((acc, select, i) => {
          const { title, name } = getValuesFromElements(select, inputs[i]);
          msg = (title && name) ? `${acc} ${title}. ${name}` : acc;
          document.getElementById("name").innerHTML = msg;
          var msgs = msg ;
          //return (title && name) ? `${acc} ${title}. ${name}` : acc;
          return msgs;
        }, '');
      }
    
      function getResultsAsArray() {
        const { selects, inputs } = getInputs();
    
        const getFieldValues = (select, i) => {
          const { title, name } = getValuesFromElements(select, inputs[i]);
    
          return (title && name) ? `${title}. ${name}` : '';
        };
    
        return selects.map(getFieldValues).filter(Boolean);
      }
    
      function getValuesFromElements(select, {value: name}) {
        const { title } = optionsSelect[select.value - 1];
    
        return {title, name};
      }
    
      function getContainerElements(query) {
        return Array.from(document.querySelectorAll(`#container > ${query}`));
      }
    
      function getInputs() {
        const selects = getContainerElements('select');
        const inputs = getContainerElements('input');
    
        return {
          selects,
            inputs
        }
      }
      function addFields() {
        const { value: number } = document.getElementById('member');
        const container = document.getElementById('container');
    
        while (container.hasChildNodes()) {
          container.removeChild(container.lastChild);
        }
    
        for (let i = 0; i < number; i++) {
          const select = document.createElement('select');
          for (let j = 0; j < optionsSelect.length; j++) {
            const options = document.createElement('option');
            options.value = optionsSelect[j].id;
            options.text = optionsSelect[j].title;
            select.appendChild(options);
          }
          container.appendChild(select);
          container.appendChild(document.createTextNode(' -> Name ' + (i + 1)));
          const input = document.createElement('input');
          input.type = 'text';
          container.appendChild(input);
          container.appendChild(document.createElement('br'));
        }
      }
    
    </script>
    
    <script type="text/javascript">
    
        function post(){
            var name = getResults();
            $.post('return_names.php',{postname:name},
            function(data){
            var result = $('#name').html(data);
            return result;
            });
        }
    </script>
    
    <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
    <a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
    
    <p id="container"></p>
    <div id="name"></div>
    
    <?php $return_var = '<input type="button" value="Submit" onclick="post();">Post <br />';
    echo $return_var;
    
    
     ?>
    

    return_names.php

    <?php
    function returnString() {
    
    $name = $_POST['postname'];
    echo "the name entered ->", $name, " <- hier";
    return $name;
    }
    
    returnString();
    
    点赞 评论 复制链接分享

相关推荐