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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35933222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:23:34  来源:igfitidea点击:

Laravel 5.2 - ajax check if value exists in database

phpjqueryajaxlaravel

提问by Mr.P

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:

这是控制器函数 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() }}"

元名称="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 ..

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

回答by Ohgodwhy

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!');
           }
        } 
    });
});

回答by m2j

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

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

first make sure you have jquery.min.jsin your public folder.

首先确保你jquery.min.js在你的public folder.

Now in blade.phpadd idfor first_name, last_name, and superior as below:

现在blade.php添加idfirst_name、last_name 和上级如下:

<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

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

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

回答by heavymetal91

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

回答by Nonong Re

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