重新加载或使用旧输入数据提交表单后,重定向到同一ajax页面

时间:2019-05-26 12:56:45

标签: ajax laravel laravel-5

我有一个带有一些侧面菜单的仪表板。单击每个菜单后,通过ajax调用加载页面。 默认情况下,加载仪表板时会加载页面,还有一个“仪表板”菜单可在其他个人资料(如个人资料和添加学生)之间切换。

但是,如果我在个人资料页面上并且刷新,它将返回到仪表板页面。另外,如果我尝试通过填写表单来添加学生,并且表单有任何错误,它将再次返回到仪表板,所有旧的输入数据都会丢失。

Web.php

Route::prefix('admin')->group(function(){
Route::get('/dashboard','AdminController@dashboard')->name('admin.dashboard');
Route::get('/login', 'Auth\AdminLoginController@showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit');
Route::post('/add_student','AdminController@add_student');

    Route::middleware('ajax')->group(function(){
    Route::get('/summary','AdminController@summary')->name('admin.summary');
    Route::get('/profile', 'AdminController@profile')->name('admin.profile');
    Route::get('/add_student_form','AdminController@add_student_form')->name('admin.add_student');
});

});

AdminController.php

 public function add_student_form(){
    return view('admin.add_student');
}

public function add_student(Request $request)
{
    $this->validate($request,[

        'name'=>'required|string',
        'course_id'=>'required',
        'dob'=>'required|date',
        'gender'=>'required|string',
        'category'=>'required|string',
        'qualification'=>'required|string',
        'fathername'=>'required|string',
        'mothername'=>'required|string',
        'mob_no'=>'required|string|max:10',
        'address'=>'required|string',
        'email'=>'required|email',
        'PIN'=>'required|string|max:6',
    ]);

    $student = new Student;
    $student->name = $request['name'];
    $student->roll_no ='NITTI'.rand(10000,99999);
    $student->password = Hash::make($student['mob']);

    $student->fees = new StudentFees;
    $student->fees->paid_fees = $request['paid_fees'];
    $student->fees->balance_fees = 7000;
    $student->detail = new StudentDetail;
    $student->detail->course_id = $request['course_id'];
    $student->detail->gender = $request['gender'];
    $student->detail->category = $request['category'];
    $student->detail->qualification = $request['qualification'];
    $student->detail->fathername = $request['fathername'];
    $student->detail->mothername = $request['mothername'];
    $student->detail->mob_no = $request['mob_no'];
    $student->detail->email = $request['email'] ;
    $student->detail->address = $request['address'];
    $student->detail->PIN=$request['PIN'];
    $student->detail->dob = $request['dob'];
    $student->push();
    return redirect()->back();

}

add_student.blade.php

  <form action="/admin/add_student" method="POST">
      @csrf
   //It has all the fields here and a submit button
   </form>

dashboard.blade.php

   <div class="container-fluid">
      <div class="row">
         <div class="col-2  sidebar">
            <img src="{{asset('/img/admin.jpg')}}" class="fit-image">
             <p class="text-center">{{Auth::user()->name}}</p>
             <hr>

         <ul class="list-group">
            <li class="list-group-item" id="summary">Dashboard</li>
            <li class="list-group-item" id="admin_profile">Profile
            </li> 
            <li class="list-group-item" id="students">Students <i class="fas fa-angle-right ml-5"></i>
           <ul class="sidenav list-group">
            <li class="list-group-item" id="add_student">Add Student</li>
            <li class="list-group-item" id="viewall">View All </li>
          </ul></li> 
        </ul>
       </div>
         <div class="col-10 dashboard" id="admin">
         </div>
        </div>
         </div>

dashboard.js

    $(document).ready(function(){
      $.ajax({
          url:'/admin/summary',
          type: "GET",
          success: function(data){
            $data = $(data); 

            $('#admin').html($data).fadeIn();    
            }
        });
      });

      $(document).on('click','#summary', function(){
        $.ajax({
            url:'/admin/summary',
            type: "GET",
            success: function(data){
              $data = $(data); 
              $('#admin').html($data).fadeIn();    
              }
          });
        });


    $(document).on('click','#admin_profile', function(){
        $.ajax({
            url:'/admin/profile',
            type: "GET", 
            success: function(data){
              $data = $(data); 
              $('#admin').html($data).fadeIn();    
              }
          });
        });
          $(document).on('click','#add_student', function(){
            $.ajax({
                url:'/admin/add_student_form',
                type: "GET", 
                success: function(data){
                  $data = $(data);  produced
                  $('#admin').html($data).fadeIn();    
                  }
              });
            });

我尝试redirect()->back->withInput('the fields');,但没有成功。 如果有更好的方法可以在重新加载或提交表单后加载包含相同页面的页面,则欢迎您。

1 个答案:

答案 0 :(得分:0)

您可以使用ajax表单发布。

我重写了代码以抽象化ajax负载。

JS:

$(document).ready(function(){
  //load summary by default
  loadPage('summary');

  //load on click menu item
  $(document).on('click','.menu-item', function(){
    loadPage($(this).attr('data-page'));
  });

  //send xcrf token in ajax header
  $.ajaxSetup({
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  });

  //submit form
  $(document).on('submit', 'form', function(){
    let form = $(this);

    $.ajax({
      url: form.attr('action'),
      type: 'POST',
      dataType: 'json',
      success: function(data){
        if(data.page){
            //load page returned in controller
            loadPage(data.page);
        }
      },
      error: function(data){
        if(data.responseJSON && data.responseJSON.errors){
            $.each(data.responseJSON.errors, function(key, value){

                //convert laravel dotted rules to jquery selectors

                key = key.replace('.', '[').replace(/\./g, '][');

                if(key.indexOf('[') !== -1){
                    key += ']';
                }

                //do something with errored elements
                form.find('*[name="' + key + '"]').addClass('error');
            });
        }
      }
    });

    return false;
  });
});

function loadPage(page){
  $.ajax({
    url:'/admin/' + page,
    type: 'GET',
    success: function(data){
      $data = $(data); 
      $('#admin').html($data).fadeIn();    
    }
  });
}

HTML:

添加到<head>

<meta name="csrf-token" content="{{ csrf_token() }}">

更改侧边栏菜单:

<ul class="list-group">
    <li class="list-group-item menu-item" data-page="summary">Dashboard</li>
    <li class="list-group-item menu-item" data-page="profile">Profile</li> 
    <li class="list-group-item" id="students">Students <i class="fas fa-angle-right ml-5"></i>
        <ul class="sidenav list-group">
            <li class="list-group-item menu-item" data-page="add_student_form">Add Student</li>
            <li class="list-group-item menu-item" data-page="viewall">View All </li>
        </ul>
    </li> 
</ul>

控制器方法:

return redirect()->back();替换为return ['page' => 'viewall'];