将foreach值添加到Ajax [英] Add foreach value to Ajax

查看:83
本文介绍了将foreach值添加到Ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个问题;1)如何将值从foreach传递给ajax.这是我的代码,到目前为止,我尝试将ajax放入foreach中,但它始终为我提供每个姓氏的ID.

2)有没有一种方法,我可以单击添加,并且数据将被保存并放置在此html表下方的另一个html表中,但是直到我单击第二个表中的insert时,才将其插入数据库中.

 < table class ="table table-bordered datatable" id ="table_export">< thead>< tr>< th&#;/th>< th> div<项目</div></th>< th> div</div</div>/th< th> div>价格</div></th>< th< div>数量</div</th>< th> div< Sell</div></th></tr></thead>< tbody><?php$ count = 1;$ notarray = DataDB :: getInstance()-> get_rows_from_field('name');foreach($ notarray如$ row):?>< tr>< td><?php echo $ count ++;?></td>< td><?php echo $ row ['name'];?></td>< td><?php echo $ row ['nickname'];?></td>< td><?php echo $ row ['surname'];</td>< form method ="post" action =" role ="form">< td>< div class ="form-group">< div class ="><输入type ="number" class ="form-control" name ="kin" data-validate ="required" data-message-required =需要Kins"自动对焦></div></div></td>< td>< div class ="btn-group">< button type ="submit" class ="btn btn-primary" name ="check"> Add</button></div></td></form></tr><?php endforeach;?></tbody></table>< br>< br>< div id ="get_result"></div>< script type ="text/javascript">$(函数(){$('form').on('submit',function(e){e.preventDefault();$ .ajax({类型:"post",网址:"verify.php",数据:$('form').serialize()+'& ins = sellin'+'& id =<?php echo $ row ['name_id'];?>',成功:功能(数据){jQuery('#get_result').html(data);}});});}); 

解决方案

如果我说对了,您的意思是您想从表A的项目列表中选择一个项目,它应该显示在表B中.单击表B中的提交"按钮以保存从表A中选择的项目?

这是解决方案:

请将该文件命名为 test.php

 <?php/***由PhpStorm创建.*用户:SQ05*日期:2017年6月1日*时间:06:31 PM*////请注意,数据是您从DB获得的数据的典型示例.所以确保你把所有的$ row都压入一个数组//这样您就可以创建这种性质的东西,例如//$ data = array();//$ i = 0;//while($ row = mysql_fetch_assoc($ query)){//$ data [$ i] = $ row;//$ i ++;//}//这会在下面创建这种性质的数据,$ data = array(array('id'=> 1,'name'=>'Loveth','age'=> 23,'phone'=>'9889087455'),array('id'=> 2,'name'=>'Susan','age'=> 51,'phone'=>'787987455'),array('id'=> 3,'name'=>'Precious','age'=> 13,'phone'=>'98989087455'),array('id'=> 4,'name'=>'Hannah','age'=> 21,'phone'=>'987087455'),array('id'=> 5,'name'=>'Kenneth','age'=> 43,'phone'=>'569087455'),);?>< div style ="float:left; width:50%">所有项目清单< table>< tr>< td>名称</td>< td>年龄< td>< td>电话</td>< td>动作</td></tr><?php$ i = 0;对于($ i = 0; $ i< count($ data); $ i ++){$ item = $ data [$ i];?>< tr>< td><?php echo $ item ['name'];?></td>< td><?php echo $ item ['age'];?></td>< td><?php echo $ item ['phone'];?></td>< td>< button onclick ='addToList(<?php echo json_encode($ item);?>);'> Add</button></td></tr><?php}?></table></div>< div style ="float:left; width:50%">要保存的项目< div id ="showToSave"></div></div>< script src ="bower_components/jquery/dist/jquery.js"></script>< ;!-请根据您自己的目录路径安装jquery->< script>var listToSave = [];//必须是全局的/***处理数据并添加到列表的添加到列表功能* @参数数据*/var addToList = function(data){var lenData = listToSave.length;if(lenData> 0){//这用于避免重复for(var j = 0; j< lenData; j ++){if(data.id == listToSave [j] .id)返回;}}listToSave.push(data);console.log(listToSave);document.getElementById('showToSave').innerHTML = createData(listToSave);};var createData =函数(数据){var len = data.length;var tableToSave =< table>< tr>< td>名称</td>< td>年龄</td>< td>电话</td>< td>操作</td>/tr>;var i;for(i = 0; i  

i have two questions which are below; 1)How do i pass a value from a foreach to ajax. this is my code and what i have so far, tried putting the ajax inside the foreach but it kept on giving me the id of the last name in the for each.

