Laravel 5.2 - ajax检查数据库中是否存在值

时间:2016-03-11 05:51:55

标签: php jquery ajax laravel

我正在创建一个员工层次结构,同时为新员工设置上级我想检查员工是否已经存在于数据库中...但是:)我想用AJAX来实现,以便实时了解它而不发送表格..

我完全不知道怎么做,因为我是Laravel的新手..

                           ***UPDATED BASED ON ADVICES:***

我在add_emp.blade.php中有一个表单:

<form action="../create_employee" method="POST">     
    <button class="button" type="submit" style="float:right"><span>Save</span></button>
    <div style="clear:both"></div>
    <fieldset>
      <legend>Personal data</legend>
        <label for="first_name">First name:</label><input type="text" class="add_emp required" name="first_name" value="" /><br />  
        <label for="last_name">Last name:</label><input type="text" class="add_emp required" name="last_name" value="" /><br />
        <label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><br /> 
    </fieldset> 
</form>

这是add_employee.blade.php

中的一个脚本
<script type="text/javascript">
    $('#superior_list').blur(function(){

      var first_name = $('#superior_list');

      $.ajax({
        method: "POST",
        url: '/check_superior',
        data: { superior: superior }
      })
      .done(function( msg ) {
        if(msg == 'exist') {
           //employee exists, do something...
           alert( "good." );
        } else {
          //employee does not exist, do something... 
           alert( "bad." );
       }
      });
    })
</script>

处理上级的路线:

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

这是Controller函数check_superior:

public function check_superior(Request\AjaxUserExistsRequest $request){ 

        if(Employee::where('superior','=',$request->input('superior'))->exists()){
           return "exist";
        }else{                                                                    
           return "not exist";
        }
}

但仍然没有工作......你能告诉我哪里可能是问题吗?

                             *** FINAL SOLUTION ***

表格:

<form action="../create_employee" method="POST">     
    <button class="button" type="submit" style="float:right"><span>Save</span></button>
    <div style="clear:both"></div>
    <fieldset>
      <legend>Personal data</legend>
        <label for="first_name">First name:</label><input type="text" class="add_emp required" name="first_name" value="" /><br />  
        <label for="last_name">Last name:</label><input type="text" class="add_emp required" name="last_name" value="" /><br />
        <label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><span id="check-superior-status"></span><br />
    </fieldset> 
</form>

添加到app.blade.php

meta name =&#34; csrf-token&#34; content =&#34; {{csrf_token()}}&#34;

控制器

public function check_superior(Request $request){ 

            if(Employee::where('first_name','=',$request->input('superior_fname'))
                        ->where('last_name','=',$request->input('superior_lname'))
                        ->exists()){
               return "exist";
            }else{                                                                    
               return "not exist";
            }
    }

final emp.blade.php AJAX脚本

// place data after SEPERIOR selection
        $( "#superior_list" ).blur(function() {

                  var sup_list = $(this).val();
                  var sup_arr = sup_list.split(' ');
                  var superior_fname = sup_arr[0];  
                  var superior_lname = sup_arr[1];
                  var superior = superior_fname+" "+superior_lname;

                  // control print out
                  //$('#check-superior-status').text(superior);

                  // get real data 
                  $.ajax({  
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    method: "POST",
                    url: '/check_superior',
                    data: { superior_fname: superior_fname, superior_lname: superior_lname },
                    /* // debug only 
                    error: function(xhr, status, error){
                        $('#check-superior-status').text(xhr.responseText);
                    },
                    */
                    success: function(data){
                        $('#check-superior-status').text(data);
                    } 
                  })

        });

这就像一个魅力:)谢谢你们..希望这会帮助别人..

4 个答案:

答案 0 :(得分:4)

首先提出请求。

php artisan make:request AjaxUserExistsRequest

然后打开请求文件(App \ Http \ Requests)并找到以下内容:

public function validate(){
    return [
        //rules
    ];
}

这是您坚持验证规则的地方,以便您可以检查正在提交的表单元素。

