Ajax和PHP进入多种形式输入到数据库 [英] ajax and php to enter multiple forms input to database

查看:129
本文介绍了Ajax和PHP进入多种形式输入到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP生成的表单与多个输入字段,其中由用户选择确定的数量。我想用一个Ajax功能,输入所有数据到数据库中。问题是,我是新来的Ajax和不知道何去了解它。 AJAX的javascript函数下面是什么,我想实现一个样品,我知道这是不正确的。有人能指出我朝着正确的方向发展。我环顾四周,并从我所看到的,JSON可能是一个解决方案,但我什么都不知道它,它读了,我还是不明白这一点。

范例Ajax:

 函数的MyFunction(){

变种I = 1;
。VAR X = $('#num_to_enter)VAL();
   而(ⅰ&其中; = x)的{
    变种名称= $('#FNAME [I])VAL()。
    。VAR LNAME = $('#L-NAME [I])VAL();
    。VAR电子邮件= $('#现[I])VAL();
    我++;
 }
    $('#SuccessDiv)HTML(输入信息与LT; IMG SRC =图像/ processing.gif/>');
     $阿贾克斯(网址:{url:process.php,
    键入:POST,
   而(ⅰ&其中; = x)的{
    数据:其中fname [I] =+名称[I] +与& lname的[I] =+ lname的[I] +与&电子邮件[I] =+电子邮件[I]中,
    我++;
 }
     成功:功能(数据){
    window.setTimeout(函数()
    {
    $('#SuccessDiv)HTML(信息新增!')。
    $('#数据)的CSS(显示,块)。
    $('#数据)HTML(数据);
    },2000);
        }
});
        返回false;
          }
 

形式的样本:

 < PHP

   回声<形式方法='后'>中;

   $ i = 1;

    而($ I< = $ num_to_enter){

    $ form_output =名字:

    <输入ID ='FNAME类型=文本名称='FNAME [$ i]'>< BR />

     姓:

    <输入ID ='L-NAME类型=文本名称='LNAME [$ i]'>< BR />

    电子邮件:

    <输入ID =电子邮件类型=文本名称=电子邮件[$ i]'>< BR />

    $ I ++;

   }

   回声<输入类型=按钮值=提交的onClick ='MyFunction的()'>< /形式GT;;

   ?>

然后数据库MySQL的样品


   < PHP
       而($ I< = $ X){

    $ X = $ _ POST ['num_to_enter'];
    $ FNAME = $ _ POST ['FNAME [$ i]];
    $ FNAME = $ _ POST ['FNAME [$ i]];
    $ FNAME = $ _ POST ['电子邮件[$ i]];

        $ SQL =INSERT INTO`mytable`
    (`firstname`,`lastname`,`email`字段)VALUES('$ FNAME [$ i],$ LNAME [$ i],$电子邮件[$ I]');;

    $ I ++;

    }

   ?>
 

解决方案

下面是AJAX的一个简单的演示:

HTML

 <形式方法=POST行动=process.phpID =my_form>
    <输入类型=文本名称=名字[]>
    <输入类型=文本名称=名字[]>
    <输入类型=文本名称=名字[]>
    <输入类型=文本名称=名字[CUSTOM1]>
    <输入类型=文本名称=名字[CUSTOM2]>
    < BR>< BR>
    <输入类型=提交值=提交>
< /形式GT;
 

的jQuery

  //监听用户提交表单
$(文件)。在('提交','#my_form',功能(五){

    //不允许自带浏览器提交过程进行
    即preventDefault();

    // AJAX耶!
    $阿贾克斯({
        网址:$(本).attr('行动')//<  - 发现从action属性process.php
        ,异步:真//<  - 不装东西了
        ,缓存:假//<  - 不要让高速缓存的问题困扰着你
        ,输入:$(本).attr(方法)//<  - 距离方法属性发现POST
        数据:$(本).serialize()//<  - 创建该对象被张贴到process.php
        ,数据类型:'json的//<  - 我们预计JSON从PHP文件
        ,成功:功能(数据){

            //数据是一个JSON对象,以便把它看作
            下面debuggin善良//取消注释
            //的console.log(数据);

            如果(data.success =='是'){
                警报('耶!');
            }
            其他{
                警报(插入失败!);
            }
        }
    });
});
 

PHP process.php

 < PHP
/ ******************* * /
/ *取消注释这里将打破AJAX调用* /
/ *不要使用AJAX,只是提交表单通常看到这个动作* /

//看到您所有的POST数据
//回声'< pre>'的print_r($ _ POST,真)。'< / pre>';

只有//看到的第一个名字
//回声$ _ POST ['姓'] [0];
//回声$ _ POST ['姓'] [1];
//回声$ _ POST ['姓'] [2];
//回声$ _ POST ['姓'] ['CUSTOM1'];
//回声$ _ POST ['姓'] ['CUSTOM2'];

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

//一些逻辑的SQL INSERT,你可以做到这一点的一部分

如果($ sql_logic =='成功'){

    //给JSON回到AJAX调用
    回声json_en code(阵列('成功'=>'是'));
}
其他{

    //给JSON回到AJAX调用
    回声json_en code(阵列('成功'=>'无'));
}
?>
 

I have a php generated form with multiple input fields the number of which is determined by user select. I would like to use an ajax function to enter all the data to database. The problem is that I am new to ajax and not sure ho to go about it. The ajax javascript function below is a sample of what I would like to achieve and I know it is not correct. Can someone point me in the right direction. I have looked around and from what I see, Json may be a solution but I know nothing about it and reading up on it I still don't get it.

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

A sample of form :

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

    }

   ?>

解决方案

Here is a simple demo of 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){

            // 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!');
            }
        }
    });
});

PHP process.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'));
}
?>

这篇关于Ajax和PHP进入多种形式输入到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