通过简单的HTML PHP表单从JQuery返回PHP变量

时间:2019-02-11 18:32:49

标签: php jquery ajax

所以我有一个非常简单的html表单(form.php),并使用php插入到SQL DB中。

问题是我有一个动态添加名称功能(get_names.html),我希望从javascript函数“ post()”返回我的PHP变量$ name,因此我可以提交所有表单一次。

对于字段名称,我将AJAX与PHP(return_names.php)一起使用以字符串形式检索“名称”,并且它与$ _POST一起使用。

如何以格式将return_names.php的返回值传递给$ name?

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();
    ?>

我希望在form.php中回显$ name并获取“ return_names.php”返回的字符串,例如“ Ann Ann Mrs. Anna”。

1 个答案:

答案 0 :(得分:0)

因此,如果有人偶然发现类似内容,请进行更新。 我使用JQuery进行了如下管理:

get_names.html

chtContrast.getData().add(series1);

return_names.php

<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;


 ?>