然后你应该使用依赖注入来强制你的请求进入user_exists()函数的第一个参数:

public function user_exists(Requests\AjaxUserExistsRequest $request){
    return User::where('first_name', $request->first_name)->first();
}

如果没有用户,这将返回null,否则我们不关心响应。

最后,我们当然需要我们的路线。

Route::post('employee_exists', 'EmployeeController@user_exists');

最后,我们将继续捕获表单提交并检查用户是否存在我们的jQuery。

$('#employee_form').submit(function(e){
    e.preventDefault();

    var first_name = $('#first_name').val(),
        $this = this; //aliased so we can use in ajax success function

    $.ajax({
        type: 'POST',
        url: '/employee_exists',
        data: {first_name: first_name},
        success: function(data){
           if(data == null){
               //then submit the form for real
               $this.submit; //doesn't fire our jQuery's submit() function
           } else {
               //show some type of message to the user
               alert('That user already exists!');
           }
        } 
    });
});

答案 1 :(得分:1)

给你的表单一个id:

<form action="../create_employee" method="POST" id="employee_form">     
    <button class="button" type="submit" style="float:right"><span>Save</span></button>
    <div style="clear:both"></div>
    <fieldset>
      <legend>Personal data</legend>
        <label for="first_name">First name:</label><input type="text" class="add_emp required" name="first_name" id="first_name" value="" /><br />  
        <label for="last_name">Last name:</label><input type="text" class="add_emp required" name="last_name" value="" /><br />
        <label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><br /> 
    </fieldset> 
</form>

您的js将如下所示

$('#employee_form').submit(function(e){
    e.preventDefault();
    var first_name = $('#first_name');
    $.ajax({
        method: "POST",
        url: "checkUserExistence.php",
        data: { first_name: first_name }
    })
    .done(function( msg ) {
        if(msg == 'exist') {
            //employee exists, do something...
        } else {
            //employee does not exist, do something...
        }
    });
})  

答案 2 :(得分:1)

如果您的数据库中存在the user already exists!,则下面会给出警告消息first_name,或者它会给出nothing。(如果您想检查更高的代码,反之亦然)

首先确保jquery.min.js中有public folder

现在在blade.php为first_name,last_name和superior添加id,如下所示:

<form action="../create_employee" method="POST">     
    <button class="button" type="submit" style="float:right"><span>Save</span></button>
    <div style="clear:both"></div>
    <fieldset>
      <legend>Personal data</legend>
        <label for="first_name">First name:</label><input type="text" id="first_name" class="add_emp required" name="first_name" value="" /><br />  
        <label for="last_name">Last name:</label><input type="text" id="last_name" class="add_emp required" name="last_name" value="" /><br />
        <label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><br /> 
    </fieldset> 
</form>

<script>
$(document).ready(function(){
    $("#superior_list").blur(function(){
        var first_name = $('#first_name').val();
        var last_name = $('#last_name').val();
        var superior = $('#superior_list').val();                

        $.ajax({
                type: 'POST',
                url: '/check_superior',
                data: {first_name: first_name, last_name: last_name, superior: superior},
                success: function(data){
                   if(data == 0){
                       alert('nothing');
                   } else {
                       alert('the user already exists!');
                   }
                } 
            });

    });
});
</script>

并在route.php

Route::post('/check_superior', array('as' => '', 'uses' => 'EmployeeController@check_superior'));
EmployeeController.php

中的

public function check_superior(){
    // can get last_name, superior like first_name below
    $first_name = Input::get('first_name');
    $data = YourModel::where('first_name',$first_name)->get();
    return count($data);
}

它应该工作。如果它没有向我们展示您的error

答案 3 :(得分:1)

还在表单中添加csrf_field以生成令牌,并在发送请求时使用此令牌。 在你的形式:

 {{ csrf_field() }}
你的ajax请求中的

$.ajax({
        headers: {'X-CSRF-Token': $('input[name="_token"]').val()},
        //other data....        
 })

你也可以用meta teg来做。在你的头脑中

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

在您的请求中

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content');
         //other data...
    }
});