Laravel 5.2更新表,使用AJAX重新添加记录而无需重新加载页面

时间:2016-05-26 09:57:13

标签: php jquery ajax laravel

我的问题有点具体......我在Laravel中有一个简单的表单,在某些字段中,我用简单的表格弹出窗口...

我需要实现,当你点击输入字段后面的图标时,弹出窗口会出现,你可以通过AJAX字段插入到表中..这很有效,直到你想看到弹出窗口中新添加的记录..当我想看到它时,我需要重新加载页面并再次打开弹出窗口...

这是我的来源......

这是我的视图

{{ Form::label('department_id', 'Department:') }}
{{ Form::select('department_id', $departments, $emp->department_id, array('placeholder' => 'Choose department ...')) }}

<a href="" id="firePopup_department">
<img src="{{ URL::asset('img/future.png') }}" alt="add_future_fields" title="Add future fields" class="add_future_icon"/>
</a>              

<div id="department_content" title="Departments" style="display:none">   
 <div class="future_field_form">                                                         
  {{ Form::label('dpt_new', 'Department:', array('class' => 'future_field_label')) }}
  {{ Form::select('dpt_new', $departments, null, array('class' => 'future_field_input dpt_new', 'placeholder' => 'Choose department ...')) }} 
  <br />
  {{ Form::label('dpt_from', 'Valid from:', array('class' => 'future_field_label')) }}
  {{ Form::date('dtp_from', null, array('id' => 'from', 'class' => 'future_field_input dpt_from')) }} 
  {{ Form::submit('Save', array('class' => 'future_field_button', 'placeholder' => 'Submit')) }}  
  <br />  
 </div>
 <p class="future_field_msg"></p>

<table class="future_field_table">
  <tr>
    <th>Value</th>
    <th>From</th>
    <th>To</th>  
    <th class="sys_action">Delete</th>  
  </tr> 
 @foreach($future_fields as $ffield) 
  @if($ffield->field_name == 'department_id')     
    <tr>
      <td>{{ $departments->get($ffield->field_value) }}</td>
      <td>{{ $ffield->valid_from }}</td>
      <td>{{ $ffield->valid_to }}</td> 
      <td class="sys_action"><a href="#" title="Delete">delete</a></td> 
   </tr> 
 @endif
@endforeach
</table>
</div>

这是 AJAX 我正在调用(由 .future_field_button 上的事件OnClick触发)

$( ".future_field_button" ).click(function() {  
    var field_value = $('.dpt_new').val();  
    var valid_from = $('.dpt_from').val();
    var field_name = 'department_id';  
    var emp_id = $('.emp_id').val(); 

    //alert(field_name + " => " + field_value + ", " + valid_from + " for: " + emp_id);


    // get real data
    $.ajax({  
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      method: "POST",
      url: '/add_future_field',
      data: { field_value: field_value, 
              valid_from: valid_from, 
              field_name: field_name,  
              emp_id: emp_id, 
             },
      // results on ERROR or SUCCESS 
      error: function(xhr, status, error){
           $('.future_field_msg').css('color','red').text("Error! Contact admin ...");
      },
      success: function(data){
          if(data == 'both_missing'){
            $('.future_field_msg').css('color','red').text("Both fields must be filled!");
          }else{
            $('.future_field_msg').css('color','green').text(" " + data);
          }
      } 
    })
});  

路线非常简单:

Route::post('add_future_field', 'EmployeeController@add_future_field'); 

最后控制器

public function add_future_field(Request $request){ 

         $field_value = $request->input('field_value'); 
         $valid_from = $request->input('valid_from'); 
         $field_name = $request->input('field_name'); 
         $emp_id = $request->input('emp_id');
         $changed_by = Auth::user()->id; 

         if($field_value == '' || $valid_from == '') {
           return "both_missing";
         }else{ 

           // insert data
           $ffield = new FutureField;
           $ffield->employee_id = $emp_id; 
           $ffield->field_name  = $field_name;
           $ffield->field_value = $field_value;
           $ffield->valid_from  = $valid_from;
           $ffield->valid_to    = '3000-01-01';
           $ffield->created_by  = $changed_by;
           $ffield->save();


           // get new actual results  
           $future_fields = array (
                'future_fields' => FutureField::select('id', 'employee_id', 'field_name', 'valid_from', 'valid_from')
                                            ->where('field_name','=', $field_name)         // only selected one   
                                            ->get(),
                );     
           return $future_fields;  
           //return $field_name.";".$field_value.";".$valid_from.";".$emp_id.";".$changed_by;                           
          }   
    }

我无法将最终的$ future_fields(带有新添加的记录)解析到目标表(视图)..你能帮我怎么做吗?我错过了什么?

一切正常,直到获取up2date数据...它们被插入但现在显示在弹出窗口中:(在 future_field_msg (p标签)中我收到[object Object] 绿色信息

谢谢

编辑: 我找到了一个可能的解决方案如何处理它...在成功的ajax请求之后,我将表隐藏在div中并再次使用jquery在同一结构中重建它...但是有更复杂的方法如何实现它?这听起来像一个'讨厌的'解决方法:)我更喜欢干净的解决方案

解决方案(诉@Thomas Van der Veen)

控制器:

return response()->json($future_fields);  

Ajax :(只有成功部分)

 success: function(data){
              if(data == 'both_missing'){
            $('.future_field_msg').css('color','red').text("Both fields must be filled!");
          }else{                    

            // get table body and remove it
            $('#department_content .future_field_table > tbody').empty(); 

            // transform JSON object to JS array
            var future_fields = data.future_fields;

            for (i in future_fields) {

               var future_field = future_fields[i];

               // generate new row content
               var newRowContent = "<tr><td>"+future_field.field_value_display+"</td><td>"+future_field.valid_from+"</td><td>"+future_field.valid_to+"</td><td class=\"sys_action\"><a href=\"#\" title=\"Delete\">x</a></td></tr>";

               $(newRowContent).appendTo($('#department_content .future_field_table > tbody'));                    
            }                                      

            $('.future_field_msg').css('color','green').text(field_value_display+" inserted!");
          }
      } 

但我现在面临的问题是,我无法在laravel中使用默认的{{}} echo函数重新填充表格。我需要生成此

<td class="sys_action">
  <a href="#" title="Delete">
    <img src="{{ URL::asset('img/delete.gif') }}" class="future_field_edit_img" alt="delete" />
  </a>
</td> 

我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

在你的控制器中,你将不得不返回json。

像这样:

return response()->json($future_fields);

Documentation

在你的javascript中,你必须循环这些数据并将它们添加到表中。

示例:

success: function(data)
{

    for (i in data)
    {

        var future_field = data[i];

        // Populate table

    }

}

OP更新后修改

您可以删除旧行并添加新行,而不是重建整个表。

示例:

$table_body = $table.find('tbody');

// Remove all table rows
....

$table_row = $('<tr><td class="somecolumn"></td><td class="othercolumn"></td></tr>');

for (i in future_fields)
{

    var future_field = future_fields[i];

    // Fill table row with desired values
    //
    $table_row.find('.someclumn').html(future_field.somevalue);

    $table_row.find('.otherclumn').html(future_field.othervalue);

    // Append new table row to tbody
    //
    $table_body.append($table_row);

}

此代码尚未经过测试,但应该正常运行(我认为)