【问题标题】:ajax and php to enter multiple forms input to databaseajax 和 php 输入多个表单输入到数据库
【发布时间】:2013-12-07 15:27:51
【问题描述】:

我有一个 php 生成的表单,其中包含多个输入字段,其数量由用户选择确定。我想使用 ajax 函数将所有数据输入数据库。问题是我是 ajax 新手,不确定如何去做。下面的 ajax javascript 函数是我想要实现的示例,我知道它不正确。有人可以指出我正确的方向。我环顾四周,从我所看到的来看,Json 可能是一个解决方案,但我对此一无所知,并且阅读它我仍然不明白。

示例 ajax:

function MyFunction(){

var i = 1;
var x = $('#num_to_enter').val();
   while (i <= x){
    var name = $('#fname[i]').val();
    var lname = $('#lname[i]').val();
    var email = $('#Email[i]').val();
    i++;
 }
    $('#SuccessDiv').html('Entering Info.<img src="images/processing.gif" />');
     $.ajax({url : 'process.php',
    type:"POST",
   while (i <= x){
    data: "fname[i]=" + name[i] + "&lname[i]=" + lname[i] + "&email[i]=" + email[i],
    i++;
 }
     success : function(data){
    window.setTimeout(function()
    {
    $('#SuccessDiv').html('Info Added!');
    $('#data').css("display","block");
    $('#data').html(data);
    }, 2000);
        }
});
        return false;
          }

表格样本:

<?php

   echo "<form method='post'>";

   $i=1;

    while($i <= $num_to_enter){

    $form_output .= "First Name:

    <input id='fname' type='text' name='fname[$i]'><br />

     Last Name:

    <input id='lname' type='text' name='lname[$i]'><br />

    Email:

    <input id='Email' type='text' name='Email[$i]'><br />

    $i++;

   }

   echo"<input type='button' value='SUBMIT' onClick='MyFunction()'></form>";

   ?>

Then DB MySQL Sample


   <?php
       while ($i <= $x){

    $x = $_POST['num_to_enter'];
    $fname = $_POST['fname[$i]'];
    $fname = $_POST['fname[$i]'];
    $fname = $_POST['email[$i]'];

        $sql = "INSERT INTO `mytable` 
    (`firstname`, `lastname`, `email`) VALUES ('$fname[$i]', '$lname[$i]', '$email[$i]');";

    $i++;

    }

   ?>

【问题讨论】:

标签: php ajax


【解决方案1】:

这是一个简单的 AJAX 演示:

HTML

<form method="POST" action="process.php" id="my_form">
    <input type="text" name="firstname[]">
    <input type="text" name="firstname[]">
    <input type="text" name="firstname[]">
    <input type="text" name="firstname[custom1]">
    <input type="text" name="firstname[custom2]">
    <br><br>
    <input type="submit" value="Submit">
</form>

jQuery

// listen for user to SUBMIT the form
$(document).on('submit', '#my_form', function(e){

    // do not allow native browser submit process to proceed
    e.preventDefault();

    // AJAX yay!
    $.ajax({
        url: $(this).attr('action') // <- find process.php from action attribute
        ,async: true // <- don't hold things up
        ,cache: false // <- don't let cache issues haunt you
        ,type: $(this).attr('method') // <- find POST from method attribute
        ,data: $(this).serialize() // <- create the object to be POSTed to process.php
        ,dataType: 'json' // <- we expect JSON from the PHP file
        ,success: function(data){

            // Server responded with a 200 code

            // data is a JSON object so treat it as such
            // un-comment below for debuggin goodness
            // console.log(data);

            if(data.success == 'yes'){
                alert('yay!');
            }
            else{
                alert('insert failed!');
            }
        }
        ,error: function(){
            // There was an error such as the server returning a 404 or 500
            // or maybe the URL is not reachable
        }
        ,complete: function(){
            // Always perform this action after success() and error()
            // have been called
        }
    });
});

PHP 进程.php

<?php
/**************************************************/
/* Uncommenting in here will break the AJAX call */
/* Don't use AJAX and just submit the form normally to see this in action */

// see all your POST data
// echo '<pre>'.print_r($_POST, true).'</pre>';

// see the first names only
// echo $_POST['firstname'][0];
// echo $_POST['firstname'][1];
// echo $_POST['firstname'][2];
// echo $_POST['firstname']['custom1'];
// echo $_POST['firstname']['custom2'];

/**************************************************/

// some logic for sql insert, you can do this part

if($sql_logic == 'success'){

    // give JSON back to AJAX call
    echo json_encode(array('success'=>'yes'));
}
else{

    // give JSON back to AJAX call
    echo json_encode(array('success'=>'no'));
}
?>

【讨论】:

  • MonkeyZeus 感谢您的回复!我认为您错过了将有超过 1 个 fname 字段的部分,依此类推,因此 fname[I]。我错了吗??
  • AJAX 发布您需要的输入字段没有问题。一旦 PHP 获取数据,您就可以正确处理它们。请查看编辑
  • MonkeyZeus 我们可以去聊天,我会告诉你更多我正在使用的东西吗??
  • 看你在哪个时区,我在纽约。我现在也在用手机,直到明天某个时候才会用电脑
  • 我也在纽约,我也会试着抓住你 2moro
【解决方案2】:
var postdata={};
postdata['num']=x;
   while (i <= x){
    postdata['fname'+i]= name[i];
    postdata['lname'+i]= lname[i];
    postdata['email'+i]= email[i];

    i++;
}
 $.ajax({url : 'process.php',
    type:"POST",
    data:postdata,
    success : function(data){
    window.setTimeout(function()
    {
    $('#SuccessDiv').html('Info Added!');
    $('#data').css("display","block");
    $('#data').html(data);
    }, 2000);
        }
});

PHP

$num=$_POST['num'];
for($i=1;i<=$num;i++)
{
 echo $_POST['fname'.$i];
 echo $_POST['lname'.$i];
 echo $_POST['email'.$i];
}

【讨论】:

  • Patato,给我一些时间来处理这个。感谢您的回复,我们会尽快回复您。
  • Patato 我认为您在正确的轨道上,我使用您的代码进行了一些更改,因为我有更多的字段然后显示在这里。将代码通过 jsLint 并在 30% 后显示太多错误无法继续。此外,使用文件中的代码,其他任何 javascript 都不起作用。我们可以去聊天,我会告诉你我有什么??
  • @CornHoleLI 抱歉迟到了,因为我在中国已经快午夜了
  • 帕拉托你在吗?
  • 不好意思,可以发邮件给我zzh2@shu.edu.cn
猜你喜欢
  • 2012-10-30
  • 1970-01-01
  • 1970-01-01
  • 2020-01-29
  • 2015-05-23
  • 1970-01-01
  • 2015-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多