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

时间:2021-07-19 00:04:38

I am creating an employee hierarchy and while setting up the superior for new employee I would like to check if the employee already exists in database ... but :) I would like to do it with AJAX to know it realtime without sending the form ..

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

I have absolutely no idea how to do it, since I am a newbie to Laravel ..

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

                           ***UPDATED BASED ON ADVICES:***

I have a form in add_emp.blade.php:

我在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>

Here is a script in add_employee.blade.php

这是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 for handling the superior:

处理上级的路线:

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

This is the Controller function 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";
        }
}

But still not working ... can you advice where could be the issue?

但仍然没有工作......你能建议问题出在哪里?

                             *** FINAL SOLUTION ***

Form:

<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>

Add to app.blade.php

添加到app.blade.php

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

meta name =“csrf-token”content =“{{csrf_token()}}”

Controller

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 script

最后的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);
                    } 
                  })

        });

This works like a charm :) thank you guys .. hope this will help someone ..

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

4 个解决方案

#1


4  

First make the request.

首先提出要求。

php artisan make:request AjaxUserExistsRequest

Then open the request file (App\Http\Requests) and find the following:

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

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

This is where you would stick your validation rules so you can check against the form elements being submit.

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

Then you should use dependency injection to force your request into the first argument of the user_exists() function:

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

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

This will return nullif no user exists, otherwise we don't care about the response.

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

Finally, of course we need our route.

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

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

Lastly, we'll go ahead and capture the form submit and check if the user exists with our jQuery.

最后,我们将继续捕获表单提交并检查用户是否存在我们的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!');
           }
        } 
    });
});

#2


1  

Give your form an id:

给你的表单一个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>

your js will look like this

你的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...
        }
    });
})  

#3


1  

also add csrf_field in your form to generate token, and use this token while sending request. in your form:

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

 {{ csrf_field() }}

in your ajax request:

在你的ajax请求中:

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

you can also do it with meta teg. in your head teg

你也可以用meta teg来做。在你的脑袋里

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

in your request

在你的请求中

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

#4


1  

The below will give alert message the user already exists! if the first_name exists in your db or it will give alret nothing.(if you want to check with superior change the code vice versa)

以下将给出用户已经存在的警告消息!如果您的数据库中存在first_name,或者它没有任何内容。(如果您想检查上级更改代码,反之亦然)

first make sure you have jquery.min.js in your public folder.

首先确保您的公用文件夹中有jquery.min.js。

Now in blade.php add id for first_name, last_name, and superior as below:

现在在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>

and in your route.php

并在你的route.php

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

in 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);
}

It should work. if it doesn't please show us your error

它应该工作。如果没有,请告诉我们您的错误

#1


4  

First make the request.

首先提出要求。

php artisan make:request AjaxUserExistsRequest

Then open the request file (App\Http\Requests) and find the following:

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

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

This is where you would stick your validation rules so you can check against the form elements being submit.

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

Then you should use dependency injection to force your request into the first argument of the user_exists() function:

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

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

This will return nullif no user exists, otherwise we don't care about the response.

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

Finally, of course we need our route.

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

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

Lastly, we'll go ahead and capture the form submit and check if the user exists with our jQuery.

最后,我们将继续捕获表单提交并检查用户是否存在我们的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!');
           }
        } 
    });
});

#2


1  

Give your form an id:

给你的表单一个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>

your js will look like this

你的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...
        }
    });
})  

#3


1  

also add csrf_field in your form to generate token, and use this token while sending request. in your form:

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

 {{ csrf_field() }}

in your ajax request:

在你的ajax请求中:

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

you can also do it with meta teg. in your head teg

你也可以用meta teg来做。在你的脑袋里

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

in your request

在你的请求中

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

#4


1  

The below will give alert message the user already exists! if the first_name exists in your db or it will give alret nothing.(if you want to check with superior change the code vice versa)

以下将给出用户已经存在的警告消息!如果您的数据库中存在first_name,或者它没有任何内容。(如果您想检查上级更改代码,反之亦然)

first make sure you have jquery.min.js in your public folder.

首先确保您的公用文件夹中有jquery.min.js。

Now in blade.php add id for first_name, last_name, and superior as below:

现在在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>

and in your route.php

并在你的route.php

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

in 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);
}

It should work. if it doesn't please show us your error

它应该工作。如果没有,请告诉我们您的错误