2)Is there a way that i can click on add and and the data will be held and put in another html table below this html table but wont be inserted into database until i click on insert in the second table.

 <table class="table table-bordered datatable" id="table_export">
                <thead>
                    <tr>
                        <th>#</th>
                        <th><div>Item</div></th>
                        <th><div>Quantity Left</div></th>
                        <th><div>Price</div></th>
                        <th><div>Quantity</div></th>
                        <th><div>Sell</div></th>

                    </tr>
                </thead>
                <tbody>
                    <?php
                        $count = 1; 
                        $notarray = DataDB::getInstance()->get_rows_from_field('name');
                        foreach($notarray as $row):?>

                    <tr>

                        <td><?php echo $count++;?></td>
                        <td><?php echo $row['name'];?></td>
                        <td><?php echo $row['nickname'];?></td>
                        <td><?php echo $row['surname']; ?></td>

                         <form method="post" action="" role="form">
                        <td>

                                <div class="form-group">

                                    <div class="">
                                        <input type="number" class="form-control" name="kin" data-validate="required" data-message-required="Kin required" autofocus>
                                    </div>
                                </div>

                        </td>

                            <td>

                            <div class="btn-group">
                            <button type="submit" class="btn btn-primary" name = "check">Add</button>
                            </div>
                            </td>
                        </form>

                   </tr>

                    <?php endforeach;?>
                </tbody>
            </table>

            <br><br>
            <div id="get_result">
                      </div>


<script type="text/javascript">


$(function () {

    $('form').on('submit', function (e) {

      e.preventDefault();

      $.ajax({
        type: 'post',
        url: 'verify.php',
        data: $('form').serialize() + '&ins=sellin' + '&id=<?php echo $row['name_id'];?>',
         success: function(data)
        {
            jQuery('#get_result').html(data);
        }
      });

    });

  });

解决方案

If I get you right, you mean you wanted to pick an item from list of items in table A and it should display in table B. Afterwards, you wanted to click submit button in table B to save the picked items from Table A?

Here is the solution:

Kindly name this file as test.php

<?php
/**
 * Created by PhpStorm.
 * User: SQ05
 * Date: 06/01/2017
 * Time: 06:31 PM
 */
//Note that data is a typical example of data u gotten from DB. so make sure u push all $row into an array
//such that u create something of this nature eg
// $data=array();
// $i=0;
//while($row=mysql_fetch_assoc($query)){
//$data[$i]=$row;
//$i++;
//}
// this will then create data of this nature below,
$data=array(
    array('id'=>1,'name'=>'Loveth','age'=>23,'phone'=>'9889087455'),
    array('id'=>2,'name'=>'Susan','age'=>51,'phone'=>'787987455'),
    array('id'=>3,'name'=>'Precious','age'=>13,'phone'=>'98989087455'),
    array('id'=>4,'name'=>'Hannah','age'=>21,'phone'=>'987087455'),
    array('id'=>5,'name'=>'Kenneth','age'=>43,'phone'=>'569087455'),
);

?>
<div style="float:left;width:50%">
    THE LIST OF ALL ITEMS
    <table>
    <tr>
        <td>Name</td>
        <td>Age</td>
        <td>Phone</td>
        <td>Action</td>
    </tr>
    <?php
    $i=0;
    for ($i=0;$i<count($data);$i++) {
        $item=$data[$i];
        ?>
        <tr>
            <td><?php echo $item['name'];?></td>
            <td><?php echo $item['age'];?></td>
            <td><?php echo $item['phone'];?></td>
            <td><button onclick='addToList(<?php echo json_encode($item);?>);'>Add</button></td>
        </tr>
    <?php
    }
    ?>
</table>
</div>

<div style="float:left; width:50%">
  THE ITEM TO BE SAVED
<div id="showToSave"></div>
    </div>

<script src="bower_components/jquery/dist/jquery.js"></script> <!--Please install jquery base on ur own directory path-->
<script>
    var listToSave=[]; // must be global

    /**
     * The add to list function that process data and add to list
     * @param data
     */
   var addToList= function(data){
        var lenData=listToSave.length;
          if(lenData>0){
              //this is used to avoid duplicate
             for(var j=0;j<lenData;j++){
                 if(data.id==listToSave[j].id) return;
             }
          }
        listToSave.push(data);
        console.log(listToSave);
        document.getElementById('showToSave').innerHTML=createData(listToSave);

    };

 var createData= function (data) {
        var len=data.length;
     var tableToSave="<table><tr><td>Name</td> <td>Age</td> <td>Phone</td> <td>Action</td></tr>";
     var i;
        for(i=0;i<len;i++){
          content=data[i];
        tableToSave+="<tr><td>"+content.name+"</td><td>"+content.age+"</td><td>"+content.phone+"</td><td>" +
            "<button onclick='deleteFromSave("+i+")'>Delete</button></td></tr>";
        }
     tableToSave+="</table><div><button onclick='saveData()' type='button'>Save</button></div>";
     return tableToSave;
    };


    /**
     * This is use to delete data added locally
     */
    var deleteFromSave=function (index) {
        listToSave.splice(index,1); //this is use to delete from list to save
        document.getElementById('showToSave').innerHTML=createData(listToSave); //to rerender after delete
    };

    /**
     * This is use to submit data
     */
    var saveData=function () {
        console.log('thjis=',listToSave);
        $.ajax({
            type: "POST",
            url: "getData.php",
            data: {list : JSON.stringify(listToSave)},
            success: function(resp){
                console.log('response=',resp);
            }
        });
    };
</script>

Kindly name this as getData.php to process the submission of the list of added data using multiple value insertion approach.

    <?php
    /**
     * Created by PhpStorm.
     * User: SQ05
     * Date: 06/01/2017
     * Time: 07:28 PM
     */
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $data = json_decode(stripslashes($_POST['list'])); //the data here can now be used to create a multiple value insert to ur mysql db.
        print_r(json_encode($data)); // this is used to send response back to ur page if using array buh echo if string
    }

这篇关于将foreach值添加到Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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